##// END OF EJS Templates
core: added more accurate time measurement for called functions
marcink -
r3853:5f8c0244 default
parent child Browse files
Show More
@@ -1,154 +1,154 b''
1 """
1 """
2 gunicorn config extension and hooks. Sets additional configuration that is
2 gunicorn config extension and hooks. Sets additional configuration that is
3 available post the .ini config.
3 available post the .ini config.
4
4
5 - workers = ${cpu_number}
5 - workers = ${cpu_number}
6 - threads = 1
6 - threads = 1
7 - proc_name = ${gunicorn_proc_name}
7 - proc_name = ${gunicorn_proc_name}
8 - worker_class = sync
8 - worker_class = sync
9 - worker_connections = 10
9 - worker_connections = 10
10 - max_requests = 1000
10 - max_requests = 1000
11 - max_requests_jitter = 30
11 - max_requests_jitter = 30
12 - timeout = 21600
12 - timeout = 21600
13
13
14 """
14 """
15
15
16 import multiprocessing
16 import multiprocessing
17 import sys
17 import sys
18 import time
18 import time
19 import datetime
19 import datetime
20 import threading
20 import threading
21 import traceback
21 import traceback
22 from gunicorn.glogging import Logger
22 from gunicorn.glogging import Logger
23
23
24
24
25 # GLOBAL
25 # GLOBAL
26 errorlog = '-'
26 errorlog = '-'
27 accesslog = '-'
27 accesslog = '-'
28 loglevel = 'debug'
28 loglevel = 'debug'
29
29
30 # SECURITY
30 # SECURITY
31
31
32 # The maximum size of HTTP request line in bytes.
32 # The maximum size of HTTP request line in bytes.
33 # 0 for unlimited
33 # 0 for unlimited
34 limit_request_line = 0
34 limit_request_line = 0
35
35
36 # Limit the number of HTTP headers fields in a request.
36 # Limit the number of HTTP headers fields in a request.
37 # By default this value is 100 and can’t be larger than 32768.
37 # By default this value is 100 and can’t be larger than 32768.
38 limit_request_fields = 10240
38 limit_request_fields = 10240
39
39
40 # Limit the allowed size of an HTTP request header field.
40 # Limit the allowed size of an HTTP request header field.
41 # Value is a positive number or 0.
41 # Value is a positive number or 0.
42 # Setting it to 0 will allow unlimited header field sizes.
42 # Setting it to 0 will allow unlimited header field sizes.
43 limit_request_field_size = 0
43 limit_request_field_size = 0
44
44
45
45
46 # Timeout for graceful workers restart.
46 # Timeout for graceful workers restart.
47 # After receiving a restart signal, workers have this much time to finish
47 # After receiving a restart signal, workers have this much time to finish
48 # serving requests. Workers still alive after the timeout (starting from the
48 # serving requests. Workers still alive after the timeout (starting from the
49 # receipt of the restart signal) are force killed.
49 # receipt of the restart signal) are force killed.
50 graceful_timeout = 30
50 graceful_timeout = 30
51
51
52
52
53 # The number of seconds to wait for requests on a Keep-Alive connection.
53 # The number of seconds to wait for requests on a Keep-Alive connection.
54 # Generally set in the 1-5 seconds range.
54 # Generally set in the 1-5 seconds range.
55 keepalive = 2
55 keepalive = 2
56
56
57
57
58 # SERVER MECHANICS
58 # SERVER MECHANICS
59 # None == system temp dir
59 # None == system temp dir
60 # worker_tmp_dir is recommended to be set to some tmpfs
60 # worker_tmp_dir is recommended to be set to some tmpfs
61 worker_tmp_dir = None
61 worker_tmp_dir = None
62 tmp_upload_dir = None
62 tmp_upload_dir = None
63
63
64 # Custom log format
64 # Custom log format
65 access_log_format = (
65 access_log_format = (
66 '%(t)s [%(p)-8s] GNCRN %(h)-15s rqt:%(L)s %(s)s %(b)-6s "%(m)s:%(U)s %(q)s" usr:%(u)s "%(f)s" "%(a)s"')
66 '%(t)s [%(p)-8s] GNCRN %(h)-15s rqt:%(L)s %(s)s %(b)-6s "%(m)s:%(U)s %(q)s" usr:%(u)s "%(f)s" "%(a)s"')
67
67
68 # self adjust workers based on CPU count
68 # self adjust workers based on CPU count
69 # workers = multiprocessing.cpu_count() * 2 + 1
69 # workers = multiprocessing.cpu_count() * 2 + 1
70
70
71
71
72 def post_fork(server, worker):
72 def post_fork(server, worker):
73 server.log.info("[<%-10s>] WORKER spawned", worker.pid)
73 server.log.info("[<%-10s>] WORKER spawned", worker.pid)
74
74
75
75
76 def pre_fork(server, worker):
76 def pre_fork(server, worker):
77 pass
77 pass
78
78
79
79
80 def pre_exec(server):
80 def pre_exec(server):
81 server.log.info("Forked child, re-executing.")
81 server.log.info("Forked child, re-executing.")
82
82
83
83
84 def on_starting(server):
84 def on_starting(server):
85 server.log.info("Server is starting.")
85 server.log.info("Server is starting.")
86
86
87
87
88 def when_ready(server):
88 def when_ready(server):
89 server.log.info("Server is ready. Spawning workers")
89 server.log.info("Server is ready. Spawning workers")
90
90
91
91
92 def on_reload(server):
92 def on_reload(server):
93 pass
93 pass
94
94
95
95
96 def worker_int(worker):
96 def worker_int(worker):
97 worker.log.info("[<%-10s>] worker received INT or QUIT signal", worker.pid)
97 worker.log.info("[<%-10s>] worker received INT or QUIT signal", worker.pid)
98
98
99 # get traceback info, on worker crash
99 # get traceback info, on worker crash
100 id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
100 id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
101 code = []
101 code = []
102 for thread_id, stack in sys._current_frames().items():
102 for thread_id, stack in sys._current_frames().items():
103 code.append(
103 code.append(
104 "\n# Thread: %s(%d)" % (id2name.get(thread_id, ""), thread_id))
104 "\n# Thread: %s(%d)" % (id2name.get(thread_id, ""), thread_id))
105 for fname, lineno, name, line in traceback.extract_stack(stack):
105 for fname, lineno, name, line in traceback.extract_stack(stack):
106 code.append('File: "%s", line %d, in %s' % (fname, lineno, name))
106 code.append('File: "%s", line %d, in %s' % (fname, lineno, name))
107 if line:
107 if line:
108 code.append(" %s" % (line.strip()))
108 code.append(" %s" % (line.strip()))
109 worker.log.debug("\n".join(code))
109 worker.log.debug("\n".join(code))
110
110
111
111
112 def worker_abort(worker):
112 def worker_abort(worker):
113 worker.log.info("[<%-10s>] worker received SIGABRT signal", worker.pid)
113 worker.log.info("[<%-10s>] worker received SIGABRT signal", worker.pid)
114
114
115
115
116 def worker_exit(server, worker):
116 def worker_exit(server, worker):
117 worker.log.info("[<%-10s>] worker exit", worker.pid)
117 worker.log.info("[<%-10s>] worker exit", worker.pid)
118
118
119
119
120 def child_exit(server, worker):
120 def child_exit(server, worker):
121 worker.log.info("[<%-10s>] worker child exit", worker.pid)
121 worker.log.info("[<%-10s>] worker child exit", worker.pid)
122
122
123
123
124 def pre_request(worker, req):
124 def pre_request(worker, req):
125 worker.start_time = time.time()
125 worker.start_time = time.time()
126 worker.log.debug(
126 worker.log.debug(
127 "GNCRN PRE WORKER [cnt:%s]: %s %s", worker.nr, req.method, req.path)
127 "GNCRN PRE WORKER [cnt:%s]: %s %s", worker.nr, req.method, req.path)
128
128
129
129
130 def post_request(worker, req, environ, resp):
130 def post_request(worker, req, environ, resp):
131 total_time = time.time() - worker.start_time
131 total_time = time.time() - worker.start_time
132 worker.log.debug(
132 worker.log.debug(
133 "GNCRN POST WORKER [cnt:%s]: %s %s resp: %s, Load Time: %.3fs",
133 "GNCRN POST WORKER [cnt:%s]: %s %s resp: %s, Load Time: %.4fs",
134 worker.nr, req.method, req.path, resp.status_code, total_time)
134 worker.nr, req.method, req.path, resp.status_code, total_time)
135
135
136
136
137 class RhodeCodeLogger(Logger):
137 class RhodeCodeLogger(Logger):
138 """
138 """
139 Custom Logger that allows some customization that gunicorn doesn't allow
139 Custom Logger that allows some customization that gunicorn doesn't allow
140 """
140 """
141
141
142 datefmt = r"%Y-%m-%d %H:%M:%S"
142 datefmt = r"%Y-%m-%d %H:%M:%S"
143
143
144 def __init__(self, cfg):
144 def __init__(self, cfg):
145 Logger.__init__(self, cfg)
145 Logger.__init__(self, cfg)
146
146
147 def now(self):
147 def now(self):
148 """ return date in RhodeCode Log format """
148 """ return date in RhodeCode Log format """
149 now = time.time()
149 now = time.time()
150 msecs = int((now - long(now)) * 1000)
150 msecs = int((now - long(now)) * 1000)
151 return time.strftime(self.datefmt, time.localtime(now)) + '.{0:03d}'.format(msecs)
151 return time.strftime(self.datefmt, time.localtime(now)) + '.{0:03d}'.format(msecs)
152
152
153
153
154 logger_class = RhodeCodeLogger
154 logger_class = RhodeCodeLogger
@@ -1,112 +1,112 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2019 RhodeCode GmbH
3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21
21
22 import logging
22 import logging
23
23
24 from rhodecode.api import jsonrpc_method
24 from rhodecode.api import jsonrpc_method
25 from rhodecode.api.exc import JSONRPCValidationError
25 from rhodecode.api.exc import JSONRPCValidationError
26 from rhodecode.api.utils import Optional
26 from rhodecode.api.utils import Optional
27 from rhodecode.lib.index import searcher_from_config
27 from rhodecode.lib.index import searcher_from_config
28 from rhodecode.model import validation_schema
28 from rhodecode.model import validation_schema
29 from rhodecode.model.validation_schema.schemas import search_schema
29 from rhodecode.model.validation_schema.schemas import search_schema
30
30
31 log = logging.getLogger(__name__)
31 log = logging.getLogger(__name__)
32
32
33
33
34 @jsonrpc_method()
34 @jsonrpc_method()
35 def search(request, apiuser, search_query, search_type, page_limit=Optional(10),
35 def search(request, apiuser, search_query, search_type, page_limit=Optional(10),
36 page=Optional(1), search_sort=Optional('newfirst'),
36 page=Optional(1), search_sort=Optional('newfirst'),
37 repo_name=Optional(None), repo_group_name=Optional(None)):
37 repo_name=Optional(None), repo_group_name=Optional(None)):
38 """
38 """
39 Fetch Full Text Search results using API.
39 Fetch Full Text Search results using API.
40
40
41 :param apiuser: This is filled automatically from the |authtoken|.
41 :param apiuser: This is filled automatically from the |authtoken|.
42 :type apiuser: AuthUser
42 :type apiuser: AuthUser
43 :param search_query: Search query.
43 :param search_query: Search query.
44 :type search_query: str
44 :type search_query: str
45 :param search_type: Search type. The following are valid options:
45 :param search_type: Search type. The following are valid options:
46 * commit
46 * commit
47 * content
47 * content
48 * path
48 * path
49 :type search_type: str
49 :type search_type: str
50 :param page_limit: Page item limit, from 1 to 500. Default 10 items.
50 :param page_limit: Page item limit, from 1 to 500. Default 10 items.
51 :type page_limit: Optional(int)
51 :type page_limit: Optional(int)
52 :param page: Page number. Default first page.
52 :param page: Page number. Default first page.
53 :type page: Optional(int)
53 :type page: Optional(int)
54 :param search_sort: Search sort order. Default newfirst. The following are valid options:
54 :param search_sort: Search sort order. Default newfirst. The following are valid options:
55 * newfirst
55 * newfirst
56 * oldfirst
56 * oldfirst
57 :type search_sort: Optional(str)
57 :type search_sort: Optional(str)
58 :param repo_name: Filter by one repo. Default is all.
58 :param repo_name: Filter by one repo. Default is all.
59 :type repo_name: Optional(str)
59 :type repo_name: Optional(str)
60 :param repo_group_name: Filter by one repo group. Default is all.
60 :param repo_group_name: Filter by one repo group. Default is all.
61 :type repo_group_name: Optional(str)
61 :type repo_group_name: Optional(str)
62 """
62 """
63
63
64 data = {'execution_time': ''}
64 data = {'execution_time': ''}
65 repo_name = Optional.extract(repo_name)
65 repo_name = Optional.extract(repo_name)
66 repo_group_name = Optional.extract(repo_group_name)
66 repo_group_name = Optional.extract(repo_group_name)
67
67
68 schema = search_schema.SearchParamsSchema()
68 schema = search_schema.SearchParamsSchema()
69
69
70 try:
70 try:
71 search_params = schema.deserialize(
71 search_params = schema.deserialize(
72 dict(search_query=search_query,
72 dict(search_query=search_query,
73 search_type=search_type,
73 search_type=search_type,
74 search_sort=Optional.extract(search_sort),
74 search_sort=Optional.extract(search_sort),
75 page_limit=Optional.extract(page_limit),
75 page_limit=Optional.extract(page_limit),
76 requested_page=Optional.extract(page))
76 requested_page=Optional.extract(page))
77 )
77 )
78 except validation_schema.Invalid as err:
78 except validation_schema.Invalid as err:
79 raise JSONRPCValidationError(colander_exc=err)
79 raise JSONRPCValidationError(colander_exc=err)
80
80
81 search_query = search_params.get('search_query')
81 search_query = search_params.get('search_query')
82 search_type = search_params.get('search_type')
82 search_type = search_params.get('search_type')
83 search_sort = search_params.get('search_sort')
83 search_sort = search_params.get('search_sort')
84
84
85 if search_params.get('search_query'):
85 if search_params.get('search_query'):
86 page_limit = search_params['page_limit']
86 page_limit = search_params['page_limit']
87 requested_page = search_params['requested_page']
87 requested_page = search_params['requested_page']
88
88
89 searcher = searcher_from_config(request.registry.settings)
89 searcher = searcher_from_config(request.registry.settings)
90
90
91 try:
91 try:
92 search_result = searcher.search(
92 search_result = searcher.search(
93 search_query, search_type, apiuser, repo_name, repo_group_name,
93 search_query, search_type, apiuser, repo_name, repo_group_name,
94 requested_page=requested_page, page_limit=page_limit, sort=search_sort)
94 requested_page=requested_page, page_limit=page_limit, sort=search_sort)
95
95
96 data.update(dict(
96 data.update(dict(
97 results=list(search_result['results']), page=requested_page,
97 results=list(search_result['results']), page=requested_page,
98 item_count=search_result['count'],
98 item_count=search_result['count'],
99 items_per_page=page_limit))
99 items_per_page=page_limit))
100 finally:
100 finally:
101 searcher.cleanup()
101 searcher.cleanup()
102
102
103 if not search_result['error']:
103 if not search_result['error']:
104 data['execution_time'] = '%s results (%.3f seconds)' % (
104 data['execution_time'] = '%s results (%.4f seconds)' % (
105 search_result['count'],
105 search_result['count'],
106 search_result['runtime'])
106 search_result['runtime'])
107 else:
107 else:
108 node = schema['search_query']
108 node = schema['search_query']
109 raise JSONRPCValidationError(
109 raise JSONRPCValidationError(
110 colander_exc=validation_schema.Invalid(node, search_result['error']))
110 colander_exc=validation_schema.Invalid(node, search_result['error']))
111
111
112 return data
112 return data
@@ -1,242 +1,242 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2017-2019 RhodeCode GmbH
3 # Copyright (C) 2017-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 import pytz
20 import pytz
21 import logging
21 import logging
22
22
23 from pyramid.view import view_config
23 from pyramid.view import view_config
24 from pyramid.response import Response
24 from pyramid.response import Response
25 from webhelpers.feedgenerator import Rss201rev2Feed, Atom1Feed
25 from webhelpers.feedgenerator import Rss201rev2Feed, Atom1Feed
26
26
27 from rhodecode.apps._base import RepoAppView
27 from rhodecode.apps._base import RepoAppView
28 from rhodecode.lib import audit_logger
28 from rhodecode.lib import audit_logger
29 from rhodecode.lib import rc_cache
29 from rhodecode.lib import rc_cache
30 from rhodecode.lib import helpers as h
30 from rhodecode.lib import helpers as h
31 from rhodecode.lib.auth import (
31 from rhodecode.lib.auth import (
32 LoginRequired, HasRepoPermissionAnyDecorator)
32 LoginRequired, HasRepoPermissionAnyDecorator)
33 from rhodecode.lib.diffs import DiffProcessor, LimitedDiffContainer
33 from rhodecode.lib.diffs import DiffProcessor, LimitedDiffContainer
34 from rhodecode.lib.utils2 import str2bool, safe_int, md5_safe
34 from rhodecode.lib.utils2 import str2bool, safe_int, md5_safe
35 from rhodecode.model.db import UserApiKeys, CacheKey
35 from rhodecode.model.db import UserApiKeys, CacheKey
36
36
37 log = logging.getLogger(__name__)
37 log = logging.getLogger(__name__)
38
38
39
39
40 class RepoFeedView(RepoAppView):
40 class RepoFeedView(RepoAppView):
41 def load_default_context(self):
41 def load_default_context(self):
42 c = self._get_local_tmpl_context()
42 c = self._get_local_tmpl_context()
43 self._load_defaults()
43 self._load_defaults()
44 return c
44 return c
45
45
46 def _get_config(self):
46 def _get_config(self):
47 import rhodecode
47 import rhodecode
48 config = rhodecode.CONFIG
48 config = rhodecode.CONFIG
49
49
50 return {
50 return {
51 'language': 'en-us',
51 'language': 'en-us',
52 'feed_ttl': '5', # TTL of feed,
52 'feed_ttl': '5', # TTL of feed,
53 'feed_include_diff':
53 'feed_include_diff':
54 str2bool(config.get('rss_include_diff', False)),
54 str2bool(config.get('rss_include_diff', False)),
55 'feed_items_per_page':
55 'feed_items_per_page':
56 safe_int(config.get('rss_items_per_page', 20)),
56 safe_int(config.get('rss_items_per_page', 20)),
57 'feed_diff_limit':
57 'feed_diff_limit':
58 # we need to protect from parsing huge diffs here other way
58 # we need to protect from parsing huge diffs here other way
59 # we can kill the server
59 # we can kill the server
60 safe_int(config.get('rss_cut_off_limit', 32 * 1024)),
60 safe_int(config.get('rss_cut_off_limit', 32 * 1024)),
61 }
61 }
62
62
63 def _load_defaults(self):
63 def _load_defaults(self):
64 _ = self.request.translate
64 _ = self.request.translate
65 config = self._get_config()
65 config = self._get_config()
66 # common values for feeds
66 # common values for feeds
67 self.description = _('Changes on %s repository')
67 self.description = _('Changes on %s repository')
68 self.title = self.title = _('%s %s feed') % (self.db_repo_name, '%s')
68 self.title = self.title = _('%s %s feed') % (self.db_repo_name, '%s')
69 self.language = config["language"]
69 self.language = config["language"]
70 self.ttl = config["feed_ttl"]
70 self.ttl = config["feed_ttl"]
71 self.feed_include_diff = config['feed_include_diff']
71 self.feed_include_diff = config['feed_include_diff']
72 self.feed_diff_limit = config['feed_diff_limit']
72 self.feed_diff_limit = config['feed_diff_limit']
73 self.feed_items_per_page = config['feed_items_per_page']
73 self.feed_items_per_page = config['feed_items_per_page']
74
74
75 def _changes(self, commit):
75 def _changes(self, commit):
76 diff_processor = DiffProcessor(
76 diff_processor = DiffProcessor(
77 commit.diff(), diff_limit=self.feed_diff_limit)
77 commit.diff(), diff_limit=self.feed_diff_limit)
78 _parsed = diff_processor.prepare(inline_diff=False)
78 _parsed = diff_processor.prepare(inline_diff=False)
79 limited_diff = isinstance(_parsed, LimitedDiffContainer)
79 limited_diff = isinstance(_parsed, LimitedDiffContainer)
80
80
81 return diff_processor, _parsed, limited_diff
81 return diff_processor, _parsed, limited_diff
82
82
83 def _get_title(self, commit):
83 def _get_title(self, commit):
84 return h.shorter(commit.message, 160)
84 return h.shorter(commit.message, 160)
85
85
86 def _get_description(self, commit):
86 def _get_description(self, commit):
87 _renderer = self.request.get_partial_renderer(
87 _renderer = self.request.get_partial_renderer(
88 'rhodecode:templates/feed/atom_feed_entry.mako')
88 'rhodecode:templates/feed/atom_feed_entry.mako')
89 diff_processor, parsed_diff, limited_diff = self._changes(commit)
89 diff_processor, parsed_diff, limited_diff = self._changes(commit)
90 filtered_parsed_diff, has_hidden_changes = self.path_filter.filter_patchset(parsed_diff)
90 filtered_parsed_diff, has_hidden_changes = self.path_filter.filter_patchset(parsed_diff)
91 return _renderer(
91 return _renderer(
92 'body',
92 'body',
93 commit=commit,
93 commit=commit,
94 parsed_diff=filtered_parsed_diff,
94 parsed_diff=filtered_parsed_diff,
95 limited_diff=limited_diff,
95 limited_diff=limited_diff,
96 feed_include_diff=self.feed_include_diff,
96 feed_include_diff=self.feed_include_diff,
97 diff_processor=diff_processor,
97 diff_processor=diff_processor,
98 has_hidden_changes=has_hidden_changes
98 has_hidden_changes=has_hidden_changes
99 )
99 )
100
100
101 def _set_timezone(self, date, tzinfo=pytz.utc):
101 def _set_timezone(self, date, tzinfo=pytz.utc):
102 if not getattr(date, "tzinfo", None):
102 if not getattr(date, "tzinfo", None):
103 date.replace(tzinfo=tzinfo)
103 date.replace(tzinfo=tzinfo)
104 return date
104 return date
105
105
106 def _get_commits(self):
106 def _get_commits(self):
107 return list(self.rhodecode_vcs_repo[-self.feed_items_per_page:])
107 return list(self.rhodecode_vcs_repo[-self.feed_items_per_page:])
108
108
109 def uid(self, repo_id, commit_id):
109 def uid(self, repo_id, commit_id):
110 return '{}:{}'.format(md5_safe(repo_id), md5_safe(commit_id))
110 return '{}:{}'.format(md5_safe(repo_id), md5_safe(commit_id))
111
111
112 @LoginRequired(auth_token_access=[UserApiKeys.ROLE_FEED])
112 @LoginRequired(auth_token_access=[UserApiKeys.ROLE_FEED])
113 @HasRepoPermissionAnyDecorator(
113 @HasRepoPermissionAnyDecorator(
114 'repository.read', 'repository.write', 'repository.admin')
114 'repository.read', 'repository.write', 'repository.admin')
115 @view_config(
115 @view_config(
116 route_name='atom_feed_home', request_method='GET',
116 route_name='atom_feed_home', request_method='GET',
117 renderer=None)
117 renderer=None)
118 @view_config(
118 @view_config(
119 route_name='atom_feed_home_old', request_method='GET',
119 route_name='atom_feed_home_old', request_method='GET',
120 renderer=None)
120 renderer=None)
121 def atom(self):
121 def atom(self):
122 """
122 """
123 Produce an atom-1.0 feed via feedgenerator module
123 Produce an atom-1.0 feed via feedgenerator module
124 """
124 """
125 self.load_default_context()
125 self.load_default_context()
126
126
127 cache_namespace_uid = 'cache_repo_instance.{}_{}'.format(
127 cache_namespace_uid = 'cache_repo_instance.{}_{}'.format(
128 self.db_repo.repo_id, CacheKey.CACHE_TYPE_FEED)
128 self.db_repo.repo_id, CacheKey.CACHE_TYPE_FEED)
129 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
129 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
130 repo_id=self.db_repo.repo_id)
130 repo_id=self.db_repo.repo_id)
131
131
132 region = rc_cache.get_or_create_region('cache_repo_longterm',
132 region = rc_cache.get_or_create_region('cache_repo_longterm',
133 cache_namespace_uid)
133 cache_namespace_uid)
134
134
135 condition = not self.path_filter.is_enabled
135 condition = not self.path_filter.is_enabled
136
136
137 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
137 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
138 condition=condition)
138 condition=condition)
139 def generate_atom_feed(repo_id, _repo_name, _feed_type):
139 def generate_atom_feed(repo_id, _repo_name, _feed_type):
140 feed = Atom1Feed(
140 feed = Atom1Feed(
141 title=self.title % _repo_name,
141 title=self.title % _repo_name,
142 link=h.route_url('repo_summary', repo_name=_repo_name),
142 link=h.route_url('repo_summary', repo_name=_repo_name),
143 description=self.description % _repo_name,
143 description=self.description % _repo_name,
144 language=self.language,
144 language=self.language,
145 ttl=self.ttl
145 ttl=self.ttl
146 )
146 )
147
147
148 for commit in reversed(self._get_commits()):
148 for commit in reversed(self._get_commits()):
149 date = self._set_timezone(commit.date)
149 date = self._set_timezone(commit.date)
150 feed.add_item(
150 feed.add_item(
151 unique_id=self.uid(repo_id, commit.raw_id),
151 unique_id=self.uid(repo_id, commit.raw_id),
152 title=self._get_title(commit),
152 title=self._get_title(commit),
153 author_name=commit.author,
153 author_name=commit.author,
154 description=self._get_description(commit),
154 description=self._get_description(commit),
155 link=h.route_url(
155 link=h.route_url(
156 'repo_commit', repo_name=_repo_name,
156 'repo_commit', repo_name=_repo_name,
157 commit_id=commit.raw_id),
157 commit_id=commit.raw_id),
158 pubdate=date,)
158 pubdate=date,)
159
159
160 return feed.mime_type, feed.writeString('utf-8')
160 return feed.mime_type, feed.writeString('utf-8')
161
161
162 inv_context_manager = rc_cache.InvalidationContext(
162 inv_context_manager = rc_cache.InvalidationContext(
163 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace)
163 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace)
164 with inv_context_manager as invalidation_context:
164 with inv_context_manager as invalidation_context:
165 args = (self.db_repo.repo_id, self.db_repo.repo_name, 'atom',)
165 args = (self.db_repo.repo_id, self.db_repo.repo_name, 'atom',)
166 # re-compute and store cache if we get invalidate signal
166 # re-compute and store cache if we get invalidate signal
167 if invalidation_context.should_invalidate():
167 if invalidation_context.should_invalidate():
168 mime_type, feed = generate_atom_feed.refresh(*args)
168 mime_type, feed = generate_atom_feed.refresh(*args)
169 else:
169 else:
170 mime_type, feed = generate_atom_feed(*args)
170 mime_type, feed = generate_atom_feed(*args)
171
171
172 log.debug('Repo ATOM feed computed in %.3fs',
172 log.debug('Repo ATOM feed computed in %.4fs',
173 inv_context_manager.compute_time)
173 inv_context_manager.compute_time)
174
174
175 response = Response(feed)
175 response = Response(feed)
176 response.content_type = mime_type
176 response.content_type = mime_type
177 return response
177 return response
178
178
179 @LoginRequired(auth_token_access=[UserApiKeys.ROLE_FEED])
179 @LoginRequired(auth_token_access=[UserApiKeys.ROLE_FEED])
180 @HasRepoPermissionAnyDecorator(
180 @HasRepoPermissionAnyDecorator(
181 'repository.read', 'repository.write', 'repository.admin')
181 'repository.read', 'repository.write', 'repository.admin')
182 @view_config(
182 @view_config(
183 route_name='rss_feed_home', request_method='GET',
183 route_name='rss_feed_home', request_method='GET',
184 renderer=None)
184 renderer=None)
185 @view_config(
185 @view_config(
186 route_name='rss_feed_home_old', request_method='GET',
186 route_name='rss_feed_home_old', request_method='GET',
187 renderer=None)
187 renderer=None)
188 def rss(self):
188 def rss(self):
189 """
189 """
190 Produce an rss2 feed via feedgenerator module
190 Produce an rss2 feed via feedgenerator module
191 """
191 """
192 self.load_default_context()
192 self.load_default_context()
193
193
194 cache_namespace_uid = 'cache_repo_instance.{}_{}'.format(
194 cache_namespace_uid = 'cache_repo_instance.{}_{}'.format(
195 self.db_repo.repo_id, CacheKey.CACHE_TYPE_FEED)
195 self.db_repo.repo_id, CacheKey.CACHE_TYPE_FEED)
196 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
196 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
197 repo_id=self.db_repo.repo_id)
197 repo_id=self.db_repo.repo_id)
198 region = rc_cache.get_or_create_region('cache_repo_longterm',
198 region = rc_cache.get_or_create_region('cache_repo_longterm',
199 cache_namespace_uid)
199 cache_namespace_uid)
200
200
201 condition = not self.path_filter.is_enabled
201 condition = not self.path_filter.is_enabled
202
202
203 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
203 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
204 condition=condition)
204 condition=condition)
205 def generate_rss_feed(repo_id, _repo_name, _feed_type):
205 def generate_rss_feed(repo_id, _repo_name, _feed_type):
206 feed = Rss201rev2Feed(
206 feed = Rss201rev2Feed(
207 title=self.title % _repo_name,
207 title=self.title % _repo_name,
208 link=h.route_url('repo_summary', repo_name=_repo_name),
208 link=h.route_url('repo_summary', repo_name=_repo_name),
209 description=self.description % _repo_name,
209 description=self.description % _repo_name,
210 language=self.language,
210 language=self.language,
211 ttl=self.ttl
211 ttl=self.ttl
212 )
212 )
213
213
214 for commit in reversed(self._get_commits()):
214 for commit in reversed(self._get_commits()):
215 date = self._set_timezone(commit.date)
215 date = self._set_timezone(commit.date)
216 feed.add_item(
216 feed.add_item(
217 unique_id=self.uid(repo_id, commit.raw_id),
217 unique_id=self.uid(repo_id, commit.raw_id),
218 title=self._get_title(commit),
218 title=self._get_title(commit),
219 author_name=commit.author,
219 author_name=commit.author,
220 description=self._get_description(commit),
220 description=self._get_description(commit),
221 link=h.route_url(
221 link=h.route_url(
222 'repo_commit', repo_name=_repo_name,
222 'repo_commit', repo_name=_repo_name,
223 commit_id=commit.raw_id),
223 commit_id=commit.raw_id),
224 pubdate=date,)
224 pubdate=date,)
225
225
226 return feed.mime_type, feed.writeString('utf-8')
226 return feed.mime_type, feed.writeString('utf-8')
227
227
228 inv_context_manager = rc_cache.InvalidationContext(
228 inv_context_manager = rc_cache.InvalidationContext(
229 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace)
229 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace)
230 with inv_context_manager as invalidation_context:
230 with inv_context_manager as invalidation_context:
231 args = (self.db_repo.repo_id, self.db_repo.repo_name, 'rss',)
231 args = (self.db_repo.repo_id, self.db_repo.repo_name, 'rss',)
232 # re-compute and store cache if we get invalidate signal
232 # re-compute and store cache if we get invalidate signal
233 if invalidation_context.should_invalidate():
233 if invalidation_context.should_invalidate():
234 mime_type, feed = generate_rss_feed.refresh(*args)
234 mime_type, feed = generate_rss_feed.refresh(*args)
235 else:
235 else:
236 mime_type, feed = generate_rss_feed(*args)
236 mime_type, feed = generate_rss_feed(*args)
237 log.debug(
237 log.debug(
238 'Repo RSS feed computed in %.3fs', inv_context_manager.compute_time)
238 'Repo RSS feed computed in %.4fs', inv_context_manager.compute_time)
239
239
240 response = Response(feed)
240 response = Response(feed)
241 response.content_type = mime_type
241 response.content_type = mime_type
242 return response
242 return response
@@ -1,396 +1,396 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2019 RhodeCode GmbH
3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22 import string
22 import string
23 import rhodecode
23 import rhodecode
24
24
25 from pyramid.view import view_config
25 from pyramid.view import view_config
26
26
27 from rhodecode.lib.view_utils import get_format_ref_id
27 from rhodecode.lib.view_utils import get_format_ref_id
28 from rhodecode.apps._base import RepoAppView
28 from rhodecode.apps._base import RepoAppView
29 from rhodecode.config.conf import (LANGUAGES_EXTENSIONS_MAP)
29 from rhodecode.config.conf import (LANGUAGES_EXTENSIONS_MAP)
30 from rhodecode.lib import helpers as h, rc_cache
30 from rhodecode.lib import helpers as h, rc_cache
31 from rhodecode.lib.utils2 import safe_str, safe_int
31 from rhodecode.lib.utils2 import safe_str, safe_int
32 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
32 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
33 from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links
33 from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links
34 from rhodecode.lib.ext_json import json
34 from rhodecode.lib.ext_json import json
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 (
36 from rhodecode.lib.vcs.exceptions import (
37 CommitError, EmptyRepositoryError, CommitDoesNotExistError)
37 CommitError, EmptyRepositoryError, CommitDoesNotExistError)
38 from rhodecode.model.db import Statistics, CacheKey, User
38 from rhodecode.model.db import Statistics, CacheKey, User
39 from rhodecode.model.meta import Session
39 from rhodecode.model.meta import Session
40 from rhodecode.model.repo import ReadmeFinder
40 from rhodecode.model.repo import ReadmeFinder
41 from rhodecode.model.scm import ScmModel
41 from rhodecode.model.scm import ScmModel
42
42
43 log = logging.getLogger(__name__)
43 log = logging.getLogger(__name__)
44
44
45
45
46 class RepoSummaryView(RepoAppView):
46 class RepoSummaryView(RepoAppView):
47
47
48 def load_default_context(self):
48 def load_default_context(self):
49 c = self._get_local_tmpl_context(include_app_defaults=True)
49 c = self._get_local_tmpl_context(include_app_defaults=True)
50 c.rhodecode_repo = None
50 c.rhodecode_repo = None
51 if not c.repository_requirements_missing:
51 if not c.repository_requirements_missing:
52 c.rhodecode_repo = self.rhodecode_vcs_repo
52 c.rhodecode_repo = self.rhodecode_vcs_repo
53 return c
53 return c
54
54
55 def _get_readme_data(self, db_repo, renderer_type):
55 def _get_readme_data(self, db_repo, renderer_type):
56
56
57 log.debug('Looking for README file')
57 log.debug('Looking for README file')
58
58
59 cache_namespace_uid = 'cache_repo_instance.{}_{}'.format(
59 cache_namespace_uid = 'cache_repo_instance.{}_{}'.format(
60 db_repo.repo_id, CacheKey.CACHE_TYPE_README)
60 db_repo.repo_id, CacheKey.CACHE_TYPE_README)
61 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
61 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
62 repo_id=self.db_repo.repo_id)
62 repo_id=self.db_repo.repo_id)
63 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
63 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
64
64
65 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
65 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
66 def generate_repo_readme(repo_id, _repo_name, _renderer_type):
66 def generate_repo_readme(repo_id, _repo_name, _renderer_type):
67 readme_data = None
67 readme_data = None
68 readme_node = None
68 readme_node = None
69 readme_filename = None
69 readme_filename = None
70 commit = self._get_landing_commit_or_none(db_repo)
70 commit = self._get_landing_commit_or_none(db_repo)
71 if commit:
71 if commit:
72 log.debug("Searching for a README file.")
72 log.debug("Searching for a README file.")
73 readme_node = ReadmeFinder(_renderer_type).search(commit)
73 readme_node = ReadmeFinder(_renderer_type).search(commit)
74 if readme_node:
74 if readme_node:
75 log.debug('Found README node: %s', readme_node)
75 log.debug('Found README node: %s', readme_node)
76 relative_urls = {
76 relative_urls = {
77 'raw': h.route_path(
77 'raw': h.route_path(
78 'repo_file_raw', repo_name=_repo_name,
78 'repo_file_raw', repo_name=_repo_name,
79 commit_id=commit.raw_id, f_path=readme_node.path),
79 commit_id=commit.raw_id, f_path=readme_node.path),
80 'standard': h.route_path(
80 'standard': h.route_path(
81 'repo_files', repo_name=_repo_name,
81 'repo_files', repo_name=_repo_name,
82 commit_id=commit.raw_id, f_path=readme_node.path),
82 commit_id=commit.raw_id, f_path=readme_node.path),
83 }
83 }
84 readme_data = self._render_readme_or_none(
84 readme_data = self._render_readme_or_none(
85 commit, readme_node, relative_urls)
85 commit, readme_node, relative_urls)
86 readme_filename = readme_node.unicode_path
86 readme_filename = readme_node.unicode_path
87
87
88 return readme_data, readme_filename
88 return readme_data, readme_filename
89
89
90 inv_context_manager = rc_cache.InvalidationContext(
90 inv_context_manager = rc_cache.InvalidationContext(
91 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace)
91 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace)
92 with inv_context_manager as invalidation_context:
92 with inv_context_manager as invalidation_context:
93 args = (db_repo.repo_id, db_repo.repo_name, renderer_type,)
93 args = (db_repo.repo_id, db_repo.repo_name, renderer_type,)
94 # re-compute and store cache if we get invalidate signal
94 # re-compute and store cache if we get invalidate signal
95 if invalidation_context.should_invalidate():
95 if invalidation_context.should_invalidate():
96 instance = generate_repo_readme.refresh(*args)
96 instance = generate_repo_readme.refresh(*args)
97 else:
97 else:
98 instance = generate_repo_readme(*args)
98 instance = generate_repo_readme(*args)
99
99
100 log.debug(
100 log.debug(
101 'Repo readme generated and computed in %.3fs',
101 'Repo readme generated and computed in %.4fs',
102 inv_context_manager.compute_time)
102 inv_context_manager.compute_time)
103 return instance
103 return instance
104
104
105 def _get_landing_commit_or_none(self, db_repo):
105 def _get_landing_commit_or_none(self, db_repo):
106 log.debug("Getting the landing commit.")
106 log.debug("Getting the landing commit.")
107 try:
107 try:
108 commit = db_repo.get_landing_commit()
108 commit = db_repo.get_landing_commit()
109 if not isinstance(commit, EmptyCommit):
109 if not isinstance(commit, EmptyCommit):
110 return commit
110 return commit
111 else:
111 else:
112 log.debug("Repository is empty, no README to render.")
112 log.debug("Repository is empty, no README to render.")
113 except CommitError:
113 except CommitError:
114 log.exception(
114 log.exception(
115 "Problem getting commit when trying to render the README.")
115 "Problem getting commit when trying to render the README.")
116
116
117 def _render_readme_or_none(self, commit, readme_node, relative_urls):
117 def _render_readme_or_none(self, commit, readme_node, relative_urls):
118 log.debug(
118 log.debug(
119 'Found README file `%s` rendering...', readme_node.path)
119 'Found README file `%s` rendering...', readme_node.path)
120 renderer = MarkupRenderer()
120 renderer = MarkupRenderer()
121 try:
121 try:
122 html_source = renderer.render(
122 html_source = renderer.render(
123 readme_node.content, filename=readme_node.path)
123 readme_node.content, filename=readme_node.path)
124 if relative_urls:
124 if relative_urls:
125 return relative_links(html_source, relative_urls)
125 return relative_links(html_source, relative_urls)
126 return html_source
126 return html_source
127 except Exception:
127 except Exception:
128 log.exception(
128 log.exception(
129 "Exception while trying to render the README")
129 "Exception while trying to render the README")
130
130
131 def _load_commits_context(self, c):
131 def _load_commits_context(self, c):
132 p = safe_int(self.request.GET.get('page'), 1)
132 p = safe_int(self.request.GET.get('page'), 1)
133 size = safe_int(self.request.GET.get('size'), 10)
133 size = safe_int(self.request.GET.get('size'), 10)
134
134
135 def url_generator(**kw):
135 def url_generator(**kw):
136 query_params = {
136 query_params = {
137 'size': size
137 'size': size
138 }
138 }
139 query_params.update(kw)
139 query_params.update(kw)
140 return h.route_path(
140 return h.route_path(
141 'repo_summary_commits',
141 'repo_summary_commits',
142 repo_name=c.rhodecode_db_repo.repo_name, _query=query_params)
142 repo_name=c.rhodecode_db_repo.repo_name, _query=query_params)
143
143
144 pre_load = ['author', 'branch', 'date', 'message']
144 pre_load = ['author', 'branch', 'date', 'message']
145 try:
145 try:
146 collection = self.rhodecode_vcs_repo.get_commits(
146 collection = self.rhodecode_vcs_repo.get_commits(
147 pre_load=pre_load, translate_tags=False)
147 pre_load=pre_load, translate_tags=False)
148 except EmptyRepositoryError:
148 except EmptyRepositoryError:
149 collection = self.rhodecode_vcs_repo
149 collection = self.rhodecode_vcs_repo
150
150
151 c.repo_commits = h.RepoPage(
151 c.repo_commits = h.RepoPage(
152 collection, page=p, items_per_page=size, url=url_generator)
152 collection, page=p, items_per_page=size, url=url_generator)
153 page_ids = [x.raw_id for x in c.repo_commits]
153 page_ids = [x.raw_id for x in c.repo_commits]
154 c.comments = self.db_repo.get_comments(page_ids)
154 c.comments = self.db_repo.get_comments(page_ids)
155 c.statuses = self.db_repo.statuses(page_ids)
155 c.statuses = self.db_repo.statuses(page_ids)
156
156
157 def _prepare_and_set_clone_url(self, c):
157 def _prepare_and_set_clone_url(self, c):
158 username = ''
158 username = ''
159 if self._rhodecode_user.username != User.DEFAULT_USER:
159 if self._rhodecode_user.username != User.DEFAULT_USER:
160 username = safe_str(self._rhodecode_user.username)
160 username = safe_str(self._rhodecode_user.username)
161
161
162 _def_clone_uri = _def_clone_uri_id = c.clone_uri_tmpl
162 _def_clone_uri = _def_clone_uri_id = c.clone_uri_tmpl
163 _def_clone_uri_ssh = c.clone_uri_ssh_tmpl
163 _def_clone_uri_ssh = c.clone_uri_ssh_tmpl
164
164
165 if '{repo}' in _def_clone_uri:
165 if '{repo}' in _def_clone_uri:
166 _def_clone_uri_id = _def_clone_uri.replace('{repo}', '_{repoid}')
166 _def_clone_uri_id = _def_clone_uri.replace('{repo}', '_{repoid}')
167 elif '{repoid}' in _def_clone_uri:
167 elif '{repoid}' in _def_clone_uri:
168 _def_clone_uri_id = _def_clone_uri.replace('_{repoid}', '{repo}')
168 _def_clone_uri_id = _def_clone_uri.replace('_{repoid}', '{repo}')
169
169
170 c.clone_repo_url = self.db_repo.clone_url(
170 c.clone_repo_url = self.db_repo.clone_url(
171 user=username, uri_tmpl=_def_clone_uri)
171 user=username, uri_tmpl=_def_clone_uri)
172 c.clone_repo_url_id = self.db_repo.clone_url(
172 c.clone_repo_url_id = self.db_repo.clone_url(
173 user=username, uri_tmpl=_def_clone_uri_id)
173 user=username, uri_tmpl=_def_clone_uri_id)
174 c.clone_repo_url_ssh = self.db_repo.clone_url(
174 c.clone_repo_url_ssh = self.db_repo.clone_url(
175 uri_tmpl=_def_clone_uri_ssh, ssh=True)
175 uri_tmpl=_def_clone_uri_ssh, ssh=True)
176
176
177 @LoginRequired()
177 @LoginRequired()
178 @HasRepoPermissionAnyDecorator(
178 @HasRepoPermissionAnyDecorator(
179 'repository.read', 'repository.write', 'repository.admin')
179 'repository.read', 'repository.write', 'repository.admin')
180 @view_config(
180 @view_config(
181 route_name='repo_summary_commits', request_method='GET',
181 route_name='repo_summary_commits', request_method='GET',
182 renderer='rhodecode:templates/summary/summary_commits.mako')
182 renderer='rhodecode:templates/summary/summary_commits.mako')
183 def summary_commits(self):
183 def summary_commits(self):
184 c = self.load_default_context()
184 c = self.load_default_context()
185 self._prepare_and_set_clone_url(c)
185 self._prepare_and_set_clone_url(c)
186 self._load_commits_context(c)
186 self._load_commits_context(c)
187 return self._get_template_context(c)
187 return self._get_template_context(c)
188
188
189 @LoginRequired()
189 @LoginRequired()
190 @HasRepoPermissionAnyDecorator(
190 @HasRepoPermissionAnyDecorator(
191 'repository.read', 'repository.write', 'repository.admin')
191 'repository.read', 'repository.write', 'repository.admin')
192 @view_config(
192 @view_config(
193 route_name='repo_summary', request_method='GET',
193 route_name='repo_summary', request_method='GET',
194 renderer='rhodecode:templates/summary/summary.mako')
194 renderer='rhodecode:templates/summary/summary.mako')
195 @view_config(
195 @view_config(
196 route_name='repo_summary_slash', request_method='GET',
196 route_name='repo_summary_slash', request_method='GET',
197 renderer='rhodecode:templates/summary/summary.mako')
197 renderer='rhodecode:templates/summary/summary.mako')
198 @view_config(
198 @view_config(
199 route_name='repo_summary_explicit', request_method='GET',
199 route_name='repo_summary_explicit', request_method='GET',
200 renderer='rhodecode:templates/summary/summary.mako')
200 renderer='rhodecode:templates/summary/summary.mako')
201 def summary(self):
201 def summary(self):
202 c = self.load_default_context()
202 c = self.load_default_context()
203
203
204 # Prepare the clone URL
204 # Prepare the clone URL
205 self._prepare_and_set_clone_url(c)
205 self._prepare_and_set_clone_url(c)
206
206
207 # update every 5 min
207 # update every 5 min
208 if self.db_repo.last_commit_cache_update_diff > 60 * 5:
208 if self.db_repo.last_commit_cache_update_diff > 60 * 5:
209 self.db_repo.update_commit_cache()
209 self.db_repo.update_commit_cache()
210
210
211 # If enabled, get statistics data
211 # If enabled, get statistics data
212
212
213 c.show_stats = bool(self.db_repo.enable_statistics)
213 c.show_stats = bool(self.db_repo.enable_statistics)
214
214
215 stats = Session().query(Statistics) \
215 stats = Session().query(Statistics) \
216 .filter(Statistics.repository == self.db_repo) \
216 .filter(Statistics.repository == self.db_repo) \
217 .scalar()
217 .scalar()
218
218
219 c.stats_percentage = 0
219 c.stats_percentage = 0
220
220
221 if stats and stats.languages:
221 if stats and stats.languages:
222 c.no_data = False is self.db_repo.enable_statistics
222 c.no_data = False is self.db_repo.enable_statistics
223 lang_stats_d = json.loads(stats.languages)
223 lang_stats_d = json.loads(stats.languages)
224
224
225 # Sort first by decreasing count and second by the file extension,
225 # Sort first by decreasing count and second by the file extension,
226 # so we have a consistent output.
226 # so we have a consistent output.
227 lang_stats_items = sorted(lang_stats_d.iteritems(),
227 lang_stats_items = sorted(lang_stats_d.iteritems(),
228 key=lambda k: (-k[1], k[0]))[:10]
228 key=lambda k: (-k[1], k[0]))[:10]
229 lang_stats = [(x, {"count": y,
229 lang_stats = [(x, {"count": y,
230 "desc": LANGUAGES_EXTENSIONS_MAP.get(x)})
230 "desc": LANGUAGES_EXTENSIONS_MAP.get(x)})
231 for x, y in lang_stats_items]
231 for x, y in lang_stats_items]
232
232
233 c.trending_languages = json.dumps(lang_stats)
233 c.trending_languages = json.dumps(lang_stats)
234 else:
234 else:
235 c.no_data = True
235 c.no_data = True
236 c.trending_languages = json.dumps({})
236 c.trending_languages = json.dumps({})
237
237
238 scm_model = ScmModel()
238 scm_model = ScmModel()
239 c.enable_downloads = self.db_repo.enable_downloads
239 c.enable_downloads = self.db_repo.enable_downloads
240 c.repository_followers = scm_model.get_followers(self.db_repo)
240 c.repository_followers = scm_model.get_followers(self.db_repo)
241 c.repository_forks = scm_model.get_forks(self.db_repo)
241 c.repository_forks = scm_model.get_forks(self.db_repo)
242
242
243 # first interaction with the VCS instance after here...
243 # first interaction with the VCS instance after here...
244 if c.repository_requirements_missing:
244 if c.repository_requirements_missing:
245 self.request.override_renderer = \
245 self.request.override_renderer = \
246 'rhodecode:templates/summary/missing_requirements.mako'
246 'rhodecode:templates/summary/missing_requirements.mako'
247 return self._get_template_context(c)
247 return self._get_template_context(c)
248
248
249 c.readme_data, c.readme_file = \
249 c.readme_data, c.readme_file = \
250 self._get_readme_data(self.db_repo, c.visual.default_renderer)
250 self._get_readme_data(self.db_repo, c.visual.default_renderer)
251
251
252 # loads the summary commits template context
252 # loads the summary commits template context
253 self._load_commits_context(c)
253 self._load_commits_context(c)
254
254
255 return self._get_template_context(c)
255 return self._get_template_context(c)
256
256
257 def get_request_commit_id(self):
257 def get_request_commit_id(self):
258 return self.request.matchdict['commit_id']
258 return self.request.matchdict['commit_id']
259
259
260 @LoginRequired()
260 @LoginRequired()
261 @HasRepoPermissionAnyDecorator(
261 @HasRepoPermissionAnyDecorator(
262 'repository.read', 'repository.write', 'repository.admin')
262 'repository.read', 'repository.write', 'repository.admin')
263 @view_config(
263 @view_config(
264 route_name='repo_stats', request_method='GET',
264 route_name='repo_stats', request_method='GET',
265 renderer='json_ext')
265 renderer='json_ext')
266 def repo_stats(self):
266 def repo_stats(self):
267 commit_id = self.get_request_commit_id()
267 commit_id = self.get_request_commit_id()
268 show_stats = bool(self.db_repo.enable_statistics)
268 show_stats = bool(self.db_repo.enable_statistics)
269 repo_id = self.db_repo.repo_id
269 repo_id = self.db_repo.repo_id
270
270
271 cache_seconds = safe_int(
271 cache_seconds = safe_int(
272 rhodecode.CONFIG.get('rc_cache.cache_repo.expiration_time'))
272 rhodecode.CONFIG.get('rc_cache.cache_repo.expiration_time'))
273 cache_on = cache_seconds > 0
273 cache_on = cache_seconds > 0
274 log.debug(
274 log.debug(
275 'Computing REPO TREE for repo_id %s commit_id `%s` '
275 'Computing REPO TREE for repo_id %s commit_id `%s` '
276 'with caching: %s[TTL: %ss]' % (
276 'with caching: %s[TTL: %ss]' % (
277 repo_id, commit_id, cache_on, cache_seconds or 0))
277 repo_id, commit_id, cache_on, cache_seconds or 0))
278
278
279 cache_namespace_uid = 'cache_repo.{}'.format(repo_id)
279 cache_namespace_uid = 'cache_repo.{}'.format(repo_id)
280 region = rc_cache.get_or_create_region('cache_repo', cache_namespace_uid)
280 region = rc_cache.get_or_create_region('cache_repo', cache_namespace_uid)
281
281
282 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
282 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
283 condition=cache_on)
283 condition=cache_on)
284 def compute_stats(repo_id, commit_id, show_stats):
284 def compute_stats(repo_id, commit_id, show_stats):
285 code_stats = {}
285 code_stats = {}
286 size = 0
286 size = 0
287 try:
287 try:
288 scm_instance = self.db_repo.scm_instance()
288 scm_instance = self.db_repo.scm_instance()
289 commit = scm_instance.get_commit(commit_id)
289 commit = scm_instance.get_commit(commit_id)
290
290
291 for node in commit.get_filenodes_generator():
291 for node in commit.get_filenodes_generator():
292 size += node.size
292 size += node.size
293 if not show_stats:
293 if not show_stats:
294 continue
294 continue
295 ext = string.lower(node.extension)
295 ext = string.lower(node.extension)
296 ext_info = LANGUAGES_EXTENSIONS_MAP.get(ext)
296 ext_info = LANGUAGES_EXTENSIONS_MAP.get(ext)
297 if ext_info:
297 if ext_info:
298 if ext in code_stats:
298 if ext in code_stats:
299 code_stats[ext]['count'] += 1
299 code_stats[ext]['count'] += 1
300 else:
300 else:
301 code_stats[ext] = {"count": 1, "desc": ext_info}
301 code_stats[ext] = {"count": 1, "desc": ext_info}
302 except (EmptyRepositoryError, CommitDoesNotExistError):
302 except (EmptyRepositoryError, CommitDoesNotExistError):
303 pass
303 pass
304 return {'size': h.format_byte_size_binary(size),
304 return {'size': h.format_byte_size_binary(size),
305 'code_stats': code_stats}
305 'code_stats': code_stats}
306
306
307 stats = compute_stats(self.db_repo.repo_id, commit_id, show_stats)
307 stats = compute_stats(self.db_repo.repo_id, commit_id, show_stats)
308 return stats
308 return stats
309
309
310 @LoginRequired()
310 @LoginRequired()
311 @HasRepoPermissionAnyDecorator(
311 @HasRepoPermissionAnyDecorator(
312 'repository.read', 'repository.write', 'repository.admin')
312 'repository.read', 'repository.write', 'repository.admin')
313 @view_config(
313 @view_config(
314 route_name='repo_refs_data', request_method='GET',
314 route_name='repo_refs_data', request_method='GET',
315 renderer='json_ext')
315 renderer='json_ext')
316 def repo_refs_data(self):
316 def repo_refs_data(self):
317 _ = self.request.translate
317 _ = self.request.translate
318 self.load_default_context()
318 self.load_default_context()
319
319
320 repo = self.rhodecode_vcs_repo
320 repo = self.rhodecode_vcs_repo
321 refs_to_create = [
321 refs_to_create = [
322 (_("Branch"), repo.branches, 'branch'),
322 (_("Branch"), repo.branches, 'branch'),
323 (_("Tag"), repo.tags, 'tag'),
323 (_("Tag"), repo.tags, 'tag'),
324 (_("Bookmark"), repo.bookmarks, 'book'),
324 (_("Bookmark"), repo.bookmarks, 'book'),
325 ]
325 ]
326 res = self._create_reference_data(repo, self.db_repo_name, refs_to_create)
326 res = self._create_reference_data(repo, self.db_repo_name, refs_to_create)
327 data = {
327 data = {
328 'more': False,
328 'more': False,
329 'results': res
329 'results': res
330 }
330 }
331 return data
331 return data
332
332
333 @LoginRequired()
333 @LoginRequired()
334 @HasRepoPermissionAnyDecorator(
334 @HasRepoPermissionAnyDecorator(
335 'repository.read', 'repository.write', 'repository.admin')
335 'repository.read', 'repository.write', 'repository.admin')
336 @view_config(
336 @view_config(
337 route_name='repo_refs_changelog_data', request_method='GET',
337 route_name='repo_refs_changelog_data', request_method='GET',
338 renderer='json_ext')
338 renderer='json_ext')
339 def repo_refs_changelog_data(self):
339 def repo_refs_changelog_data(self):
340 _ = self.request.translate
340 _ = self.request.translate
341 self.load_default_context()
341 self.load_default_context()
342
342
343 repo = self.rhodecode_vcs_repo
343 repo = self.rhodecode_vcs_repo
344
344
345 refs_to_create = [
345 refs_to_create = [
346 (_("Branches"), repo.branches, 'branch'),
346 (_("Branches"), repo.branches, 'branch'),
347 (_("Closed branches"), repo.branches_closed, 'branch_closed'),
347 (_("Closed branches"), repo.branches_closed, 'branch_closed'),
348 # TODO: enable when vcs can handle bookmarks filters
348 # TODO: enable when vcs can handle bookmarks filters
349 # (_("Bookmarks"), repo.bookmarks, "book"),
349 # (_("Bookmarks"), repo.bookmarks, "book"),
350 ]
350 ]
351 res = self._create_reference_data(
351 res = self._create_reference_data(
352 repo, self.db_repo_name, refs_to_create)
352 repo, self.db_repo_name, refs_to_create)
353 data = {
353 data = {
354 'more': False,
354 'more': False,
355 'results': res
355 'results': res
356 }
356 }
357 return data
357 return data
358
358
359 def _create_reference_data(self, repo, full_repo_name, refs_to_create):
359 def _create_reference_data(self, repo, full_repo_name, refs_to_create):
360 format_ref_id = get_format_ref_id(repo)
360 format_ref_id = get_format_ref_id(repo)
361
361
362 result = []
362 result = []
363 for title, refs, ref_type in refs_to_create:
363 for title, refs, ref_type in refs_to_create:
364 if refs:
364 if refs:
365 result.append({
365 result.append({
366 'text': title,
366 'text': title,
367 'children': self._create_reference_items(
367 'children': self._create_reference_items(
368 repo, full_repo_name, refs, ref_type,
368 repo, full_repo_name, refs, ref_type,
369 format_ref_id),
369 format_ref_id),
370 })
370 })
371 return result
371 return result
372
372
373 def _create_reference_items(self, repo, full_repo_name, refs, ref_type, format_ref_id):
373 def _create_reference_items(self, repo, full_repo_name, refs, ref_type, format_ref_id):
374 result = []
374 result = []
375 is_svn = h.is_svn(repo)
375 is_svn = h.is_svn(repo)
376 for ref_name, raw_id in refs.iteritems():
376 for ref_name, raw_id in refs.iteritems():
377 files_url = self._create_files_url(
377 files_url = self._create_files_url(
378 repo, full_repo_name, ref_name, raw_id, is_svn)
378 repo, full_repo_name, ref_name, raw_id, is_svn)
379 result.append({
379 result.append({
380 'text': ref_name,
380 'text': ref_name,
381 'id': format_ref_id(ref_name, raw_id),
381 'id': format_ref_id(ref_name, raw_id),
382 'raw_id': raw_id,
382 'raw_id': raw_id,
383 'type': ref_type,
383 'type': ref_type,
384 'files_url': files_url,
384 'files_url': files_url,
385 'idx': 0,
385 'idx': 0,
386 })
386 })
387 return result
387 return result
388
388
389 def _create_files_url(self, repo, full_repo_name, ref_name, raw_id, is_svn):
389 def _create_files_url(self, repo, full_repo_name, ref_name, raw_id, is_svn):
390 use_commit_id = '/' in ref_name or is_svn
390 use_commit_id = '/' in ref_name or is_svn
391 return h.route_path(
391 return h.route_path(
392 'repo_files',
392 'repo_files',
393 repo_name=full_repo_name,
393 repo_name=full_repo_name,
394 f_path=ref_name if is_svn else '',
394 f_path=ref_name if is_svn else '',
395 commit_id=raw_id if use_commit_id else ref_name,
395 commit_id=raw_id if use_commit_id else ref_name,
396 _query=dict(at=ref_name))
396 _query=dict(at=ref_name))
@@ -1,164 +1,164 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2019 RhodeCode GmbH
3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22 import urllib
22 import urllib
23 from pyramid.view import view_config
23 from pyramid.view import view_config
24 from webhelpers.util import update_params
24 from webhelpers.util import update_params
25
25
26 from rhodecode.apps._base import BaseAppView, RepoAppView, RepoGroupAppView
26 from rhodecode.apps._base import BaseAppView, RepoAppView, RepoGroupAppView
27 from rhodecode.lib.auth import (
27 from rhodecode.lib.auth import (
28 LoginRequired, HasRepoPermissionAnyDecorator, HasRepoGroupPermissionAnyDecorator)
28 LoginRequired, HasRepoPermissionAnyDecorator, HasRepoGroupPermissionAnyDecorator)
29 from rhodecode.lib.helpers import Page
29 from rhodecode.lib.helpers import Page
30 from rhodecode.lib.utils2 import safe_str
30 from rhodecode.lib.utils2 import safe_str
31 from rhodecode.lib.index import searcher_from_config
31 from rhodecode.lib.index import searcher_from_config
32 from rhodecode.model import validation_schema
32 from rhodecode.model import validation_schema
33 from rhodecode.model.validation_schema.schemas import search_schema
33 from rhodecode.model.validation_schema.schemas import search_schema
34
34
35 log = logging.getLogger(__name__)
35 log = logging.getLogger(__name__)
36
36
37
37
38 def perform_search(request, tmpl_context, repo_name=None, repo_group_name=None):
38 def perform_search(request, tmpl_context, repo_name=None, repo_group_name=None):
39 searcher = searcher_from_config(request.registry.settings)
39 searcher = searcher_from_config(request.registry.settings)
40 formatted_results = []
40 formatted_results = []
41 execution_time = ''
41 execution_time = ''
42
42
43 schema = search_schema.SearchParamsSchema()
43 schema = search_schema.SearchParamsSchema()
44 search_tags = []
44 search_tags = []
45 search_params = {}
45 search_params = {}
46 errors = []
46 errors = []
47 try:
47 try:
48 search_params = schema.deserialize(
48 search_params = schema.deserialize(
49 dict(
49 dict(
50 search_query=request.GET.get('q'),
50 search_query=request.GET.get('q'),
51 search_type=request.GET.get('type'),
51 search_type=request.GET.get('type'),
52 search_sort=request.GET.get('sort'),
52 search_sort=request.GET.get('sort'),
53 search_max_lines=request.GET.get('max_lines'),
53 search_max_lines=request.GET.get('max_lines'),
54 page_limit=request.GET.get('page_limit'),
54 page_limit=request.GET.get('page_limit'),
55 requested_page=request.GET.get('page'),
55 requested_page=request.GET.get('page'),
56 )
56 )
57 )
57 )
58 except validation_schema.Invalid as e:
58 except validation_schema.Invalid as e:
59 errors = e.children
59 errors = e.children
60
60
61 def url_generator(**kw):
61 def url_generator(**kw):
62 q = urllib.quote(safe_str(search_query))
62 q = urllib.quote(safe_str(search_query))
63 return update_params(
63 return update_params(
64 "?q=%s&type=%s&max_lines=%s" % (
64 "?q=%s&type=%s&max_lines=%s" % (
65 q, safe_str(search_type), search_max_lines), **kw)
65 q, safe_str(search_type), search_max_lines), **kw)
66
66
67 c = tmpl_context
67 c = tmpl_context
68 search_query = search_params.get('search_query')
68 search_query = search_params.get('search_query')
69 search_type = search_params.get('search_type')
69 search_type = search_params.get('search_type')
70 search_sort = search_params.get('search_sort')
70 search_sort = search_params.get('search_sort')
71 search_max_lines = search_params.get('search_max_lines')
71 search_max_lines = search_params.get('search_max_lines')
72 if search_params.get('search_query'):
72 if search_params.get('search_query'):
73 page_limit = search_params['page_limit']
73 page_limit = search_params['page_limit']
74 requested_page = search_params['requested_page']
74 requested_page = search_params['requested_page']
75
75
76 try:
76 try:
77 search_result = searcher.search(
77 search_result = searcher.search(
78 search_query, search_type, c.auth_user, repo_name, repo_group_name,
78 search_query, search_type, c.auth_user, repo_name, repo_group_name,
79 requested_page=requested_page, page_limit=page_limit, sort=search_sort)
79 requested_page=requested_page, page_limit=page_limit, sort=search_sort)
80
80
81 formatted_results = Page(
81 formatted_results = Page(
82 search_result['results'], page=requested_page,
82 search_result['results'], page=requested_page,
83 item_count=search_result['count'],
83 item_count=search_result['count'],
84 items_per_page=page_limit, url=url_generator)
84 items_per_page=page_limit, url=url_generator)
85 finally:
85 finally:
86 searcher.cleanup()
86 searcher.cleanup()
87
87
88 search_tags = searcher.extract_search_tags(search_query)
88 search_tags = searcher.extract_search_tags(search_query)
89
89
90 if not search_result['error']:
90 if not search_result['error']:
91 execution_time = '%s results (%.3f seconds)' % (
91 execution_time = '%s results (%.4f seconds)' % (
92 search_result['count'],
92 search_result['count'],
93 search_result['runtime'])
93 search_result['runtime'])
94 elif not errors:
94 elif not errors:
95 node = schema['search_query']
95 node = schema['search_query']
96 errors = [
96 errors = [
97 validation_schema.Invalid(node, search_result['error'])]
97 validation_schema.Invalid(node, search_result['error'])]
98
98
99 c.perm_user = c.auth_user
99 c.perm_user = c.auth_user
100 c.repo_name = repo_name
100 c.repo_name = repo_name
101 c.repo_group_name = repo_group_name
101 c.repo_group_name = repo_group_name
102 c.sort = search_sort
102 c.sort = search_sort
103 c.url_generator = url_generator
103 c.url_generator = url_generator
104 c.errors = errors
104 c.errors = errors
105 c.formatted_results = formatted_results
105 c.formatted_results = formatted_results
106 c.runtime = execution_time
106 c.runtime = execution_time
107 c.cur_query = search_query
107 c.cur_query = search_query
108 c.search_type = search_type
108 c.search_type = search_type
109 c.searcher = searcher
109 c.searcher = searcher
110 c.search_tags = search_tags
110 c.search_tags = search_tags
111
111
112
112
113 class SearchView(BaseAppView):
113 class SearchView(BaseAppView):
114 def load_default_context(self):
114 def load_default_context(self):
115 c = self._get_local_tmpl_context()
115 c = self._get_local_tmpl_context()
116 return c
116 return c
117
117
118 @LoginRequired()
118 @LoginRequired()
119 @view_config(
119 @view_config(
120 route_name='search', request_method='GET',
120 route_name='search', request_method='GET',
121 renderer='rhodecode:templates/search/search.mako')
121 renderer='rhodecode:templates/search/search.mako')
122 def search(self):
122 def search(self):
123 c = self.load_default_context()
123 c = self.load_default_context()
124 perform_search(self.request, c)
124 perform_search(self.request, c)
125 return self._get_template_context(c)
125 return self._get_template_context(c)
126
126
127
127
128 class SearchRepoView(RepoAppView):
128 class SearchRepoView(RepoAppView):
129 def load_default_context(self):
129 def load_default_context(self):
130 c = self._get_local_tmpl_context()
130 c = self._get_local_tmpl_context()
131 c.active = 'search'
131 c.active = 'search'
132 return c
132 return c
133
133
134 @LoginRequired()
134 @LoginRequired()
135 @HasRepoPermissionAnyDecorator(
135 @HasRepoPermissionAnyDecorator(
136 'repository.read', 'repository.write', 'repository.admin')
136 'repository.read', 'repository.write', 'repository.admin')
137 @view_config(
137 @view_config(
138 route_name='search_repo', request_method='GET',
138 route_name='search_repo', request_method='GET',
139 renderer='rhodecode:templates/search/search.mako')
139 renderer='rhodecode:templates/search/search.mako')
140 @view_config(
140 @view_config(
141 route_name='search_repo_alt', request_method='GET',
141 route_name='search_repo_alt', request_method='GET',
142 renderer='rhodecode:templates/search/search.mako')
142 renderer='rhodecode:templates/search/search.mako')
143 def search_repo(self):
143 def search_repo(self):
144 c = self.load_default_context()
144 c = self.load_default_context()
145 perform_search(self.request, c, repo_name=self.db_repo_name)
145 perform_search(self.request, c, repo_name=self.db_repo_name)
146 return self._get_template_context(c)
146 return self._get_template_context(c)
147
147
148
148
149 class SearchRepoGroupView(RepoGroupAppView):
149 class SearchRepoGroupView(RepoGroupAppView):
150 def load_default_context(self):
150 def load_default_context(self):
151 c = self._get_local_tmpl_context()
151 c = self._get_local_tmpl_context()
152 c.active = 'search'
152 c.active = 'search'
153 return c
153 return c
154
154
155 @LoginRequired()
155 @LoginRequired()
156 @HasRepoGroupPermissionAnyDecorator(
156 @HasRepoGroupPermissionAnyDecorator(
157 'group.read', 'group.write', 'group.admin')
157 'group.read', 'group.write', 'group.admin')
158 @view_config(
158 @view_config(
159 route_name='search_repo_group', request_method='GET',
159 route_name='search_repo_group', request_method='GET',
160 renderer='rhodecode:templates/search/search.mako')
160 renderer='rhodecode:templates/search/search.mako')
161 def search_repo_group(self):
161 def search_repo_group(self):
162 c = self.load_default_context()
162 c = self.load_default_context()
163 perform_search(self.request, c, repo_group_name=self.db_repo_group_name)
163 perform_search(self.request, c, repo_group_name=self.db_repo_group_name)
164 return self._get_template_context(c)
164 return self._get_template_context(c)
@@ -1,797 +1,797 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Authentication modules
22 Authentication modules
23 """
23 """
24 import socket
24 import socket
25 import string
25 import string
26 import colander
26 import colander
27 import copy
27 import copy
28 import logging
28 import logging
29 import time
29 import time
30 import traceback
30 import traceback
31 import warnings
31 import warnings
32 import functools
32 import functools
33
33
34 from pyramid.threadlocal import get_current_registry
34 from pyramid.threadlocal import get_current_registry
35
35
36 from rhodecode.authentication.interface import IAuthnPluginRegistry
36 from rhodecode.authentication.interface import IAuthnPluginRegistry
37 from rhodecode.authentication.schema import AuthnPluginSettingsSchemaBase
37 from rhodecode.authentication.schema import AuthnPluginSettingsSchemaBase
38 from rhodecode.lib import rc_cache
38 from rhodecode.lib import rc_cache
39 from rhodecode.lib.auth import PasswordGenerator, _RhodeCodeCryptoBCrypt
39 from rhodecode.lib.auth import PasswordGenerator, _RhodeCodeCryptoBCrypt
40 from rhodecode.lib.utils2 import safe_int, safe_str
40 from rhodecode.lib.utils2 import safe_int, safe_str
41 from rhodecode.lib.exceptions import LdapConnectionError, LdapUsernameError, \
41 from rhodecode.lib.exceptions import LdapConnectionError, LdapUsernameError, \
42 LdapPasswordError
42 LdapPasswordError
43 from rhodecode.model.db import User
43 from rhodecode.model.db import User
44 from rhodecode.model.meta import Session
44 from rhodecode.model.meta import Session
45 from rhodecode.model.settings import SettingsModel
45 from rhodecode.model.settings import SettingsModel
46 from rhodecode.model.user import UserModel
46 from rhodecode.model.user import UserModel
47 from rhodecode.model.user_group import UserGroupModel
47 from rhodecode.model.user_group import UserGroupModel
48
48
49
49
50 log = logging.getLogger(__name__)
50 log = logging.getLogger(__name__)
51
51
52 # auth types that authenticate() function can receive
52 # auth types that authenticate() function can receive
53 VCS_TYPE = 'vcs'
53 VCS_TYPE = 'vcs'
54 HTTP_TYPE = 'http'
54 HTTP_TYPE = 'http'
55
55
56 external_auth_session_key = 'rhodecode.external_auth'
56 external_auth_session_key = 'rhodecode.external_auth'
57
57
58
58
59 class hybrid_property(object):
59 class hybrid_property(object):
60 """
60 """
61 a property decorator that works both for instance and class
61 a property decorator that works both for instance and class
62 """
62 """
63 def __init__(self, fget, fset=None, fdel=None, expr=None):
63 def __init__(self, fget, fset=None, fdel=None, expr=None):
64 self.fget = fget
64 self.fget = fget
65 self.fset = fset
65 self.fset = fset
66 self.fdel = fdel
66 self.fdel = fdel
67 self.expr = expr or fget
67 self.expr = expr or fget
68 functools.update_wrapper(self, fget)
68 functools.update_wrapper(self, fget)
69
69
70 def __get__(self, instance, owner):
70 def __get__(self, instance, owner):
71 if instance is None:
71 if instance is None:
72 return self.expr(owner)
72 return self.expr(owner)
73 else:
73 else:
74 return self.fget(instance)
74 return self.fget(instance)
75
75
76 def __set__(self, instance, value):
76 def __set__(self, instance, value):
77 self.fset(instance, value)
77 self.fset(instance, value)
78
78
79 def __delete__(self, instance):
79 def __delete__(self, instance):
80 self.fdel(instance)
80 self.fdel(instance)
81
81
82
82
83 class LazyFormencode(object):
83 class LazyFormencode(object):
84 def __init__(self, formencode_obj, *args, **kwargs):
84 def __init__(self, formencode_obj, *args, **kwargs):
85 self.formencode_obj = formencode_obj
85 self.formencode_obj = formencode_obj
86 self.args = args
86 self.args = args
87 self.kwargs = kwargs
87 self.kwargs = kwargs
88
88
89 def __call__(self, *args, **kwargs):
89 def __call__(self, *args, **kwargs):
90 from inspect import isfunction
90 from inspect import isfunction
91 formencode_obj = self.formencode_obj
91 formencode_obj = self.formencode_obj
92 if isfunction(formencode_obj):
92 if isfunction(formencode_obj):
93 # case we wrap validators into functions
93 # case we wrap validators into functions
94 formencode_obj = self.formencode_obj(*args, **kwargs)
94 formencode_obj = self.formencode_obj(*args, **kwargs)
95 return formencode_obj(*self.args, **self.kwargs)
95 return formencode_obj(*self.args, **self.kwargs)
96
96
97
97
98 class RhodeCodeAuthPluginBase(object):
98 class RhodeCodeAuthPluginBase(object):
99 # UID is used to register plugin to the registry
99 # UID is used to register plugin to the registry
100 uid = None
100 uid = None
101
101
102 # cache the authentication request for N amount of seconds. Some kind
102 # cache the authentication request for N amount of seconds. Some kind
103 # of authentication methods are very heavy and it's very efficient to cache
103 # of authentication methods are very heavy and it's very efficient to cache
104 # the result of a call. If it's set to None (default) cache is off
104 # the result of a call. If it's set to None (default) cache is off
105 AUTH_CACHE_TTL = None
105 AUTH_CACHE_TTL = None
106 AUTH_CACHE = {}
106 AUTH_CACHE = {}
107
107
108 auth_func_attrs = {
108 auth_func_attrs = {
109 "username": "unique username",
109 "username": "unique username",
110 "firstname": "first name",
110 "firstname": "first name",
111 "lastname": "last name",
111 "lastname": "last name",
112 "email": "email address",
112 "email": "email address",
113 "groups": '["list", "of", "groups"]',
113 "groups": '["list", "of", "groups"]',
114 "user_group_sync":
114 "user_group_sync":
115 'True|False defines if returned user groups should be synced',
115 'True|False defines if returned user groups should be synced',
116 "extern_name": "name in external source of record",
116 "extern_name": "name in external source of record",
117 "extern_type": "type of external source of record",
117 "extern_type": "type of external source of record",
118 "admin": 'True|False defines if user should be RhodeCode super admin',
118 "admin": 'True|False defines if user should be RhodeCode super admin',
119 "active":
119 "active":
120 'True|False defines active state of user internally for RhodeCode',
120 'True|False defines active state of user internally for RhodeCode',
121 "active_from_extern":
121 "active_from_extern":
122 "True|False|None, active state from the external auth, "
122 "True|False|None, active state from the external auth, "
123 "None means use definition from RhodeCode extern_type active value"
123 "None means use definition from RhodeCode extern_type active value"
124
124
125 }
125 }
126 # set on authenticate() method and via set_auth_type func.
126 # set on authenticate() method and via set_auth_type func.
127 auth_type = None
127 auth_type = None
128
128
129 # set on authenticate() method and via set_calling_scope_repo, this is a
129 # set on authenticate() method and via set_calling_scope_repo, this is a
130 # calling scope repository when doing authentication most likely on VCS
130 # calling scope repository when doing authentication most likely on VCS
131 # operations
131 # operations
132 acl_repo_name = None
132 acl_repo_name = None
133
133
134 # List of setting names to store encrypted. Plugins may override this list
134 # List of setting names to store encrypted. Plugins may override this list
135 # to store settings encrypted.
135 # to store settings encrypted.
136 _settings_encrypted = []
136 _settings_encrypted = []
137
137
138 # Mapping of python to DB settings model types. Plugins may override or
138 # Mapping of python to DB settings model types. Plugins may override or
139 # extend this mapping.
139 # extend this mapping.
140 _settings_type_map = {
140 _settings_type_map = {
141 colander.String: 'unicode',
141 colander.String: 'unicode',
142 colander.Integer: 'int',
142 colander.Integer: 'int',
143 colander.Boolean: 'bool',
143 colander.Boolean: 'bool',
144 colander.List: 'list',
144 colander.List: 'list',
145 }
145 }
146
146
147 # list of keys in settings that are unsafe to be logged, should be passwords
147 # list of keys in settings that are unsafe to be logged, should be passwords
148 # or other crucial credentials
148 # or other crucial credentials
149 _settings_unsafe_keys = []
149 _settings_unsafe_keys = []
150
150
151 def __init__(self, plugin_id):
151 def __init__(self, plugin_id):
152 self._plugin_id = plugin_id
152 self._plugin_id = plugin_id
153
153
154 def __str__(self):
154 def __str__(self):
155 return self.get_id()
155 return self.get_id()
156
156
157 def _get_setting_full_name(self, name):
157 def _get_setting_full_name(self, name):
158 """
158 """
159 Return the full setting name used for storing values in the database.
159 Return the full setting name used for storing values in the database.
160 """
160 """
161 # TODO: johbo: Using the name here is problematic. It would be good to
161 # TODO: johbo: Using the name here is problematic. It would be good to
162 # introduce either new models in the database to hold Plugin and
162 # introduce either new models in the database to hold Plugin and
163 # PluginSetting or to use the plugin id here.
163 # PluginSetting or to use the plugin id here.
164 return 'auth_{}_{}'.format(self.name, name)
164 return 'auth_{}_{}'.format(self.name, name)
165
165
166 def _get_setting_type(self, name):
166 def _get_setting_type(self, name):
167 """
167 """
168 Return the type of a setting. This type is defined by the SettingsModel
168 Return the type of a setting. This type is defined by the SettingsModel
169 and determines how the setting is stored in DB. Optionally the suffix
169 and determines how the setting is stored in DB. Optionally the suffix
170 `.encrypted` is appended to instruct SettingsModel to store it
170 `.encrypted` is appended to instruct SettingsModel to store it
171 encrypted.
171 encrypted.
172 """
172 """
173 schema_node = self.get_settings_schema().get(name)
173 schema_node = self.get_settings_schema().get(name)
174 db_type = self._settings_type_map.get(
174 db_type = self._settings_type_map.get(
175 type(schema_node.typ), 'unicode')
175 type(schema_node.typ), 'unicode')
176 if name in self._settings_encrypted:
176 if name in self._settings_encrypted:
177 db_type = '{}.encrypted'.format(db_type)
177 db_type = '{}.encrypted'.format(db_type)
178 return db_type
178 return db_type
179
179
180 @classmethod
180 @classmethod
181 def docs(cls):
181 def docs(cls):
182 """
182 """
183 Defines documentation url which helps with plugin setup
183 Defines documentation url which helps with plugin setup
184 """
184 """
185 return ''
185 return ''
186
186
187 @classmethod
187 @classmethod
188 def icon(cls):
188 def icon(cls):
189 """
189 """
190 Defines ICON in SVG format for authentication method
190 Defines ICON in SVG format for authentication method
191 """
191 """
192 return ''
192 return ''
193
193
194 def is_enabled(self):
194 def is_enabled(self):
195 """
195 """
196 Returns true if this plugin is enabled. An enabled plugin can be
196 Returns true if this plugin is enabled. An enabled plugin can be
197 configured in the admin interface but it is not consulted during
197 configured in the admin interface but it is not consulted during
198 authentication.
198 authentication.
199 """
199 """
200 auth_plugins = SettingsModel().get_auth_plugins()
200 auth_plugins = SettingsModel().get_auth_plugins()
201 return self.get_id() in auth_plugins
201 return self.get_id() in auth_plugins
202
202
203 def is_active(self, plugin_cached_settings=None):
203 def is_active(self, plugin_cached_settings=None):
204 """
204 """
205 Returns true if the plugin is activated. An activated plugin is
205 Returns true if the plugin is activated. An activated plugin is
206 consulted during authentication, assumed it is also enabled.
206 consulted during authentication, assumed it is also enabled.
207 """
207 """
208 return self.get_setting_by_name(
208 return self.get_setting_by_name(
209 'enabled', plugin_cached_settings=plugin_cached_settings)
209 'enabled', plugin_cached_settings=plugin_cached_settings)
210
210
211 def get_id(self):
211 def get_id(self):
212 """
212 """
213 Returns the plugin id.
213 Returns the plugin id.
214 """
214 """
215 return self._plugin_id
215 return self._plugin_id
216
216
217 def get_display_name(self):
217 def get_display_name(self):
218 """
218 """
219 Returns a translation string for displaying purposes.
219 Returns a translation string for displaying purposes.
220 """
220 """
221 raise NotImplementedError('Not implemented in base class')
221 raise NotImplementedError('Not implemented in base class')
222
222
223 def get_settings_schema(self):
223 def get_settings_schema(self):
224 """
224 """
225 Returns a colander schema, representing the plugin settings.
225 Returns a colander schema, representing the plugin settings.
226 """
226 """
227 return AuthnPluginSettingsSchemaBase()
227 return AuthnPluginSettingsSchemaBase()
228
228
229 def get_settings(self):
229 def get_settings(self):
230 """
230 """
231 Returns the plugin settings as dictionary.
231 Returns the plugin settings as dictionary.
232 """
232 """
233 settings = {}
233 settings = {}
234 raw_settings = SettingsModel().get_all_settings()
234 raw_settings = SettingsModel().get_all_settings()
235 for node in self.get_settings_schema():
235 for node in self.get_settings_schema():
236 settings[node.name] = self.get_setting_by_name(
236 settings[node.name] = self.get_setting_by_name(
237 node.name, plugin_cached_settings=raw_settings)
237 node.name, plugin_cached_settings=raw_settings)
238 return settings
238 return settings
239
239
240 def get_setting_by_name(self, name, default=None, plugin_cached_settings=None):
240 def get_setting_by_name(self, name, default=None, plugin_cached_settings=None):
241 """
241 """
242 Returns a plugin setting by name.
242 Returns a plugin setting by name.
243 """
243 """
244 full_name = 'rhodecode_{}'.format(self._get_setting_full_name(name))
244 full_name = 'rhodecode_{}'.format(self._get_setting_full_name(name))
245 if plugin_cached_settings:
245 if plugin_cached_settings:
246 plugin_settings = plugin_cached_settings
246 plugin_settings = plugin_cached_settings
247 else:
247 else:
248 plugin_settings = SettingsModel().get_all_settings()
248 plugin_settings = SettingsModel().get_all_settings()
249
249
250 if full_name in plugin_settings:
250 if full_name in plugin_settings:
251 return plugin_settings[full_name]
251 return plugin_settings[full_name]
252 else:
252 else:
253 return default
253 return default
254
254
255 def create_or_update_setting(self, name, value):
255 def create_or_update_setting(self, name, value):
256 """
256 """
257 Create or update a setting for this plugin in the persistent storage.
257 Create or update a setting for this plugin in the persistent storage.
258 """
258 """
259 full_name = self._get_setting_full_name(name)
259 full_name = self._get_setting_full_name(name)
260 type_ = self._get_setting_type(name)
260 type_ = self._get_setting_type(name)
261 db_setting = SettingsModel().create_or_update_setting(
261 db_setting = SettingsModel().create_or_update_setting(
262 full_name, value, type_)
262 full_name, value, type_)
263 return db_setting.app_settings_value
263 return db_setting.app_settings_value
264
264
265 def log_safe_settings(self, settings):
265 def log_safe_settings(self, settings):
266 """
266 """
267 returns a log safe representation of settings, without any secrets
267 returns a log safe representation of settings, without any secrets
268 """
268 """
269 settings_copy = copy.deepcopy(settings)
269 settings_copy = copy.deepcopy(settings)
270 for k in self._settings_unsafe_keys:
270 for k in self._settings_unsafe_keys:
271 if k in settings_copy:
271 if k in settings_copy:
272 del settings_copy[k]
272 del settings_copy[k]
273 return settings_copy
273 return settings_copy
274
274
275 @hybrid_property
275 @hybrid_property
276 def name(self):
276 def name(self):
277 """
277 """
278 Returns the name of this authentication plugin.
278 Returns the name of this authentication plugin.
279
279
280 :returns: string
280 :returns: string
281 """
281 """
282 raise NotImplementedError("Not implemented in base class")
282 raise NotImplementedError("Not implemented in base class")
283
283
284 def get_url_slug(self):
284 def get_url_slug(self):
285 """
285 """
286 Returns a slug which should be used when constructing URLs which refer
286 Returns a slug which should be used when constructing URLs which refer
287 to this plugin. By default it returns the plugin name. If the name is
287 to this plugin. By default it returns the plugin name. If the name is
288 not suitable for using it in an URL the plugin should override this
288 not suitable for using it in an URL the plugin should override this
289 method.
289 method.
290 """
290 """
291 return self.name
291 return self.name
292
292
293 @property
293 @property
294 def is_headers_auth(self):
294 def is_headers_auth(self):
295 """
295 """
296 Returns True if this authentication plugin uses HTTP headers as
296 Returns True if this authentication plugin uses HTTP headers as
297 authentication method.
297 authentication method.
298 """
298 """
299 return False
299 return False
300
300
301 @hybrid_property
301 @hybrid_property
302 def is_container_auth(self):
302 def is_container_auth(self):
303 """
303 """
304 Deprecated method that indicates if this authentication plugin uses
304 Deprecated method that indicates if this authentication plugin uses
305 HTTP headers as authentication method.
305 HTTP headers as authentication method.
306 """
306 """
307 warnings.warn(
307 warnings.warn(
308 'Use is_headers_auth instead.', category=DeprecationWarning)
308 'Use is_headers_auth instead.', category=DeprecationWarning)
309 return self.is_headers_auth
309 return self.is_headers_auth
310
310
311 @hybrid_property
311 @hybrid_property
312 def allows_creating_users(self):
312 def allows_creating_users(self):
313 """
313 """
314 Defines if Plugin allows users to be created on-the-fly when
314 Defines if Plugin allows users to be created on-the-fly when
315 authentication is called. Controls how external plugins should behave
315 authentication is called. Controls how external plugins should behave
316 in terms if they are allowed to create new users, or not. Base plugins
316 in terms if they are allowed to create new users, or not. Base plugins
317 should not be allowed to, but External ones should be !
317 should not be allowed to, but External ones should be !
318
318
319 :return: bool
319 :return: bool
320 """
320 """
321 return False
321 return False
322
322
323 def set_auth_type(self, auth_type):
323 def set_auth_type(self, auth_type):
324 self.auth_type = auth_type
324 self.auth_type = auth_type
325
325
326 def set_calling_scope_repo(self, acl_repo_name):
326 def set_calling_scope_repo(self, acl_repo_name):
327 self.acl_repo_name = acl_repo_name
327 self.acl_repo_name = acl_repo_name
328
328
329 def allows_authentication_from(
329 def allows_authentication_from(
330 self, user, allows_non_existing_user=True,
330 self, user, allows_non_existing_user=True,
331 allowed_auth_plugins=None, allowed_auth_sources=None):
331 allowed_auth_plugins=None, allowed_auth_sources=None):
332 """
332 """
333 Checks if this authentication module should accept a request for
333 Checks if this authentication module should accept a request for
334 the current user.
334 the current user.
335
335
336 :param user: user object fetched using plugin's get_user() method.
336 :param user: user object fetched using plugin's get_user() method.
337 :param allows_non_existing_user: if True, don't allow the
337 :param allows_non_existing_user: if True, don't allow the
338 user to be empty, meaning not existing in our database
338 user to be empty, meaning not existing in our database
339 :param allowed_auth_plugins: if provided, users extern_type will be
339 :param allowed_auth_plugins: if provided, users extern_type will be
340 checked against a list of provided extern types, which are plugin
340 checked against a list of provided extern types, which are plugin
341 auth_names in the end
341 auth_names in the end
342 :param allowed_auth_sources: authentication type allowed,
342 :param allowed_auth_sources: authentication type allowed,
343 `http` or `vcs` default is both.
343 `http` or `vcs` default is both.
344 defines if plugin will accept only http authentication vcs
344 defines if plugin will accept only http authentication vcs
345 authentication(git/hg) or both
345 authentication(git/hg) or both
346 :returns: boolean
346 :returns: boolean
347 """
347 """
348 if not user and not allows_non_existing_user:
348 if not user and not allows_non_existing_user:
349 log.debug('User is empty but plugin does not allow empty users,'
349 log.debug('User is empty but plugin does not allow empty users,'
350 'not allowed to authenticate')
350 'not allowed to authenticate')
351 return False
351 return False
352
352
353 expected_auth_plugins = allowed_auth_plugins or [self.name]
353 expected_auth_plugins = allowed_auth_plugins or [self.name]
354 if user and (user.extern_type and
354 if user and (user.extern_type and
355 user.extern_type not in expected_auth_plugins):
355 user.extern_type not in expected_auth_plugins):
356 log.debug(
356 log.debug(
357 'User `%s` is bound to `%s` auth type. Plugin allows only '
357 'User `%s` is bound to `%s` auth type. Plugin allows only '
358 '%s, skipping', user, user.extern_type, expected_auth_plugins)
358 '%s, skipping', user, user.extern_type, expected_auth_plugins)
359
359
360 return False
360 return False
361
361
362 # by default accept both
362 # by default accept both
363 expected_auth_from = allowed_auth_sources or [HTTP_TYPE, VCS_TYPE]
363 expected_auth_from = allowed_auth_sources or [HTTP_TYPE, VCS_TYPE]
364 if self.auth_type not in expected_auth_from:
364 if self.auth_type not in expected_auth_from:
365 log.debug('Current auth source is %s but plugin only allows %s',
365 log.debug('Current auth source is %s but plugin only allows %s',
366 self.auth_type, expected_auth_from)
366 self.auth_type, expected_auth_from)
367 return False
367 return False
368
368
369 return True
369 return True
370
370
371 def get_user(self, username=None, **kwargs):
371 def get_user(self, username=None, **kwargs):
372 """
372 """
373 Helper method for user fetching in plugins, by default it's using
373 Helper method for user fetching in plugins, by default it's using
374 simple fetch by username, but this method can be custimized in plugins
374 simple fetch by username, but this method can be custimized in plugins
375 eg. headers auth plugin to fetch user by environ params
375 eg. headers auth plugin to fetch user by environ params
376
376
377 :param username: username if given to fetch from database
377 :param username: username if given to fetch from database
378 :param kwargs: extra arguments needed for user fetching.
378 :param kwargs: extra arguments needed for user fetching.
379 """
379 """
380 user = None
380 user = None
381 log.debug(
381 log.debug(
382 'Trying to fetch user `%s` from RhodeCode database', username)
382 'Trying to fetch user `%s` from RhodeCode database', username)
383 if username:
383 if username:
384 user = User.get_by_username(username)
384 user = User.get_by_username(username)
385 if not user:
385 if not user:
386 log.debug('User not found, fallback to fetch user in '
386 log.debug('User not found, fallback to fetch user in '
387 'case insensitive mode')
387 'case insensitive mode')
388 user = User.get_by_username(username, case_insensitive=True)
388 user = User.get_by_username(username, case_insensitive=True)
389 else:
389 else:
390 log.debug('provided username:`%s` is empty skipping...', username)
390 log.debug('provided username:`%s` is empty skipping...', username)
391 if not user:
391 if not user:
392 log.debug('User `%s` not found in database', username)
392 log.debug('User `%s` not found in database', username)
393 else:
393 else:
394 log.debug('Got DB user:%s', user)
394 log.debug('Got DB user:%s', user)
395 return user
395 return user
396
396
397 def user_activation_state(self):
397 def user_activation_state(self):
398 """
398 """
399 Defines user activation state when creating new users
399 Defines user activation state when creating new users
400
400
401 :returns: boolean
401 :returns: boolean
402 """
402 """
403 raise NotImplementedError("Not implemented in base class")
403 raise NotImplementedError("Not implemented in base class")
404
404
405 def auth(self, userobj, username, passwd, settings, **kwargs):
405 def auth(self, userobj, username, passwd, settings, **kwargs):
406 """
406 """
407 Given a user object (which may be null), username, a plaintext
407 Given a user object (which may be null), username, a plaintext
408 password, and a settings object (containing all the keys needed as
408 password, and a settings object (containing all the keys needed as
409 listed in settings()), authenticate this user's login attempt.
409 listed in settings()), authenticate this user's login attempt.
410
410
411 Return None on failure. On success, return a dictionary of the form:
411 Return None on failure. On success, return a dictionary of the form:
412
412
413 see: RhodeCodeAuthPluginBase.auth_func_attrs
413 see: RhodeCodeAuthPluginBase.auth_func_attrs
414 This is later validated for correctness
414 This is later validated for correctness
415 """
415 """
416 raise NotImplementedError("not implemented in base class")
416 raise NotImplementedError("not implemented in base class")
417
417
418 def _authenticate(self, userobj, username, passwd, settings, **kwargs):
418 def _authenticate(self, userobj, username, passwd, settings, **kwargs):
419 """
419 """
420 Wrapper to call self.auth() that validates call on it
420 Wrapper to call self.auth() that validates call on it
421
421
422 :param userobj: userobj
422 :param userobj: userobj
423 :param username: username
423 :param username: username
424 :param passwd: plaintext password
424 :param passwd: plaintext password
425 :param settings: plugin settings
425 :param settings: plugin settings
426 """
426 """
427 auth = self.auth(userobj, username, passwd, settings, **kwargs)
427 auth = self.auth(userobj, username, passwd, settings, **kwargs)
428 if auth:
428 if auth:
429 auth['_plugin'] = self.name
429 auth['_plugin'] = self.name
430 auth['_ttl_cache'] = self.get_ttl_cache(settings)
430 auth['_ttl_cache'] = self.get_ttl_cache(settings)
431 # check if hash should be migrated ?
431 # check if hash should be migrated ?
432 new_hash = auth.get('_hash_migrate')
432 new_hash = auth.get('_hash_migrate')
433 if new_hash:
433 if new_hash:
434 self._migrate_hash_to_bcrypt(username, passwd, new_hash)
434 self._migrate_hash_to_bcrypt(username, passwd, new_hash)
435 if 'user_group_sync' not in auth:
435 if 'user_group_sync' not in auth:
436 auth['user_group_sync'] = False
436 auth['user_group_sync'] = False
437 return self._validate_auth_return(auth)
437 return self._validate_auth_return(auth)
438 return auth
438 return auth
439
439
440 def _migrate_hash_to_bcrypt(self, username, password, new_hash):
440 def _migrate_hash_to_bcrypt(self, username, password, new_hash):
441 new_hash_cypher = _RhodeCodeCryptoBCrypt()
441 new_hash_cypher = _RhodeCodeCryptoBCrypt()
442 # extra checks, so make sure new hash is correct.
442 # extra checks, so make sure new hash is correct.
443 password_encoded = safe_str(password)
443 password_encoded = safe_str(password)
444 if new_hash and new_hash_cypher.hash_check(
444 if new_hash and new_hash_cypher.hash_check(
445 password_encoded, new_hash):
445 password_encoded, new_hash):
446 cur_user = User.get_by_username(username)
446 cur_user = User.get_by_username(username)
447 cur_user.password = new_hash
447 cur_user.password = new_hash
448 Session().add(cur_user)
448 Session().add(cur_user)
449 Session().flush()
449 Session().flush()
450 log.info('Migrated user %s hash to bcrypt', cur_user)
450 log.info('Migrated user %s hash to bcrypt', cur_user)
451
451
452 def _validate_auth_return(self, ret):
452 def _validate_auth_return(self, ret):
453 if not isinstance(ret, dict):
453 if not isinstance(ret, dict):
454 raise Exception('returned value from auth must be a dict')
454 raise Exception('returned value from auth must be a dict')
455 for k in self.auth_func_attrs:
455 for k in self.auth_func_attrs:
456 if k not in ret:
456 if k not in ret:
457 raise Exception('Missing %s attribute from returned data' % k)
457 raise Exception('Missing %s attribute from returned data' % k)
458 return ret
458 return ret
459
459
460 def get_ttl_cache(self, settings=None):
460 def get_ttl_cache(self, settings=None):
461 plugin_settings = settings or self.get_settings()
461 plugin_settings = settings or self.get_settings()
462 # we set default to 30, we make a compromise here,
462 # we set default to 30, we make a compromise here,
463 # performance > security, mostly due to LDAP/SVN, majority
463 # performance > security, mostly due to LDAP/SVN, majority
464 # of users pick cache_ttl to be enabled
464 # of users pick cache_ttl to be enabled
465 from rhodecode.authentication import plugin_default_auth_ttl
465 from rhodecode.authentication import plugin_default_auth_ttl
466 cache_ttl = plugin_default_auth_ttl
466 cache_ttl = plugin_default_auth_ttl
467
467
468 if isinstance(self.AUTH_CACHE_TTL, (int, long)):
468 if isinstance(self.AUTH_CACHE_TTL, (int, long)):
469 # plugin cache set inside is more important than the settings value
469 # plugin cache set inside is more important than the settings value
470 cache_ttl = self.AUTH_CACHE_TTL
470 cache_ttl = self.AUTH_CACHE_TTL
471 elif plugin_settings.get('cache_ttl'):
471 elif plugin_settings.get('cache_ttl'):
472 cache_ttl = safe_int(plugin_settings.get('cache_ttl'), 0)
472 cache_ttl = safe_int(plugin_settings.get('cache_ttl'), 0)
473
473
474 plugin_cache_active = bool(cache_ttl and cache_ttl > 0)
474 plugin_cache_active = bool(cache_ttl and cache_ttl > 0)
475 return plugin_cache_active, cache_ttl
475 return plugin_cache_active, cache_ttl
476
476
477
477
478 class RhodeCodeExternalAuthPlugin(RhodeCodeAuthPluginBase):
478 class RhodeCodeExternalAuthPlugin(RhodeCodeAuthPluginBase):
479
479
480 @hybrid_property
480 @hybrid_property
481 def allows_creating_users(self):
481 def allows_creating_users(self):
482 return True
482 return True
483
483
484 def use_fake_password(self):
484 def use_fake_password(self):
485 """
485 """
486 Return a boolean that indicates whether or not we should set the user's
486 Return a boolean that indicates whether or not we should set the user's
487 password to a random value when it is authenticated by this plugin.
487 password to a random value when it is authenticated by this plugin.
488 If your plugin provides authentication, then you will generally
488 If your plugin provides authentication, then you will generally
489 want this.
489 want this.
490
490
491 :returns: boolean
491 :returns: boolean
492 """
492 """
493 raise NotImplementedError("Not implemented in base class")
493 raise NotImplementedError("Not implemented in base class")
494
494
495 def _authenticate(self, userobj, username, passwd, settings, **kwargs):
495 def _authenticate(self, userobj, username, passwd, settings, **kwargs):
496 # at this point _authenticate calls plugin's `auth()` function
496 # at this point _authenticate calls plugin's `auth()` function
497 auth = super(RhodeCodeExternalAuthPlugin, self)._authenticate(
497 auth = super(RhodeCodeExternalAuthPlugin, self)._authenticate(
498 userobj, username, passwd, settings, **kwargs)
498 userobj, username, passwd, settings, **kwargs)
499
499
500 if auth:
500 if auth:
501 # maybe plugin will clean the username ?
501 # maybe plugin will clean the username ?
502 # we should use the return value
502 # we should use the return value
503 username = auth['username']
503 username = auth['username']
504
504
505 # if external source tells us that user is not active, we should
505 # if external source tells us that user is not active, we should
506 # skip rest of the process. This can prevent from creating users in
506 # skip rest of the process. This can prevent from creating users in
507 # RhodeCode when using external authentication, but if it's
507 # RhodeCode when using external authentication, but if it's
508 # inactive user we shouldn't create that user anyway
508 # inactive user we shouldn't create that user anyway
509 if auth['active_from_extern'] is False:
509 if auth['active_from_extern'] is False:
510 log.warning(
510 log.warning(
511 "User %s authenticated against %s, but is inactive",
511 "User %s authenticated against %s, but is inactive",
512 username, self.__module__)
512 username, self.__module__)
513 return None
513 return None
514
514
515 cur_user = User.get_by_username(username, case_insensitive=True)
515 cur_user = User.get_by_username(username, case_insensitive=True)
516 is_user_existing = cur_user is not None
516 is_user_existing = cur_user is not None
517
517
518 if is_user_existing:
518 if is_user_existing:
519 log.debug('Syncing user `%s` from '
519 log.debug('Syncing user `%s` from '
520 '`%s` plugin', username, self.name)
520 '`%s` plugin', username, self.name)
521 else:
521 else:
522 log.debug('Creating non existing user `%s` from '
522 log.debug('Creating non existing user `%s` from '
523 '`%s` plugin', username, self.name)
523 '`%s` plugin', username, self.name)
524
524
525 if self.allows_creating_users:
525 if self.allows_creating_users:
526 log.debug('Plugin `%s` allows to '
526 log.debug('Plugin `%s` allows to '
527 'create new users', self.name)
527 'create new users', self.name)
528 else:
528 else:
529 log.debug('Plugin `%s` does not allow to '
529 log.debug('Plugin `%s` does not allow to '
530 'create new users', self.name)
530 'create new users', self.name)
531
531
532 user_parameters = {
532 user_parameters = {
533 'username': username,
533 'username': username,
534 'email': auth["email"],
534 'email': auth["email"],
535 'firstname': auth["firstname"],
535 'firstname': auth["firstname"],
536 'lastname': auth["lastname"],
536 'lastname': auth["lastname"],
537 'active': auth["active"],
537 'active': auth["active"],
538 'admin': auth["admin"],
538 'admin': auth["admin"],
539 'extern_name': auth["extern_name"],
539 'extern_name': auth["extern_name"],
540 'extern_type': self.name,
540 'extern_type': self.name,
541 'plugin': self,
541 'plugin': self,
542 'allow_to_create_user': self.allows_creating_users,
542 'allow_to_create_user': self.allows_creating_users,
543 }
543 }
544
544
545 if not is_user_existing:
545 if not is_user_existing:
546 if self.use_fake_password():
546 if self.use_fake_password():
547 # Randomize the PW because we don't need it, but don't want
547 # Randomize the PW because we don't need it, but don't want
548 # them blank either
548 # them blank either
549 passwd = PasswordGenerator().gen_password(length=16)
549 passwd = PasswordGenerator().gen_password(length=16)
550 user_parameters['password'] = passwd
550 user_parameters['password'] = passwd
551 else:
551 else:
552 # Since the password is required by create_or_update method of
552 # Since the password is required by create_or_update method of
553 # UserModel, we need to set it explicitly.
553 # UserModel, we need to set it explicitly.
554 # The create_or_update method is smart and recognises the
554 # The create_or_update method is smart and recognises the
555 # password hashes as well.
555 # password hashes as well.
556 user_parameters['password'] = cur_user.password
556 user_parameters['password'] = cur_user.password
557
557
558 # we either create or update users, we also pass the flag
558 # we either create or update users, we also pass the flag
559 # that controls if this method can actually do that.
559 # that controls if this method can actually do that.
560 # raises NotAllowedToCreateUserError if it cannot, and we try to.
560 # raises NotAllowedToCreateUserError if it cannot, and we try to.
561 user = UserModel().create_or_update(**user_parameters)
561 user = UserModel().create_or_update(**user_parameters)
562 Session().flush()
562 Session().flush()
563 # enforce user is just in given groups, all of them has to be ones
563 # enforce user is just in given groups, all of them has to be ones
564 # created from plugins. We store this info in _group_data JSON
564 # created from plugins. We store this info in _group_data JSON
565 # field
565 # field
566
566
567 if auth['user_group_sync']:
567 if auth['user_group_sync']:
568 try:
568 try:
569 groups = auth['groups'] or []
569 groups = auth['groups'] or []
570 log.debug(
570 log.debug(
571 'Performing user_group sync based on set `%s` '
571 'Performing user_group sync based on set `%s` '
572 'returned by `%s` plugin', groups, self.name)
572 'returned by `%s` plugin', groups, self.name)
573 UserGroupModel().enforce_groups(user, groups, self.name)
573 UserGroupModel().enforce_groups(user, groups, self.name)
574 except Exception:
574 except Exception:
575 # for any reason group syncing fails, we should
575 # for any reason group syncing fails, we should
576 # proceed with login
576 # proceed with login
577 log.error(traceback.format_exc())
577 log.error(traceback.format_exc())
578
578
579 Session().commit()
579 Session().commit()
580 return auth
580 return auth
581
581
582
582
583 class AuthLdapBase(object):
583 class AuthLdapBase(object):
584
584
585 @classmethod
585 @classmethod
586 def _build_servers(cls, ldap_server_type, ldap_server, port, use_resolver=True):
586 def _build_servers(cls, ldap_server_type, ldap_server, port, use_resolver=True):
587
587
588 def host_resolver(host, port, full_resolve=True):
588 def host_resolver(host, port, full_resolve=True):
589 """
589 """
590 Main work for this function is to prevent ldap connection issues,
590 Main work for this function is to prevent ldap connection issues,
591 and detect them early using a "greenified" sockets
591 and detect them early using a "greenified" sockets
592 """
592 """
593 host = host.strip()
593 host = host.strip()
594 if not full_resolve:
594 if not full_resolve:
595 return '{}:{}'.format(host, port)
595 return '{}:{}'.format(host, port)
596
596
597 log.debug('LDAP: Resolving IP for LDAP host %s', host)
597 log.debug('LDAP: Resolving IP for LDAP host %s', host)
598 try:
598 try:
599 ip = socket.gethostbyname(host)
599 ip = socket.gethostbyname(host)
600 log.debug('Got LDAP server %s ip %s', host, ip)
600 log.debug('Got LDAP server %s ip %s', host, ip)
601 except Exception:
601 except Exception:
602 raise LdapConnectionError(
602 raise LdapConnectionError(
603 'Failed to resolve host: `{}`'.format(host))
603 'Failed to resolve host: `{}`'.format(host))
604
604
605 log.debug('LDAP: Checking if IP %s is accessible', ip)
605 log.debug('LDAP: Checking if IP %s is accessible', ip)
606 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
606 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
607 try:
607 try:
608 s.connect((ip, int(port)))
608 s.connect((ip, int(port)))
609 s.shutdown(socket.SHUT_RD)
609 s.shutdown(socket.SHUT_RD)
610 except Exception:
610 except Exception:
611 raise LdapConnectionError(
611 raise LdapConnectionError(
612 'Failed to connect to host: `{}:{}`'.format(host, port))
612 'Failed to connect to host: `{}:{}`'.format(host, port))
613
613
614 return '{}:{}'.format(host, port)
614 return '{}:{}'.format(host, port)
615
615
616 if len(ldap_server) == 1:
616 if len(ldap_server) == 1:
617 # in case of single server use resolver to detect potential
617 # in case of single server use resolver to detect potential
618 # connection issues
618 # connection issues
619 full_resolve = True
619 full_resolve = True
620 else:
620 else:
621 full_resolve = False
621 full_resolve = False
622
622
623 return ', '.join(
623 return ', '.join(
624 ["{}://{}".format(
624 ["{}://{}".format(
625 ldap_server_type,
625 ldap_server_type,
626 host_resolver(host, port, full_resolve=use_resolver and full_resolve))
626 host_resolver(host, port, full_resolve=use_resolver and full_resolve))
627 for host in ldap_server])
627 for host in ldap_server])
628
628
629 @classmethod
629 @classmethod
630 def _get_server_list(cls, servers):
630 def _get_server_list(cls, servers):
631 return map(string.strip, servers.split(','))
631 return map(string.strip, servers.split(','))
632
632
633 @classmethod
633 @classmethod
634 def get_uid(cls, username, server_addresses):
634 def get_uid(cls, username, server_addresses):
635 uid = username
635 uid = username
636 for server_addr in server_addresses:
636 for server_addr in server_addresses:
637 uid = chop_at(username, "@%s" % server_addr)
637 uid = chop_at(username, "@%s" % server_addr)
638 return uid
638 return uid
639
639
640 @classmethod
640 @classmethod
641 def validate_username(cls, username):
641 def validate_username(cls, username):
642 if "," in username:
642 if "," in username:
643 raise LdapUsernameError(
643 raise LdapUsernameError(
644 "invalid character `,` in username: `{}`".format(username))
644 "invalid character `,` in username: `{}`".format(username))
645
645
646 @classmethod
646 @classmethod
647 def validate_password(cls, username, password):
647 def validate_password(cls, username, password):
648 if not password:
648 if not password:
649 msg = "Authenticating user %s with blank password not allowed"
649 msg = "Authenticating user %s with blank password not allowed"
650 log.warning(msg, username)
650 log.warning(msg, username)
651 raise LdapPasswordError(msg)
651 raise LdapPasswordError(msg)
652
652
653
653
654 def loadplugin(plugin_id):
654 def loadplugin(plugin_id):
655 """
655 """
656 Loads and returns an instantiated authentication plugin.
656 Loads and returns an instantiated authentication plugin.
657 Returns the RhodeCodeAuthPluginBase subclass on success,
657 Returns the RhodeCodeAuthPluginBase subclass on success,
658 or None on failure.
658 or None on failure.
659 """
659 """
660 # TODO: Disusing pyramids thread locals to retrieve the registry.
660 # TODO: Disusing pyramids thread locals to retrieve the registry.
661 authn_registry = get_authn_registry()
661 authn_registry = get_authn_registry()
662 plugin = authn_registry.get_plugin(plugin_id)
662 plugin = authn_registry.get_plugin(plugin_id)
663 if plugin is None:
663 if plugin is None:
664 log.error('Authentication plugin not found: "%s"', plugin_id)
664 log.error('Authentication plugin not found: "%s"', plugin_id)
665 return plugin
665 return plugin
666
666
667
667
668 def get_authn_registry(registry=None):
668 def get_authn_registry(registry=None):
669 registry = registry or get_current_registry()
669 registry = registry or get_current_registry()
670 authn_registry = registry.getUtility(IAuthnPluginRegistry)
670 authn_registry = registry.getUtility(IAuthnPluginRegistry)
671 return authn_registry
671 return authn_registry
672
672
673
673
674 def authenticate(username, password, environ=None, auth_type=None,
674 def authenticate(username, password, environ=None, auth_type=None,
675 skip_missing=False, registry=None, acl_repo_name=None):
675 skip_missing=False, registry=None, acl_repo_name=None):
676 """
676 """
677 Authentication function used for access control,
677 Authentication function used for access control,
678 It tries to authenticate based on enabled authentication modules.
678 It tries to authenticate based on enabled authentication modules.
679
679
680 :param username: username can be empty for headers auth
680 :param username: username can be empty for headers auth
681 :param password: password can be empty for headers auth
681 :param password: password can be empty for headers auth
682 :param environ: environ headers passed for headers auth
682 :param environ: environ headers passed for headers auth
683 :param auth_type: type of authentication, either `HTTP_TYPE` or `VCS_TYPE`
683 :param auth_type: type of authentication, either `HTTP_TYPE` or `VCS_TYPE`
684 :param skip_missing: ignores plugins that are in db but not in environment
684 :param skip_missing: ignores plugins that are in db but not in environment
685 :returns: None if auth failed, plugin_user dict if auth is correct
685 :returns: None if auth failed, plugin_user dict if auth is correct
686 """
686 """
687 if not auth_type or auth_type not in [HTTP_TYPE, VCS_TYPE]:
687 if not auth_type or auth_type not in [HTTP_TYPE, VCS_TYPE]:
688 raise ValueError('auth type must be on of http, vcs got "%s" instead'
688 raise ValueError('auth type must be on of http, vcs got "%s" instead'
689 % auth_type)
689 % auth_type)
690 headers_only = environ and not (username and password)
690 headers_only = environ and not (username and password)
691
691
692 authn_registry = get_authn_registry(registry)
692 authn_registry = get_authn_registry(registry)
693 plugins_to_check = authn_registry.get_plugins_for_authentication()
693 plugins_to_check = authn_registry.get_plugins_for_authentication()
694 log.debug('Starting ordered authentication chain using %s plugins',
694 log.debug('Starting ordered authentication chain using %s plugins',
695 [x.name for x in plugins_to_check])
695 [x.name for x in plugins_to_check])
696 for plugin in plugins_to_check:
696 for plugin in plugins_to_check:
697 plugin.set_auth_type(auth_type)
697 plugin.set_auth_type(auth_type)
698 plugin.set_calling_scope_repo(acl_repo_name)
698 plugin.set_calling_scope_repo(acl_repo_name)
699
699
700 if headers_only and not plugin.is_headers_auth:
700 if headers_only and not plugin.is_headers_auth:
701 log.debug('Auth type is for headers only and plugin `%s` is not '
701 log.debug('Auth type is for headers only and plugin `%s` is not '
702 'headers plugin, skipping...', plugin.get_id())
702 'headers plugin, skipping...', plugin.get_id())
703 continue
703 continue
704
704
705 log.debug('Trying authentication using ** %s **', plugin.get_id())
705 log.debug('Trying authentication using ** %s **', plugin.get_id())
706
706
707 # load plugin settings from RhodeCode database
707 # load plugin settings from RhodeCode database
708 plugin_settings = plugin.get_settings()
708 plugin_settings = plugin.get_settings()
709 plugin_sanitized_settings = plugin.log_safe_settings(plugin_settings)
709 plugin_sanitized_settings = plugin.log_safe_settings(plugin_settings)
710 log.debug('Plugin `%s` settings:%s', plugin.get_id(), plugin_sanitized_settings)
710 log.debug('Plugin `%s` settings:%s', plugin.get_id(), plugin_sanitized_settings)
711
711
712 # use plugin's method of user extraction.
712 # use plugin's method of user extraction.
713 user = plugin.get_user(username, environ=environ,
713 user = plugin.get_user(username, environ=environ,
714 settings=plugin_settings)
714 settings=plugin_settings)
715 display_user = user.username if user else username
715 display_user = user.username if user else username
716 log.debug(
716 log.debug(
717 'Plugin %s extracted user is `%s`', plugin.get_id(), display_user)
717 'Plugin %s extracted user is `%s`', plugin.get_id(), display_user)
718
718
719 if not plugin.allows_authentication_from(user):
719 if not plugin.allows_authentication_from(user):
720 log.debug('Plugin %s does not accept user `%s` for authentication',
720 log.debug('Plugin %s does not accept user `%s` for authentication',
721 plugin.get_id(), display_user)
721 plugin.get_id(), display_user)
722 continue
722 continue
723 else:
723 else:
724 log.debug('Plugin %s accepted user `%s` for authentication',
724 log.debug('Plugin %s accepted user `%s` for authentication',
725 plugin.get_id(), display_user)
725 plugin.get_id(), display_user)
726
726
727 log.info('Authenticating user `%s` using %s plugin',
727 log.info('Authenticating user `%s` using %s plugin',
728 display_user, plugin.get_id())
728 display_user, plugin.get_id())
729
729
730 plugin_cache_active, cache_ttl = plugin.get_ttl_cache(plugin_settings)
730 plugin_cache_active, cache_ttl = plugin.get_ttl_cache(plugin_settings)
731
731
732 log.debug('AUTH_CACHE_TTL for plugin `%s` active: %s (TTL: %s)',
732 log.debug('AUTH_CACHE_TTL for plugin `%s` active: %s (TTL: %s)',
733 plugin.get_id(), plugin_cache_active, cache_ttl)
733 plugin.get_id(), plugin_cache_active, cache_ttl)
734
734
735 user_id = user.user_id if user else None
735 user_id = user.user_id if user else None
736 # don't cache for empty users
736 # don't cache for empty users
737 plugin_cache_active = plugin_cache_active and user_id
737 plugin_cache_active = plugin_cache_active and user_id
738 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
738 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
739 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
739 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
740
740
741 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
741 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
742 expiration_time=cache_ttl,
742 expiration_time=cache_ttl,
743 condition=plugin_cache_active)
743 condition=plugin_cache_active)
744 def compute_auth(
744 def compute_auth(
745 cache_name, plugin_name, username, password):
745 cache_name, plugin_name, username, password):
746
746
747 # _authenticate is a wrapper for .auth() method of plugin.
747 # _authenticate is a wrapper for .auth() method of plugin.
748 # it checks if .auth() sends proper data.
748 # it checks if .auth() sends proper data.
749 # For RhodeCodeExternalAuthPlugin it also maps users to
749 # For RhodeCodeExternalAuthPlugin it also maps users to
750 # Database and maps the attributes returned from .auth()
750 # Database and maps the attributes returned from .auth()
751 # to RhodeCode database. If this function returns data
751 # to RhodeCode database. If this function returns data
752 # then auth is correct.
752 # then auth is correct.
753 log.debug('Running plugin `%s` _authenticate method '
753 log.debug('Running plugin `%s` _authenticate method '
754 'using username and password', plugin.get_id())
754 'using username and password', plugin.get_id())
755 return plugin._authenticate(
755 return plugin._authenticate(
756 user, username, password, plugin_settings,
756 user, username, password, plugin_settings,
757 environ=environ or {})
757 environ=environ or {})
758
758
759 start = time.time()
759 start = time.time()
760 # for environ based auth, password can be empty, but then the validation is
760 # for environ based auth, password can be empty, but then the validation is
761 # on the server that fills in the env data needed for authentication
761 # on the server that fills in the env data needed for authentication
762 plugin_user = compute_auth('auth', plugin.name, username, (password or ''))
762 plugin_user = compute_auth('auth', plugin.name, username, (password or ''))
763
763
764 auth_time = time.time() - start
764 auth_time = time.time() - start
765 log.debug('Authentication for plugin `%s` completed in %.3fs, '
765 log.debug('Authentication for plugin `%s` completed in %.4fs, '
766 'expiration time of fetched cache %.1fs.',
766 'expiration time of fetched cache %.1fs.',
767 plugin.get_id(), auth_time, cache_ttl)
767 plugin.get_id(), auth_time, cache_ttl)
768
768
769 log.debug('PLUGIN USER DATA: %s', plugin_user)
769 log.debug('PLUGIN USER DATA: %s', plugin_user)
770
770
771 if plugin_user:
771 if plugin_user:
772 log.debug('Plugin returned proper authentication data')
772 log.debug('Plugin returned proper authentication data')
773 return plugin_user
773 return plugin_user
774 # we failed to Auth because .auth() method didn't return proper user
774 # we failed to Auth because .auth() method didn't return proper user
775 log.debug("User `%s` failed to authenticate against %s",
775 log.debug("User `%s` failed to authenticate against %s",
776 display_user, plugin.get_id())
776 display_user, plugin.get_id())
777
777
778 # case when we failed to authenticate against all defined plugins
778 # case when we failed to authenticate against all defined plugins
779 return None
779 return None
780
780
781
781
782 def chop_at(s, sub, inclusive=False):
782 def chop_at(s, sub, inclusive=False):
783 """Truncate string ``s`` at the first occurrence of ``sub``.
783 """Truncate string ``s`` at the first occurrence of ``sub``.
784
784
785 If ``inclusive`` is true, truncate just after ``sub`` rather than at it.
785 If ``inclusive`` is true, truncate just after ``sub`` rather than at it.
786
786
787 >>> chop_at("plutocratic brats", "rat")
787 >>> chop_at("plutocratic brats", "rat")
788 'plutoc'
788 'plutoc'
789 >>> chop_at("plutocratic brats", "rat", True)
789 >>> chop_at("plutocratic brats", "rat", True)
790 'plutocrat'
790 'plutocrat'
791 """
791 """
792 pos = s.find(sub)
792 pos = s.find(sub)
793 if pos == -1:
793 if pos == -1:
794 return s
794 return s
795 if inclusive:
795 if inclusive:
796 return s[:pos+len(sub)]
796 return s[:pos+len(sub)]
797 return s[:pos]
797 return s[:pos]
@@ -1,2352 +1,2352 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 authentication and permission libraries
22 authentication and permission libraries
23 """
23 """
24
24
25 import os
25 import os
26 import time
26 import time
27 import inspect
27 import inspect
28 import collections
28 import collections
29 import fnmatch
29 import fnmatch
30 import hashlib
30 import hashlib
31 import itertools
31 import itertools
32 import logging
32 import logging
33 import random
33 import random
34 import traceback
34 import traceback
35 from functools import wraps
35 from functools import wraps
36
36
37 import ipaddress
37 import ipaddress
38
38
39 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
39 from pyramid.httpexceptions import HTTPForbidden, HTTPFound, HTTPNotFound
40 from sqlalchemy.orm.exc import ObjectDeletedError
40 from sqlalchemy.orm.exc import ObjectDeletedError
41 from sqlalchemy.orm import joinedload
41 from sqlalchemy.orm import joinedload
42 from zope.cachedescriptors.property import Lazy as LazyProperty
42 from zope.cachedescriptors.property import Lazy as LazyProperty
43
43
44 import rhodecode
44 import rhodecode
45 from rhodecode.model import meta
45 from rhodecode.model import meta
46 from rhodecode.model.meta import Session
46 from rhodecode.model.meta import Session
47 from rhodecode.model.user import UserModel
47 from rhodecode.model.user import UserModel
48 from rhodecode.model.db import (
48 from rhodecode.model.db import (
49 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
49 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
50 UserIpMap, UserApiKeys, RepoGroup, UserGroup)
50 UserIpMap, UserApiKeys, RepoGroup, UserGroup)
51 from rhodecode.lib import rc_cache
51 from rhodecode.lib import rc_cache
52 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5, safe_int, sha1
52 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5, safe_int, sha1
53 from rhodecode.lib.utils import (
53 from rhodecode.lib.utils import (
54 get_repo_slug, get_repo_group_slug, get_user_group_slug)
54 get_repo_slug, get_repo_group_slug, get_user_group_slug)
55 from rhodecode.lib.caching_query import FromCache
55 from rhodecode.lib.caching_query import FromCache
56
56
57
57
58 if rhodecode.is_unix:
58 if rhodecode.is_unix:
59 import bcrypt
59 import bcrypt
60
60
61 log = logging.getLogger(__name__)
61 log = logging.getLogger(__name__)
62
62
63 csrf_token_key = "csrf_token"
63 csrf_token_key = "csrf_token"
64
64
65
65
66 class PasswordGenerator(object):
66 class PasswordGenerator(object):
67 """
67 """
68 This is a simple class for generating password from different sets of
68 This is a simple class for generating password from different sets of
69 characters
69 characters
70 usage::
70 usage::
71 passwd_gen = PasswordGenerator()
71 passwd_gen = PasswordGenerator()
72 #print 8-letter password containing only big and small letters
72 #print 8-letter password containing only big and small letters
73 of alphabet
73 of alphabet
74 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
74 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
75 """
75 """
76 ALPHABETS_NUM = r'''1234567890'''
76 ALPHABETS_NUM = r'''1234567890'''
77 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
77 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
78 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
78 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
79 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
79 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
80 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
80 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
81 + ALPHABETS_NUM + ALPHABETS_SPECIAL
81 + ALPHABETS_NUM + ALPHABETS_SPECIAL
82 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
82 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
83 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
83 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
84 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
84 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
85 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
85 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
86
86
87 def __init__(self, passwd=''):
87 def __init__(self, passwd=''):
88 self.passwd = passwd
88 self.passwd = passwd
89
89
90 def gen_password(self, length, type_=None):
90 def gen_password(self, length, type_=None):
91 if type_ is None:
91 if type_ is None:
92 type_ = self.ALPHABETS_FULL
92 type_ = self.ALPHABETS_FULL
93 self.passwd = ''.join([random.choice(type_) for _ in range(length)])
93 self.passwd = ''.join([random.choice(type_) for _ in range(length)])
94 return self.passwd
94 return self.passwd
95
95
96
96
97 class _RhodeCodeCryptoBase(object):
97 class _RhodeCodeCryptoBase(object):
98 ENC_PREF = None
98 ENC_PREF = None
99
99
100 def hash_create(self, str_):
100 def hash_create(self, str_):
101 """
101 """
102 hash the string using
102 hash the string using
103
103
104 :param str_: password to hash
104 :param str_: password to hash
105 """
105 """
106 raise NotImplementedError
106 raise NotImplementedError
107
107
108 def hash_check_with_upgrade(self, password, hashed):
108 def hash_check_with_upgrade(self, password, hashed):
109 """
109 """
110 Returns tuple in which first element is boolean that states that
110 Returns tuple in which first element is boolean that states that
111 given password matches it's hashed version, and the second is new hash
111 given password matches it's hashed version, and the second is new hash
112 of the password, in case this password should be migrated to new
112 of the password, in case this password should be migrated to new
113 cipher.
113 cipher.
114 """
114 """
115 checked_hash = self.hash_check(password, hashed)
115 checked_hash = self.hash_check(password, hashed)
116 return checked_hash, None
116 return checked_hash, None
117
117
118 def hash_check(self, password, hashed):
118 def hash_check(self, password, hashed):
119 """
119 """
120 Checks matching password with it's hashed value.
120 Checks matching password with it's hashed value.
121
121
122 :param password: password
122 :param password: password
123 :param hashed: password in hashed form
123 :param hashed: password in hashed form
124 """
124 """
125 raise NotImplementedError
125 raise NotImplementedError
126
126
127 def _assert_bytes(self, value):
127 def _assert_bytes(self, value):
128 """
128 """
129 Passing in an `unicode` object can lead to hard to detect issues
129 Passing in an `unicode` object can lead to hard to detect issues
130 if passwords contain non-ascii characters. Doing a type check
130 if passwords contain non-ascii characters. Doing a type check
131 during runtime, so that such mistakes are detected early on.
131 during runtime, so that such mistakes are detected early on.
132 """
132 """
133 if not isinstance(value, str):
133 if not isinstance(value, str):
134 raise TypeError(
134 raise TypeError(
135 "Bytestring required as input, got %r." % (value, ))
135 "Bytestring required as input, got %r." % (value, ))
136
136
137
137
138 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
138 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
139 ENC_PREF = ('$2a$10', '$2b$10')
139 ENC_PREF = ('$2a$10', '$2b$10')
140
140
141 def hash_create(self, str_):
141 def hash_create(self, str_):
142 self._assert_bytes(str_)
142 self._assert_bytes(str_)
143 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
143 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
144
144
145 def hash_check_with_upgrade(self, password, hashed):
145 def hash_check_with_upgrade(self, password, hashed):
146 """
146 """
147 Returns tuple in which first element is boolean that states that
147 Returns tuple in which first element is boolean that states that
148 given password matches it's hashed version, and the second is new hash
148 given password matches it's hashed version, and the second is new hash
149 of the password, in case this password should be migrated to new
149 of the password, in case this password should be migrated to new
150 cipher.
150 cipher.
151
151
152 This implements special upgrade logic which works like that:
152 This implements special upgrade logic which works like that:
153 - check if the given password == bcrypted hash, if yes then we
153 - check if the given password == bcrypted hash, if yes then we
154 properly used password and it was already in bcrypt. Proceed
154 properly used password and it was already in bcrypt. Proceed
155 without any changes
155 without any changes
156 - if bcrypt hash check is not working try with sha256. If hash compare
156 - if bcrypt hash check is not working try with sha256. If hash compare
157 is ok, it means we using correct but old hashed password. indicate
157 is ok, it means we using correct but old hashed password. indicate
158 hash change and proceed
158 hash change and proceed
159 """
159 """
160
160
161 new_hash = None
161 new_hash = None
162
162
163 # regular pw check
163 # regular pw check
164 password_match_bcrypt = self.hash_check(password, hashed)
164 password_match_bcrypt = self.hash_check(password, hashed)
165
165
166 # now we want to know if the password was maybe from sha256
166 # now we want to know if the password was maybe from sha256
167 # basically calling _RhodeCodeCryptoSha256().hash_check()
167 # basically calling _RhodeCodeCryptoSha256().hash_check()
168 if not password_match_bcrypt:
168 if not password_match_bcrypt:
169 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
169 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
170 new_hash = self.hash_create(password) # make new bcrypt hash
170 new_hash = self.hash_create(password) # make new bcrypt hash
171 password_match_bcrypt = True
171 password_match_bcrypt = True
172
172
173 return password_match_bcrypt, new_hash
173 return password_match_bcrypt, new_hash
174
174
175 def hash_check(self, password, hashed):
175 def hash_check(self, password, hashed):
176 """
176 """
177 Checks matching password with it's hashed value.
177 Checks matching password with it's hashed value.
178
178
179 :param password: password
179 :param password: password
180 :param hashed: password in hashed form
180 :param hashed: password in hashed form
181 """
181 """
182 self._assert_bytes(password)
182 self._assert_bytes(password)
183 try:
183 try:
184 return bcrypt.hashpw(password, hashed) == hashed
184 return bcrypt.hashpw(password, hashed) == hashed
185 except ValueError as e:
185 except ValueError as e:
186 # we're having a invalid salt here probably, we should not crash
186 # we're having a invalid salt here probably, we should not crash
187 # just return with False as it would be a wrong password.
187 # just return with False as it would be a wrong password.
188 log.debug('Failed to check password hash using bcrypt %s',
188 log.debug('Failed to check password hash using bcrypt %s',
189 safe_str(e))
189 safe_str(e))
190
190
191 return False
191 return False
192
192
193
193
194 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
194 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
195 ENC_PREF = '_'
195 ENC_PREF = '_'
196
196
197 def hash_create(self, str_):
197 def hash_create(self, str_):
198 self._assert_bytes(str_)
198 self._assert_bytes(str_)
199 return hashlib.sha256(str_).hexdigest()
199 return hashlib.sha256(str_).hexdigest()
200
200
201 def hash_check(self, password, hashed):
201 def hash_check(self, password, hashed):
202 """
202 """
203 Checks matching password with it's hashed value.
203 Checks matching password with it's hashed value.
204
204
205 :param password: password
205 :param password: password
206 :param hashed: password in hashed form
206 :param hashed: password in hashed form
207 """
207 """
208 self._assert_bytes(password)
208 self._assert_bytes(password)
209 return hashlib.sha256(password).hexdigest() == hashed
209 return hashlib.sha256(password).hexdigest() == hashed
210
210
211
211
212 class _RhodeCodeCryptoTest(_RhodeCodeCryptoBase):
212 class _RhodeCodeCryptoTest(_RhodeCodeCryptoBase):
213 ENC_PREF = '_'
213 ENC_PREF = '_'
214
214
215 def hash_create(self, str_):
215 def hash_create(self, str_):
216 self._assert_bytes(str_)
216 self._assert_bytes(str_)
217 return sha1(str_)
217 return sha1(str_)
218
218
219 def hash_check(self, password, hashed):
219 def hash_check(self, password, hashed):
220 """
220 """
221 Checks matching password with it's hashed value.
221 Checks matching password with it's hashed value.
222
222
223 :param password: password
223 :param password: password
224 :param hashed: password in hashed form
224 :param hashed: password in hashed form
225 """
225 """
226 self._assert_bytes(password)
226 self._assert_bytes(password)
227 return sha1(password) == hashed
227 return sha1(password) == hashed
228
228
229
229
230 def crypto_backend():
230 def crypto_backend():
231 """
231 """
232 Return the matching crypto backend.
232 Return the matching crypto backend.
233
233
234 Selection is based on if we run tests or not, we pick sha1-test backend to run
234 Selection is based on if we run tests or not, we pick sha1-test backend to run
235 tests faster since BCRYPT is expensive to calculate
235 tests faster since BCRYPT is expensive to calculate
236 """
236 """
237 if rhodecode.is_test:
237 if rhodecode.is_test:
238 RhodeCodeCrypto = _RhodeCodeCryptoTest()
238 RhodeCodeCrypto = _RhodeCodeCryptoTest()
239 else:
239 else:
240 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
240 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
241
241
242 return RhodeCodeCrypto
242 return RhodeCodeCrypto
243
243
244
244
245 def get_crypt_password(password):
245 def get_crypt_password(password):
246 """
246 """
247 Create the hash of `password` with the active crypto backend.
247 Create the hash of `password` with the active crypto backend.
248
248
249 :param password: The cleartext password.
249 :param password: The cleartext password.
250 :type password: unicode
250 :type password: unicode
251 """
251 """
252 password = safe_str(password)
252 password = safe_str(password)
253 return crypto_backend().hash_create(password)
253 return crypto_backend().hash_create(password)
254
254
255
255
256 def check_password(password, hashed):
256 def check_password(password, hashed):
257 """
257 """
258 Check if the value in `password` matches the hash in `hashed`.
258 Check if the value in `password` matches the hash in `hashed`.
259
259
260 :param password: The cleartext password.
260 :param password: The cleartext password.
261 :type password: unicode
261 :type password: unicode
262
262
263 :param hashed: The expected hashed version of the password.
263 :param hashed: The expected hashed version of the password.
264 :type hashed: The hash has to be passed in in text representation.
264 :type hashed: The hash has to be passed in in text representation.
265 """
265 """
266 password = safe_str(password)
266 password = safe_str(password)
267 return crypto_backend().hash_check(password, hashed)
267 return crypto_backend().hash_check(password, hashed)
268
268
269
269
270 def generate_auth_token(data, salt=None):
270 def generate_auth_token(data, salt=None):
271 """
271 """
272 Generates API KEY from given string
272 Generates API KEY from given string
273 """
273 """
274
274
275 if salt is None:
275 if salt is None:
276 salt = os.urandom(16)
276 salt = os.urandom(16)
277 return hashlib.sha1(safe_str(data) + salt).hexdigest()
277 return hashlib.sha1(safe_str(data) + salt).hexdigest()
278
278
279
279
280 def get_came_from(request):
280 def get_came_from(request):
281 """
281 """
282 get query_string+path from request sanitized after removing auth_token
282 get query_string+path from request sanitized after removing auth_token
283 """
283 """
284 _req = request
284 _req = request
285
285
286 path = _req.path
286 path = _req.path
287 if 'auth_token' in _req.GET:
287 if 'auth_token' in _req.GET:
288 # sanitize the request and remove auth_token for redirection
288 # sanitize the request and remove auth_token for redirection
289 _req.GET.pop('auth_token')
289 _req.GET.pop('auth_token')
290 qs = _req.query_string
290 qs = _req.query_string
291 if qs:
291 if qs:
292 path += '?' + qs
292 path += '?' + qs
293
293
294 return path
294 return path
295
295
296
296
297 class CookieStoreWrapper(object):
297 class CookieStoreWrapper(object):
298
298
299 def __init__(self, cookie_store):
299 def __init__(self, cookie_store):
300 self.cookie_store = cookie_store
300 self.cookie_store = cookie_store
301
301
302 def __repr__(self):
302 def __repr__(self):
303 return 'CookieStore<%s>' % (self.cookie_store)
303 return 'CookieStore<%s>' % (self.cookie_store)
304
304
305 def get(self, key, other=None):
305 def get(self, key, other=None):
306 if isinstance(self.cookie_store, dict):
306 if isinstance(self.cookie_store, dict):
307 return self.cookie_store.get(key, other)
307 return self.cookie_store.get(key, other)
308 elif isinstance(self.cookie_store, AuthUser):
308 elif isinstance(self.cookie_store, AuthUser):
309 return self.cookie_store.__dict__.get(key, other)
309 return self.cookie_store.__dict__.get(key, other)
310
310
311
311
312 def _cached_perms_data(user_id, scope, user_is_admin,
312 def _cached_perms_data(user_id, scope, user_is_admin,
313 user_inherit_default_permissions, explicit, algo,
313 user_inherit_default_permissions, explicit, algo,
314 calculate_super_admin):
314 calculate_super_admin):
315
315
316 permissions = PermissionCalculator(
316 permissions = PermissionCalculator(
317 user_id, scope, user_is_admin, user_inherit_default_permissions,
317 user_id, scope, user_is_admin, user_inherit_default_permissions,
318 explicit, algo, calculate_super_admin)
318 explicit, algo, calculate_super_admin)
319 return permissions.calculate()
319 return permissions.calculate()
320
320
321
321
322 class PermOrigin(object):
322 class PermOrigin(object):
323 SUPER_ADMIN = 'superadmin'
323 SUPER_ADMIN = 'superadmin'
324 ARCHIVED = 'archived'
324 ARCHIVED = 'archived'
325
325
326 REPO_USER = 'user:%s'
326 REPO_USER = 'user:%s'
327 REPO_USERGROUP = 'usergroup:%s'
327 REPO_USERGROUP = 'usergroup:%s'
328 REPO_OWNER = 'repo.owner'
328 REPO_OWNER = 'repo.owner'
329 REPO_DEFAULT = 'repo.default'
329 REPO_DEFAULT = 'repo.default'
330 REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit'
330 REPO_DEFAULT_NO_INHERIT = 'repo.default.no.inherit'
331 REPO_PRIVATE = 'repo.private'
331 REPO_PRIVATE = 'repo.private'
332
332
333 REPOGROUP_USER = 'user:%s'
333 REPOGROUP_USER = 'user:%s'
334 REPOGROUP_USERGROUP = 'usergroup:%s'
334 REPOGROUP_USERGROUP = 'usergroup:%s'
335 REPOGROUP_OWNER = 'group.owner'
335 REPOGROUP_OWNER = 'group.owner'
336 REPOGROUP_DEFAULT = 'group.default'
336 REPOGROUP_DEFAULT = 'group.default'
337 REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit'
337 REPOGROUP_DEFAULT_NO_INHERIT = 'group.default.no.inherit'
338
338
339 USERGROUP_USER = 'user:%s'
339 USERGROUP_USER = 'user:%s'
340 USERGROUP_USERGROUP = 'usergroup:%s'
340 USERGROUP_USERGROUP = 'usergroup:%s'
341 USERGROUP_OWNER = 'usergroup.owner'
341 USERGROUP_OWNER = 'usergroup.owner'
342 USERGROUP_DEFAULT = 'usergroup.default'
342 USERGROUP_DEFAULT = 'usergroup.default'
343 USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit'
343 USERGROUP_DEFAULT_NO_INHERIT = 'usergroup.default.no.inherit'
344
344
345
345
346 class PermOriginDict(dict):
346 class PermOriginDict(dict):
347 """
347 """
348 A special dict used for tracking permissions along with their origins.
348 A special dict used for tracking permissions along with their origins.
349
349
350 `__setitem__` has been overridden to expect a tuple(perm, origin)
350 `__setitem__` has been overridden to expect a tuple(perm, origin)
351 `__getitem__` will return only the perm
351 `__getitem__` will return only the perm
352 `.perm_origin_stack` will return the stack of (perm, origin) set per key
352 `.perm_origin_stack` will return the stack of (perm, origin) set per key
353
353
354 >>> perms = PermOriginDict()
354 >>> perms = PermOriginDict()
355 >>> perms['resource'] = 'read', 'default'
355 >>> perms['resource'] = 'read', 'default'
356 >>> perms['resource']
356 >>> perms['resource']
357 'read'
357 'read'
358 >>> perms['resource'] = 'write', 'admin'
358 >>> perms['resource'] = 'write', 'admin'
359 >>> perms['resource']
359 >>> perms['resource']
360 'write'
360 'write'
361 >>> perms.perm_origin_stack
361 >>> perms.perm_origin_stack
362 {'resource': [('read', 'default'), ('write', 'admin')]}
362 {'resource': [('read', 'default'), ('write', 'admin')]}
363 """
363 """
364
364
365 def __init__(self, *args, **kw):
365 def __init__(self, *args, **kw):
366 dict.__init__(self, *args, **kw)
366 dict.__init__(self, *args, **kw)
367 self.perm_origin_stack = collections.OrderedDict()
367 self.perm_origin_stack = collections.OrderedDict()
368
368
369 def __setitem__(self, key, (perm, origin)):
369 def __setitem__(self, key, (perm, origin)):
370 self.perm_origin_stack.setdefault(key, []).append(
370 self.perm_origin_stack.setdefault(key, []).append(
371 (perm, origin))
371 (perm, origin))
372 dict.__setitem__(self, key, perm)
372 dict.__setitem__(self, key, perm)
373
373
374
374
375 class BranchPermOriginDict(PermOriginDict):
375 class BranchPermOriginDict(PermOriginDict):
376 """
376 """
377 Dedicated branch permissions dict, with tracking of patterns and origins.
377 Dedicated branch permissions dict, with tracking of patterns and origins.
378
378
379 >>> perms = BranchPermOriginDict()
379 >>> perms = BranchPermOriginDict()
380 >>> perms['resource'] = '*pattern', 'read', 'default'
380 >>> perms['resource'] = '*pattern', 'read', 'default'
381 >>> perms['resource']
381 >>> perms['resource']
382 {'*pattern': 'read'}
382 {'*pattern': 'read'}
383 >>> perms['resource'] = '*pattern', 'write', 'admin'
383 >>> perms['resource'] = '*pattern', 'write', 'admin'
384 >>> perms['resource']
384 >>> perms['resource']
385 {'*pattern': 'write'}
385 {'*pattern': 'write'}
386 >>> perms.perm_origin_stack
386 >>> perms.perm_origin_stack
387 {'resource': {'*pattern': [('read', 'default'), ('write', 'admin')]}}
387 {'resource': {'*pattern': [('read', 'default'), ('write', 'admin')]}}
388 """
388 """
389 def __setitem__(self, key, (pattern, perm, origin)):
389 def __setitem__(self, key, (pattern, perm, origin)):
390
390
391 self.perm_origin_stack.setdefault(key, {}) \
391 self.perm_origin_stack.setdefault(key, {}) \
392 .setdefault(pattern, []).append((perm, origin))
392 .setdefault(pattern, []).append((perm, origin))
393
393
394 if key in self:
394 if key in self:
395 self[key].__setitem__(pattern, perm)
395 self[key].__setitem__(pattern, perm)
396 else:
396 else:
397 patterns = collections.OrderedDict()
397 patterns = collections.OrderedDict()
398 patterns[pattern] = perm
398 patterns[pattern] = perm
399 dict.__setitem__(self, key, patterns)
399 dict.__setitem__(self, key, patterns)
400
400
401
401
402 class PermissionCalculator(object):
402 class PermissionCalculator(object):
403
403
404 def __init__(
404 def __init__(
405 self, user_id, scope, user_is_admin,
405 self, user_id, scope, user_is_admin,
406 user_inherit_default_permissions, explicit, algo,
406 user_inherit_default_permissions, explicit, algo,
407 calculate_super_admin_as_user=False):
407 calculate_super_admin_as_user=False):
408
408
409 self.user_id = user_id
409 self.user_id = user_id
410 self.user_is_admin = user_is_admin
410 self.user_is_admin = user_is_admin
411 self.inherit_default_permissions = user_inherit_default_permissions
411 self.inherit_default_permissions = user_inherit_default_permissions
412 self.explicit = explicit
412 self.explicit = explicit
413 self.algo = algo
413 self.algo = algo
414 self.calculate_super_admin_as_user = calculate_super_admin_as_user
414 self.calculate_super_admin_as_user = calculate_super_admin_as_user
415
415
416 scope = scope or {}
416 scope = scope or {}
417 self.scope_repo_id = scope.get('repo_id')
417 self.scope_repo_id = scope.get('repo_id')
418 self.scope_repo_group_id = scope.get('repo_group_id')
418 self.scope_repo_group_id = scope.get('repo_group_id')
419 self.scope_user_group_id = scope.get('user_group_id')
419 self.scope_user_group_id = scope.get('user_group_id')
420
420
421 self.default_user_id = User.get_default_user(cache=True).user_id
421 self.default_user_id = User.get_default_user(cache=True).user_id
422
422
423 self.permissions_repositories = PermOriginDict()
423 self.permissions_repositories = PermOriginDict()
424 self.permissions_repository_groups = PermOriginDict()
424 self.permissions_repository_groups = PermOriginDict()
425 self.permissions_user_groups = PermOriginDict()
425 self.permissions_user_groups = PermOriginDict()
426 self.permissions_repository_branches = BranchPermOriginDict()
426 self.permissions_repository_branches = BranchPermOriginDict()
427 self.permissions_global = set()
427 self.permissions_global = set()
428
428
429 self.default_repo_perms = Permission.get_default_repo_perms(
429 self.default_repo_perms = Permission.get_default_repo_perms(
430 self.default_user_id, self.scope_repo_id)
430 self.default_user_id, self.scope_repo_id)
431 self.default_repo_groups_perms = Permission.get_default_group_perms(
431 self.default_repo_groups_perms = Permission.get_default_group_perms(
432 self.default_user_id, self.scope_repo_group_id)
432 self.default_user_id, self.scope_repo_group_id)
433 self.default_user_group_perms = \
433 self.default_user_group_perms = \
434 Permission.get_default_user_group_perms(
434 Permission.get_default_user_group_perms(
435 self.default_user_id, self.scope_user_group_id)
435 self.default_user_id, self.scope_user_group_id)
436
436
437 # default branch perms
437 # default branch perms
438 self.default_branch_repo_perms = \
438 self.default_branch_repo_perms = \
439 Permission.get_default_repo_branch_perms(
439 Permission.get_default_repo_branch_perms(
440 self.default_user_id, self.scope_repo_id)
440 self.default_user_id, self.scope_repo_id)
441
441
442 def calculate(self):
442 def calculate(self):
443 if self.user_is_admin and not self.calculate_super_admin_as_user:
443 if self.user_is_admin and not self.calculate_super_admin_as_user:
444 return self._calculate_admin_permissions()
444 return self._calculate_admin_permissions()
445
445
446 self._calculate_global_default_permissions()
446 self._calculate_global_default_permissions()
447 self._calculate_global_permissions()
447 self._calculate_global_permissions()
448 self._calculate_default_permissions()
448 self._calculate_default_permissions()
449 self._calculate_repository_permissions()
449 self._calculate_repository_permissions()
450 self._calculate_repository_branch_permissions()
450 self._calculate_repository_branch_permissions()
451 self._calculate_repository_group_permissions()
451 self._calculate_repository_group_permissions()
452 self._calculate_user_group_permissions()
452 self._calculate_user_group_permissions()
453 return self._permission_structure()
453 return self._permission_structure()
454
454
455 def _calculate_admin_permissions(self):
455 def _calculate_admin_permissions(self):
456 """
456 """
457 admin user have all default rights for repositories
457 admin user have all default rights for repositories
458 and groups set to admin
458 and groups set to admin
459 """
459 """
460 self.permissions_global.add('hg.admin')
460 self.permissions_global.add('hg.admin')
461 self.permissions_global.add('hg.create.write_on_repogroup.true')
461 self.permissions_global.add('hg.create.write_on_repogroup.true')
462
462
463 # repositories
463 # repositories
464 for perm in self.default_repo_perms:
464 for perm in self.default_repo_perms:
465 r_k = perm.UserRepoToPerm.repository.repo_name
465 r_k = perm.UserRepoToPerm.repository.repo_name
466 archived = perm.UserRepoToPerm.repository.archived
466 archived = perm.UserRepoToPerm.repository.archived
467 p = 'repository.admin'
467 p = 'repository.admin'
468 self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN
468 self.permissions_repositories[r_k] = p, PermOrigin.SUPER_ADMIN
469 # special case for archived repositories, which we block still even for
469 # special case for archived repositories, which we block still even for
470 # super admins
470 # super admins
471 if archived:
471 if archived:
472 p = 'repository.read'
472 p = 'repository.read'
473 self.permissions_repositories[r_k] = p, PermOrigin.ARCHIVED
473 self.permissions_repositories[r_k] = p, PermOrigin.ARCHIVED
474
474
475 # repository groups
475 # repository groups
476 for perm in self.default_repo_groups_perms:
476 for perm in self.default_repo_groups_perms:
477 rg_k = perm.UserRepoGroupToPerm.group.group_name
477 rg_k = perm.UserRepoGroupToPerm.group.group_name
478 p = 'group.admin'
478 p = 'group.admin'
479 self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN
479 self.permissions_repository_groups[rg_k] = p, PermOrigin.SUPER_ADMIN
480
480
481 # user groups
481 # user groups
482 for perm in self.default_user_group_perms:
482 for perm in self.default_user_group_perms:
483 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
483 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
484 p = 'usergroup.admin'
484 p = 'usergroup.admin'
485 self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN
485 self.permissions_user_groups[u_k] = p, PermOrigin.SUPER_ADMIN
486
486
487 # branch permissions
487 # branch permissions
488 # since super-admin also can have custom rule permissions
488 # since super-admin also can have custom rule permissions
489 # we *always* need to calculate those inherited from default, and also explicit
489 # we *always* need to calculate those inherited from default, and also explicit
490 self._calculate_default_permissions_repository_branches(
490 self._calculate_default_permissions_repository_branches(
491 user_inherit_object_permissions=False)
491 user_inherit_object_permissions=False)
492 self._calculate_repository_branch_permissions()
492 self._calculate_repository_branch_permissions()
493
493
494 return self._permission_structure()
494 return self._permission_structure()
495
495
496 def _calculate_global_default_permissions(self):
496 def _calculate_global_default_permissions(self):
497 """
497 """
498 global permissions taken from the default user
498 global permissions taken from the default user
499 """
499 """
500 default_global_perms = UserToPerm.query()\
500 default_global_perms = UserToPerm.query()\
501 .filter(UserToPerm.user_id == self.default_user_id)\
501 .filter(UserToPerm.user_id == self.default_user_id)\
502 .options(joinedload(UserToPerm.permission))
502 .options(joinedload(UserToPerm.permission))
503
503
504 for perm in default_global_perms:
504 for perm in default_global_perms:
505 self.permissions_global.add(perm.permission.permission_name)
505 self.permissions_global.add(perm.permission.permission_name)
506
506
507 if self.user_is_admin:
507 if self.user_is_admin:
508 self.permissions_global.add('hg.admin')
508 self.permissions_global.add('hg.admin')
509 self.permissions_global.add('hg.create.write_on_repogroup.true')
509 self.permissions_global.add('hg.create.write_on_repogroup.true')
510
510
511 def _calculate_global_permissions(self):
511 def _calculate_global_permissions(self):
512 """
512 """
513 Set global system permissions with user permissions or permissions
513 Set global system permissions with user permissions or permissions
514 taken from the user groups of the current user.
514 taken from the user groups of the current user.
515
515
516 The permissions include repo creating, repo group creating, forking
516 The permissions include repo creating, repo group creating, forking
517 etc.
517 etc.
518 """
518 """
519
519
520 # now we read the defined permissions and overwrite what we have set
520 # now we read the defined permissions and overwrite what we have set
521 # before those can be configured from groups or users explicitly.
521 # before those can be configured from groups or users explicitly.
522
522
523 # In case we want to extend this list we should make sure
523 # In case we want to extend this list we should make sure
524 # this is in sync with User.DEFAULT_USER_PERMISSIONS definitions
524 # this is in sync with User.DEFAULT_USER_PERMISSIONS definitions
525 _configurable = frozenset([
525 _configurable = frozenset([
526 'hg.fork.none', 'hg.fork.repository',
526 'hg.fork.none', 'hg.fork.repository',
527 'hg.create.none', 'hg.create.repository',
527 'hg.create.none', 'hg.create.repository',
528 'hg.usergroup.create.false', 'hg.usergroup.create.true',
528 'hg.usergroup.create.false', 'hg.usergroup.create.true',
529 'hg.repogroup.create.false', 'hg.repogroup.create.true',
529 'hg.repogroup.create.false', 'hg.repogroup.create.true',
530 'hg.create.write_on_repogroup.false', 'hg.create.write_on_repogroup.true',
530 'hg.create.write_on_repogroup.false', 'hg.create.write_on_repogroup.true',
531 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
531 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
532 ])
532 ])
533
533
534 # USER GROUPS comes first user group global permissions
534 # USER GROUPS comes first user group global permissions
535 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
535 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
536 .options(joinedload(UserGroupToPerm.permission))\
536 .options(joinedload(UserGroupToPerm.permission))\
537 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
537 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
538 UserGroupMember.users_group_id))\
538 UserGroupMember.users_group_id))\
539 .filter(UserGroupMember.user_id == self.user_id)\
539 .filter(UserGroupMember.user_id == self.user_id)\
540 .order_by(UserGroupToPerm.users_group_id)\
540 .order_by(UserGroupToPerm.users_group_id)\
541 .all()
541 .all()
542
542
543 # need to group here by groups since user can be in more than
543 # need to group here by groups since user can be in more than
544 # one group, so we get all groups
544 # one group, so we get all groups
545 _explicit_grouped_perms = [
545 _explicit_grouped_perms = [
546 [x, list(y)] for x, y in
546 [x, list(y)] for x, y in
547 itertools.groupby(user_perms_from_users_groups,
547 itertools.groupby(user_perms_from_users_groups,
548 lambda _x: _x.users_group)]
548 lambda _x: _x.users_group)]
549
549
550 for gr, perms in _explicit_grouped_perms:
550 for gr, perms in _explicit_grouped_perms:
551 # since user can be in multiple groups iterate over them and
551 # since user can be in multiple groups iterate over them and
552 # select the lowest permissions first (more explicit)
552 # select the lowest permissions first (more explicit)
553 # TODO(marcink): do this^^
553 # TODO(marcink): do this^^
554
554
555 # group doesn't inherit default permissions so we actually set them
555 # group doesn't inherit default permissions so we actually set them
556 if not gr.inherit_default_permissions:
556 if not gr.inherit_default_permissions:
557 # NEED TO IGNORE all previously set configurable permissions
557 # NEED TO IGNORE all previously set configurable permissions
558 # and replace them with explicitly set from this user
558 # and replace them with explicitly set from this user
559 # group permissions
559 # group permissions
560 self.permissions_global = self.permissions_global.difference(
560 self.permissions_global = self.permissions_global.difference(
561 _configurable)
561 _configurable)
562 for perm in perms:
562 for perm in perms:
563 self.permissions_global.add(perm.permission.permission_name)
563 self.permissions_global.add(perm.permission.permission_name)
564
564
565 # user explicit global permissions
565 # user explicit global permissions
566 user_perms = Session().query(UserToPerm)\
566 user_perms = Session().query(UserToPerm)\
567 .options(joinedload(UserToPerm.permission))\
567 .options(joinedload(UserToPerm.permission))\
568 .filter(UserToPerm.user_id == self.user_id).all()
568 .filter(UserToPerm.user_id == self.user_id).all()
569
569
570 if not self.inherit_default_permissions:
570 if not self.inherit_default_permissions:
571 # NEED TO IGNORE all configurable permissions and
571 # NEED TO IGNORE all configurable permissions and
572 # replace them with explicitly set from this user permissions
572 # replace them with explicitly set from this user permissions
573 self.permissions_global = self.permissions_global.difference(
573 self.permissions_global = self.permissions_global.difference(
574 _configurable)
574 _configurable)
575 for perm in user_perms:
575 for perm in user_perms:
576 self.permissions_global.add(perm.permission.permission_name)
576 self.permissions_global.add(perm.permission.permission_name)
577
577
578 def _calculate_default_permissions_repositories(self, user_inherit_object_permissions):
578 def _calculate_default_permissions_repositories(self, user_inherit_object_permissions):
579 for perm in self.default_repo_perms:
579 for perm in self.default_repo_perms:
580 r_k = perm.UserRepoToPerm.repository.repo_name
580 r_k = perm.UserRepoToPerm.repository.repo_name
581 archived = perm.UserRepoToPerm.repository.archived
581 archived = perm.UserRepoToPerm.repository.archived
582 p = perm.Permission.permission_name
582 p = perm.Permission.permission_name
583 o = PermOrigin.REPO_DEFAULT
583 o = PermOrigin.REPO_DEFAULT
584 self.permissions_repositories[r_k] = p, o
584 self.permissions_repositories[r_k] = p, o
585
585
586 # if we decide this user isn't inheriting permissions from
586 # if we decide this user isn't inheriting permissions from
587 # default user we set him to .none so only explicit
587 # default user we set him to .none so only explicit
588 # permissions work
588 # permissions work
589 if not user_inherit_object_permissions:
589 if not user_inherit_object_permissions:
590 p = 'repository.none'
590 p = 'repository.none'
591 o = PermOrigin.REPO_DEFAULT_NO_INHERIT
591 o = PermOrigin.REPO_DEFAULT_NO_INHERIT
592 self.permissions_repositories[r_k] = p, o
592 self.permissions_repositories[r_k] = p, o
593
593
594 if perm.Repository.private and not (
594 if perm.Repository.private and not (
595 perm.Repository.user_id == self.user_id):
595 perm.Repository.user_id == self.user_id):
596 # disable defaults for private repos,
596 # disable defaults for private repos,
597 p = 'repository.none'
597 p = 'repository.none'
598 o = PermOrigin.REPO_PRIVATE
598 o = PermOrigin.REPO_PRIVATE
599 self.permissions_repositories[r_k] = p, o
599 self.permissions_repositories[r_k] = p, o
600
600
601 elif perm.Repository.user_id == self.user_id:
601 elif perm.Repository.user_id == self.user_id:
602 # set admin if owner
602 # set admin if owner
603 p = 'repository.admin'
603 p = 'repository.admin'
604 o = PermOrigin.REPO_OWNER
604 o = PermOrigin.REPO_OWNER
605 self.permissions_repositories[r_k] = p, o
605 self.permissions_repositories[r_k] = p, o
606
606
607 if self.user_is_admin:
607 if self.user_is_admin:
608 p = 'repository.admin'
608 p = 'repository.admin'
609 o = PermOrigin.SUPER_ADMIN
609 o = PermOrigin.SUPER_ADMIN
610 self.permissions_repositories[r_k] = p, o
610 self.permissions_repositories[r_k] = p, o
611
611
612 # finally in case of archived repositories, we downgrade higher
612 # finally in case of archived repositories, we downgrade higher
613 # permissions to read
613 # permissions to read
614 if archived:
614 if archived:
615 current_perm = self.permissions_repositories[r_k]
615 current_perm = self.permissions_repositories[r_k]
616 if current_perm in ['repository.write', 'repository.admin']:
616 if current_perm in ['repository.write', 'repository.admin']:
617 p = 'repository.read'
617 p = 'repository.read'
618 o = PermOrigin.ARCHIVED
618 o = PermOrigin.ARCHIVED
619 self.permissions_repositories[r_k] = p, o
619 self.permissions_repositories[r_k] = p, o
620
620
621 def _calculate_default_permissions_repository_branches(self, user_inherit_object_permissions):
621 def _calculate_default_permissions_repository_branches(self, user_inherit_object_permissions):
622 for perm in self.default_branch_repo_perms:
622 for perm in self.default_branch_repo_perms:
623
623
624 r_k = perm.UserRepoToPerm.repository.repo_name
624 r_k = perm.UserRepoToPerm.repository.repo_name
625 p = perm.Permission.permission_name
625 p = perm.Permission.permission_name
626 pattern = perm.UserToRepoBranchPermission.branch_pattern
626 pattern = perm.UserToRepoBranchPermission.branch_pattern
627 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
627 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
628
628
629 if not self.explicit:
629 if not self.explicit:
630 cur_perm = self.permissions_repository_branches.get(r_k)
630 cur_perm = self.permissions_repository_branches.get(r_k)
631 if cur_perm:
631 if cur_perm:
632 cur_perm = cur_perm[pattern]
632 cur_perm = cur_perm[pattern]
633 cur_perm = cur_perm or 'branch.none'
633 cur_perm = cur_perm or 'branch.none'
634
634
635 p = self._choose_permission(p, cur_perm)
635 p = self._choose_permission(p, cur_perm)
636
636
637 # NOTE(marcink): register all pattern/perm instances in this
637 # NOTE(marcink): register all pattern/perm instances in this
638 # special dict that aggregates entries
638 # special dict that aggregates entries
639 self.permissions_repository_branches[r_k] = pattern, p, o
639 self.permissions_repository_branches[r_k] = pattern, p, o
640
640
641 def _calculate_default_permissions_repository_groups(self, user_inherit_object_permissions):
641 def _calculate_default_permissions_repository_groups(self, user_inherit_object_permissions):
642 for perm in self.default_repo_groups_perms:
642 for perm in self.default_repo_groups_perms:
643 rg_k = perm.UserRepoGroupToPerm.group.group_name
643 rg_k = perm.UserRepoGroupToPerm.group.group_name
644 p = perm.Permission.permission_name
644 p = perm.Permission.permission_name
645 o = PermOrigin.REPOGROUP_DEFAULT
645 o = PermOrigin.REPOGROUP_DEFAULT
646 self.permissions_repository_groups[rg_k] = p, o
646 self.permissions_repository_groups[rg_k] = p, o
647
647
648 # if we decide this user isn't inheriting permissions from default
648 # if we decide this user isn't inheriting permissions from default
649 # user we set him to .none so only explicit permissions work
649 # user we set him to .none so only explicit permissions work
650 if not user_inherit_object_permissions:
650 if not user_inherit_object_permissions:
651 p = 'group.none'
651 p = 'group.none'
652 o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT
652 o = PermOrigin.REPOGROUP_DEFAULT_NO_INHERIT
653 self.permissions_repository_groups[rg_k] = p, o
653 self.permissions_repository_groups[rg_k] = p, o
654
654
655 if perm.RepoGroup.user_id == self.user_id:
655 if perm.RepoGroup.user_id == self.user_id:
656 # set admin if owner
656 # set admin if owner
657 p = 'group.admin'
657 p = 'group.admin'
658 o = PermOrigin.REPOGROUP_OWNER
658 o = PermOrigin.REPOGROUP_OWNER
659 self.permissions_repository_groups[rg_k] = p, o
659 self.permissions_repository_groups[rg_k] = p, o
660
660
661 if self.user_is_admin:
661 if self.user_is_admin:
662 p = 'group.admin'
662 p = 'group.admin'
663 o = PermOrigin.SUPER_ADMIN
663 o = PermOrigin.SUPER_ADMIN
664 self.permissions_repository_groups[rg_k] = p, o
664 self.permissions_repository_groups[rg_k] = p, o
665
665
666 def _calculate_default_permissions_user_groups(self, user_inherit_object_permissions):
666 def _calculate_default_permissions_user_groups(self, user_inherit_object_permissions):
667 for perm in self.default_user_group_perms:
667 for perm in self.default_user_group_perms:
668 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
668 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
669 p = perm.Permission.permission_name
669 p = perm.Permission.permission_name
670 o = PermOrigin.USERGROUP_DEFAULT
670 o = PermOrigin.USERGROUP_DEFAULT
671 self.permissions_user_groups[u_k] = p, o
671 self.permissions_user_groups[u_k] = p, o
672
672
673 # if we decide this user isn't inheriting permissions from default
673 # if we decide this user isn't inheriting permissions from default
674 # user we set him to .none so only explicit permissions work
674 # user we set him to .none so only explicit permissions work
675 if not user_inherit_object_permissions:
675 if not user_inherit_object_permissions:
676 p = 'usergroup.none'
676 p = 'usergroup.none'
677 o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT
677 o = PermOrigin.USERGROUP_DEFAULT_NO_INHERIT
678 self.permissions_user_groups[u_k] = p, o
678 self.permissions_user_groups[u_k] = p, o
679
679
680 if perm.UserGroup.user_id == self.user_id:
680 if perm.UserGroup.user_id == self.user_id:
681 # set admin if owner
681 # set admin if owner
682 p = 'usergroup.admin'
682 p = 'usergroup.admin'
683 o = PermOrigin.USERGROUP_OWNER
683 o = PermOrigin.USERGROUP_OWNER
684 self.permissions_user_groups[u_k] = p, o
684 self.permissions_user_groups[u_k] = p, o
685
685
686 if self.user_is_admin:
686 if self.user_is_admin:
687 p = 'usergroup.admin'
687 p = 'usergroup.admin'
688 o = PermOrigin.SUPER_ADMIN
688 o = PermOrigin.SUPER_ADMIN
689 self.permissions_user_groups[u_k] = p, o
689 self.permissions_user_groups[u_k] = p, o
690
690
691 def _calculate_default_permissions(self):
691 def _calculate_default_permissions(self):
692 """
692 """
693 Set default user permissions for repositories, repository branches,
693 Set default user permissions for repositories, repository branches,
694 repository groups, user groups taken from the default user.
694 repository groups, user groups taken from the default user.
695
695
696 Calculate inheritance of object permissions based on what we have now
696 Calculate inheritance of object permissions based on what we have now
697 in GLOBAL permissions. We check if .false is in GLOBAL since this is
697 in GLOBAL permissions. We check if .false is in GLOBAL since this is
698 explicitly set. Inherit is the opposite of .false being there.
698 explicitly set. Inherit is the opposite of .false being there.
699
699
700 .. note::
700 .. note::
701
701
702 the syntax is little bit odd but what we need to check here is
702 the syntax is little bit odd but what we need to check here is
703 the opposite of .false permission being in the list so even for
703 the opposite of .false permission being in the list so even for
704 inconsistent state when both .true/.false is there
704 inconsistent state when both .true/.false is there
705 .false is more important
705 .false is more important
706
706
707 """
707 """
708 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
708 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
709 in self.permissions_global)
709 in self.permissions_global)
710
710
711 # default permissions inherited from `default` user permissions
711 # default permissions inherited from `default` user permissions
712 self._calculate_default_permissions_repositories(
712 self._calculate_default_permissions_repositories(
713 user_inherit_object_permissions)
713 user_inherit_object_permissions)
714
714
715 self._calculate_default_permissions_repository_branches(
715 self._calculate_default_permissions_repository_branches(
716 user_inherit_object_permissions)
716 user_inherit_object_permissions)
717
717
718 self._calculate_default_permissions_repository_groups(
718 self._calculate_default_permissions_repository_groups(
719 user_inherit_object_permissions)
719 user_inherit_object_permissions)
720
720
721 self._calculate_default_permissions_user_groups(
721 self._calculate_default_permissions_user_groups(
722 user_inherit_object_permissions)
722 user_inherit_object_permissions)
723
723
724 def _calculate_repository_permissions(self):
724 def _calculate_repository_permissions(self):
725 """
725 """
726 Repository permissions for the current user.
726 Repository permissions for the current user.
727
727
728 Check if the user is part of user groups for this repository and
728 Check if the user is part of user groups for this repository and
729 fill in the permission from it. `_choose_permission` decides of which
729 fill in the permission from it. `_choose_permission` decides of which
730 permission should be selected based on selected method.
730 permission should be selected based on selected method.
731 """
731 """
732
732
733 # user group for repositories permissions
733 # user group for repositories permissions
734 user_repo_perms_from_user_group = Permission\
734 user_repo_perms_from_user_group = Permission\
735 .get_default_repo_perms_from_user_group(
735 .get_default_repo_perms_from_user_group(
736 self.user_id, self.scope_repo_id)
736 self.user_id, self.scope_repo_id)
737
737
738 multiple_counter = collections.defaultdict(int)
738 multiple_counter = collections.defaultdict(int)
739 for perm in user_repo_perms_from_user_group:
739 for perm in user_repo_perms_from_user_group:
740 r_k = perm.UserGroupRepoToPerm.repository.repo_name
740 r_k = perm.UserGroupRepoToPerm.repository.repo_name
741 multiple_counter[r_k] += 1
741 multiple_counter[r_k] += 1
742 p = perm.Permission.permission_name
742 p = perm.Permission.permission_name
743 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
743 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
744 .users_group.users_group_name
744 .users_group.users_group_name
745
745
746 if multiple_counter[r_k] > 1:
746 if multiple_counter[r_k] > 1:
747 cur_perm = self.permissions_repositories[r_k]
747 cur_perm = self.permissions_repositories[r_k]
748 p = self._choose_permission(p, cur_perm)
748 p = self._choose_permission(p, cur_perm)
749
749
750 self.permissions_repositories[r_k] = p, o
750 self.permissions_repositories[r_k] = p, o
751
751
752 if perm.Repository.user_id == self.user_id:
752 if perm.Repository.user_id == self.user_id:
753 # set admin if owner
753 # set admin if owner
754 p = 'repository.admin'
754 p = 'repository.admin'
755 o = PermOrigin.REPO_OWNER
755 o = PermOrigin.REPO_OWNER
756 self.permissions_repositories[r_k] = p, o
756 self.permissions_repositories[r_k] = p, o
757
757
758 if self.user_is_admin:
758 if self.user_is_admin:
759 p = 'repository.admin'
759 p = 'repository.admin'
760 o = PermOrigin.SUPER_ADMIN
760 o = PermOrigin.SUPER_ADMIN
761 self.permissions_repositories[r_k] = p, o
761 self.permissions_repositories[r_k] = p, o
762
762
763 # user explicit permissions for repositories, overrides any specified
763 # user explicit permissions for repositories, overrides any specified
764 # by the group permission
764 # by the group permission
765 user_repo_perms = Permission.get_default_repo_perms(
765 user_repo_perms = Permission.get_default_repo_perms(
766 self.user_id, self.scope_repo_id)
766 self.user_id, self.scope_repo_id)
767 for perm in user_repo_perms:
767 for perm in user_repo_perms:
768 r_k = perm.UserRepoToPerm.repository.repo_name
768 r_k = perm.UserRepoToPerm.repository.repo_name
769 p = perm.Permission.permission_name
769 p = perm.Permission.permission_name
770 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
770 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
771
771
772 if not self.explicit:
772 if not self.explicit:
773 cur_perm = self.permissions_repositories.get(
773 cur_perm = self.permissions_repositories.get(
774 r_k, 'repository.none')
774 r_k, 'repository.none')
775 p = self._choose_permission(p, cur_perm)
775 p = self._choose_permission(p, cur_perm)
776
776
777 self.permissions_repositories[r_k] = p, o
777 self.permissions_repositories[r_k] = p, o
778
778
779 if perm.Repository.user_id == self.user_id:
779 if perm.Repository.user_id == self.user_id:
780 # set admin if owner
780 # set admin if owner
781 p = 'repository.admin'
781 p = 'repository.admin'
782 o = PermOrigin.REPO_OWNER
782 o = PermOrigin.REPO_OWNER
783 self.permissions_repositories[r_k] = p, o
783 self.permissions_repositories[r_k] = p, o
784
784
785 if self.user_is_admin:
785 if self.user_is_admin:
786 p = 'repository.admin'
786 p = 'repository.admin'
787 o = PermOrigin.SUPER_ADMIN
787 o = PermOrigin.SUPER_ADMIN
788 self.permissions_repositories[r_k] = p, o
788 self.permissions_repositories[r_k] = p, o
789
789
790 def _calculate_repository_branch_permissions(self):
790 def _calculate_repository_branch_permissions(self):
791 # user group for repositories permissions
791 # user group for repositories permissions
792 user_repo_branch_perms_from_user_group = Permission\
792 user_repo_branch_perms_from_user_group = Permission\
793 .get_default_repo_branch_perms_from_user_group(
793 .get_default_repo_branch_perms_from_user_group(
794 self.user_id, self.scope_repo_id)
794 self.user_id, self.scope_repo_id)
795
795
796 multiple_counter = collections.defaultdict(int)
796 multiple_counter = collections.defaultdict(int)
797 for perm in user_repo_branch_perms_from_user_group:
797 for perm in user_repo_branch_perms_from_user_group:
798 r_k = perm.UserGroupRepoToPerm.repository.repo_name
798 r_k = perm.UserGroupRepoToPerm.repository.repo_name
799 p = perm.Permission.permission_name
799 p = perm.Permission.permission_name
800 pattern = perm.UserGroupToRepoBranchPermission.branch_pattern
800 pattern = perm.UserGroupToRepoBranchPermission.branch_pattern
801 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
801 o = PermOrigin.REPO_USERGROUP % perm.UserGroupRepoToPerm\
802 .users_group.users_group_name
802 .users_group.users_group_name
803
803
804 multiple_counter[r_k] += 1
804 multiple_counter[r_k] += 1
805 if multiple_counter[r_k] > 1:
805 if multiple_counter[r_k] > 1:
806 cur_perm = self.permissions_repository_branches[r_k][pattern]
806 cur_perm = self.permissions_repository_branches[r_k][pattern]
807 p = self._choose_permission(p, cur_perm)
807 p = self._choose_permission(p, cur_perm)
808
808
809 self.permissions_repository_branches[r_k] = pattern, p, o
809 self.permissions_repository_branches[r_k] = pattern, p, o
810
810
811 # user explicit branch permissions for repositories, overrides
811 # user explicit branch permissions for repositories, overrides
812 # any specified by the group permission
812 # any specified by the group permission
813 user_repo_branch_perms = Permission.get_default_repo_branch_perms(
813 user_repo_branch_perms = Permission.get_default_repo_branch_perms(
814 self.user_id, self.scope_repo_id)
814 self.user_id, self.scope_repo_id)
815
815
816 for perm in user_repo_branch_perms:
816 for perm in user_repo_branch_perms:
817
817
818 r_k = perm.UserRepoToPerm.repository.repo_name
818 r_k = perm.UserRepoToPerm.repository.repo_name
819 p = perm.Permission.permission_name
819 p = perm.Permission.permission_name
820 pattern = perm.UserToRepoBranchPermission.branch_pattern
820 pattern = perm.UserToRepoBranchPermission.branch_pattern
821 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
821 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
822
822
823 if not self.explicit:
823 if not self.explicit:
824 cur_perm = self.permissions_repository_branches.get(r_k)
824 cur_perm = self.permissions_repository_branches.get(r_k)
825 if cur_perm:
825 if cur_perm:
826 cur_perm = cur_perm[pattern]
826 cur_perm = cur_perm[pattern]
827 cur_perm = cur_perm or 'branch.none'
827 cur_perm = cur_perm or 'branch.none'
828 p = self._choose_permission(p, cur_perm)
828 p = self._choose_permission(p, cur_perm)
829
829
830 # NOTE(marcink): register all pattern/perm instances in this
830 # NOTE(marcink): register all pattern/perm instances in this
831 # special dict that aggregates entries
831 # special dict that aggregates entries
832 self.permissions_repository_branches[r_k] = pattern, p, o
832 self.permissions_repository_branches[r_k] = pattern, p, o
833
833
834 def _calculate_repository_group_permissions(self):
834 def _calculate_repository_group_permissions(self):
835 """
835 """
836 Repository group permissions for the current user.
836 Repository group permissions for the current user.
837
837
838 Check if the user is part of user groups for repository groups and
838 Check if the user is part of user groups for repository groups and
839 fill in the permissions from it. `_choose_permission` decides of which
839 fill in the permissions from it. `_choose_permission` decides of which
840 permission should be selected based on selected method.
840 permission should be selected based on selected method.
841 """
841 """
842 # user group for repo groups permissions
842 # user group for repo groups permissions
843 user_repo_group_perms_from_user_group = Permission\
843 user_repo_group_perms_from_user_group = Permission\
844 .get_default_group_perms_from_user_group(
844 .get_default_group_perms_from_user_group(
845 self.user_id, self.scope_repo_group_id)
845 self.user_id, self.scope_repo_group_id)
846
846
847 multiple_counter = collections.defaultdict(int)
847 multiple_counter = collections.defaultdict(int)
848 for perm in user_repo_group_perms_from_user_group:
848 for perm in user_repo_group_perms_from_user_group:
849 rg_k = perm.UserGroupRepoGroupToPerm.group.group_name
849 rg_k = perm.UserGroupRepoGroupToPerm.group.group_name
850 multiple_counter[rg_k] += 1
850 multiple_counter[rg_k] += 1
851 o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\
851 o = PermOrigin.REPOGROUP_USERGROUP % perm.UserGroupRepoGroupToPerm\
852 .users_group.users_group_name
852 .users_group.users_group_name
853 p = perm.Permission.permission_name
853 p = perm.Permission.permission_name
854
854
855 if multiple_counter[rg_k] > 1:
855 if multiple_counter[rg_k] > 1:
856 cur_perm = self.permissions_repository_groups[rg_k]
856 cur_perm = self.permissions_repository_groups[rg_k]
857 p = self._choose_permission(p, cur_perm)
857 p = self._choose_permission(p, cur_perm)
858 self.permissions_repository_groups[rg_k] = p, o
858 self.permissions_repository_groups[rg_k] = p, o
859
859
860 if perm.RepoGroup.user_id == self.user_id:
860 if perm.RepoGroup.user_id == self.user_id:
861 # set admin if owner, even for member of other user group
861 # set admin if owner, even for member of other user group
862 p = 'group.admin'
862 p = 'group.admin'
863 o = PermOrigin.REPOGROUP_OWNER
863 o = PermOrigin.REPOGROUP_OWNER
864 self.permissions_repository_groups[rg_k] = p, o
864 self.permissions_repository_groups[rg_k] = p, o
865
865
866 if self.user_is_admin:
866 if self.user_is_admin:
867 p = 'group.admin'
867 p = 'group.admin'
868 o = PermOrigin.SUPER_ADMIN
868 o = PermOrigin.SUPER_ADMIN
869 self.permissions_repository_groups[rg_k] = p, o
869 self.permissions_repository_groups[rg_k] = p, o
870
870
871 # user explicit permissions for repository groups
871 # user explicit permissions for repository groups
872 user_repo_groups_perms = Permission.get_default_group_perms(
872 user_repo_groups_perms = Permission.get_default_group_perms(
873 self.user_id, self.scope_repo_group_id)
873 self.user_id, self.scope_repo_group_id)
874 for perm in user_repo_groups_perms:
874 for perm in user_repo_groups_perms:
875 rg_k = perm.UserRepoGroupToPerm.group.group_name
875 rg_k = perm.UserRepoGroupToPerm.group.group_name
876 o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\
876 o = PermOrigin.REPOGROUP_USER % perm.UserRepoGroupToPerm\
877 .user.username
877 .user.username
878 p = perm.Permission.permission_name
878 p = perm.Permission.permission_name
879
879
880 if not self.explicit:
880 if not self.explicit:
881 cur_perm = self.permissions_repository_groups.get(rg_k, 'group.none')
881 cur_perm = self.permissions_repository_groups.get(rg_k, 'group.none')
882 p = self._choose_permission(p, cur_perm)
882 p = self._choose_permission(p, cur_perm)
883
883
884 self.permissions_repository_groups[rg_k] = p, o
884 self.permissions_repository_groups[rg_k] = p, o
885
885
886 if perm.RepoGroup.user_id == self.user_id:
886 if perm.RepoGroup.user_id == self.user_id:
887 # set admin if owner
887 # set admin if owner
888 p = 'group.admin'
888 p = 'group.admin'
889 o = PermOrigin.REPOGROUP_OWNER
889 o = PermOrigin.REPOGROUP_OWNER
890 self.permissions_repository_groups[rg_k] = p, o
890 self.permissions_repository_groups[rg_k] = p, o
891
891
892 if self.user_is_admin:
892 if self.user_is_admin:
893 p = 'group.admin'
893 p = 'group.admin'
894 o = PermOrigin.SUPER_ADMIN
894 o = PermOrigin.SUPER_ADMIN
895 self.permissions_repository_groups[rg_k] = p, o
895 self.permissions_repository_groups[rg_k] = p, o
896
896
897 def _calculate_user_group_permissions(self):
897 def _calculate_user_group_permissions(self):
898 """
898 """
899 User group permissions for the current user.
899 User group permissions for the current user.
900 """
900 """
901 # user group for user group permissions
901 # user group for user group permissions
902 user_group_from_user_group = Permission\
902 user_group_from_user_group = Permission\
903 .get_default_user_group_perms_from_user_group(
903 .get_default_user_group_perms_from_user_group(
904 self.user_id, self.scope_user_group_id)
904 self.user_id, self.scope_user_group_id)
905
905
906 multiple_counter = collections.defaultdict(int)
906 multiple_counter = collections.defaultdict(int)
907 for perm in user_group_from_user_group:
907 for perm in user_group_from_user_group:
908 ug_k = perm.UserGroupUserGroupToPerm\
908 ug_k = perm.UserGroupUserGroupToPerm\
909 .target_user_group.users_group_name
909 .target_user_group.users_group_name
910 multiple_counter[ug_k] += 1
910 multiple_counter[ug_k] += 1
911 o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\
911 o = PermOrigin.USERGROUP_USERGROUP % perm.UserGroupUserGroupToPerm\
912 .user_group.users_group_name
912 .user_group.users_group_name
913 p = perm.Permission.permission_name
913 p = perm.Permission.permission_name
914
914
915 if multiple_counter[ug_k] > 1:
915 if multiple_counter[ug_k] > 1:
916 cur_perm = self.permissions_user_groups[ug_k]
916 cur_perm = self.permissions_user_groups[ug_k]
917 p = self._choose_permission(p, cur_perm)
917 p = self._choose_permission(p, cur_perm)
918
918
919 self.permissions_user_groups[ug_k] = p, o
919 self.permissions_user_groups[ug_k] = p, o
920
920
921 if perm.UserGroup.user_id == self.user_id:
921 if perm.UserGroup.user_id == self.user_id:
922 # set admin if owner, even for member of other user group
922 # set admin if owner, even for member of other user group
923 p = 'usergroup.admin'
923 p = 'usergroup.admin'
924 o = PermOrigin.USERGROUP_OWNER
924 o = PermOrigin.USERGROUP_OWNER
925 self.permissions_user_groups[ug_k] = p, o
925 self.permissions_user_groups[ug_k] = p, o
926
926
927 if self.user_is_admin:
927 if self.user_is_admin:
928 p = 'usergroup.admin'
928 p = 'usergroup.admin'
929 o = PermOrigin.SUPER_ADMIN
929 o = PermOrigin.SUPER_ADMIN
930 self.permissions_user_groups[ug_k] = p, o
930 self.permissions_user_groups[ug_k] = p, o
931
931
932 # user explicit permission for user groups
932 # user explicit permission for user groups
933 user_user_groups_perms = Permission.get_default_user_group_perms(
933 user_user_groups_perms = Permission.get_default_user_group_perms(
934 self.user_id, self.scope_user_group_id)
934 self.user_id, self.scope_user_group_id)
935 for perm in user_user_groups_perms:
935 for perm in user_user_groups_perms:
936 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
936 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
937 o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\
937 o = PermOrigin.USERGROUP_USER % perm.UserUserGroupToPerm\
938 .user.username
938 .user.username
939 p = perm.Permission.permission_name
939 p = perm.Permission.permission_name
940
940
941 if not self.explicit:
941 if not self.explicit:
942 cur_perm = self.permissions_user_groups.get(ug_k, 'usergroup.none')
942 cur_perm = self.permissions_user_groups.get(ug_k, 'usergroup.none')
943 p = self._choose_permission(p, cur_perm)
943 p = self._choose_permission(p, cur_perm)
944
944
945 self.permissions_user_groups[ug_k] = p, o
945 self.permissions_user_groups[ug_k] = p, o
946
946
947 if perm.UserGroup.user_id == self.user_id:
947 if perm.UserGroup.user_id == self.user_id:
948 # set admin if owner
948 # set admin if owner
949 p = 'usergroup.admin'
949 p = 'usergroup.admin'
950 o = PermOrigin.USERGROUP_OWNER
950 o = PermOrigin.USERGROUP_OWNER
951 self.permissions_user_groups[ug_k] = p, o
951 self.permissions_user_groups[ug_k] = p, o
952
952
953 if self.user_is_admin:
953 if self.user_is_admin:
954 p = 'usergroup.admin'
954 p = 'usergroup.admin'
955 o = PermOrigin.SUPER_ADMIN
955 o = PermOrigin.SUPER_ADMIN
956 self.permissions_user_groups[ug_k] = p, o
956 self.permissions_user_groups[ug_k] = p, o
957
957
958 def _choose_permission(self, new_perm, cur_perm):
958 def _choose_permission(self, new_perm, cur_perm):
959 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
959 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
960 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
960 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
961 if self.algo == 'higherwin':
961 if self.algo == 'higherwin':
962 if new_perm_val > cur_perm_val:
962 if new_perm_val > cur_perm_val:
963 return new_perm
963 return new_perm
964 return cur_perm
964 return cur_perm
965 elif self.algo == 'lowerwin':
965 elif self.algo == 'lowerwin':
966 if new_perm_val < cur_perm_val:
966 if new_perm_val < cur_perm_val:
967 return new_perm
967 return new_perm
968 return cur_perm
968 return cur_perm
969
969
970 def _permission_structure(self):
970 def _permission_structure(self):
971 return {
971 return {
972 'global': self.permissions_global,
972 'global': self.permissions_global,
973 'repositories': self.permissions_repositories,
973 'repositories': self.permissions_repositories,
974 'repository_branches': self.permissions_repository_branches,
974 'repository_branches': self.permissions_repository_branches,
975 'repositories_groups': self.permissions_repository_groups,
975 'repositories_groups': self.permissions_repository_groups,
976 'user_groups': self.permissions_user_groups,
976 'user_groups': self.permissions_user_groups,
977 }
977 }
978
978
979
979
980 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
980 def allowed_auth_token_access(view_name, auth_token, whitelist=None):
981 """
981 """
982 Check if given controller_name is in whitelist of auth token access
982 Check if given controller_name is in whitelist of auth token access
983 """
983 """
984 if not whitelist:
984 if not whitelist:
985 from rhodecode import CONFIG
985 from rhodecode import CONFIG
986 whitelist = aslist(
986 whitelist = aslist(
987 CONFIG.get('api_access_controllers_whitelist'), sep=',')
987 CONFIG.get('api_access_controllers_whitelist'), sep=',')
988 # backward compat translation
988 # backward compat translation
989 compat = {
989 compat = {
990 # old controller, new VIEW
990 # old controller, new VIEW
991 'ChangesetController:*': 'RepoCommitsView:*',
991 'ChangesetController:*': 'RepoCommitsView:*',
992 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
992 'ChangesetController:changeset_patch': 'RepoCommitsView:repo_commit_patch',
993 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
993 'ChangesetController:changeset_raw': 'RepoCommitsView:repo_commit_raw',
994 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
994 'FilesController:raw': 'RepoCommitsView:repo_commit_raw',
995 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
995 'FilesController:archivefile': 'RepoFilesView:repo_archivefile',
996 'GistsController:*': 'GistView:*',
996 'GistsController:*': 'GistView:*',
997 }
997 }
998
998
999 log.debug(
999 log.debug(
1000 'Allowed views for AUTH TOKEN access: %s', whitelist)
1000 'Allowed views for AUTH TOKEN access: %s', whitelist)
1001 auth_token_access_valid = False
1001 auth_token_access_valid = False
1002
1002
1003 for entry in whitelist:
1003 for entry in whitelist:
1004 token_match = True
1004 token_match = True
1005 if entry in compat:
1005 if entry in compat:
1006 # translate from old Controllers to Pyramid Views
1006 # translate from old Controllers to Pyramid Views
1007 entry = compat[entry]
1007 entry = compat[entry]
1008
1008
1009 if '@' in entry:
1009 if '@' in entry:
1010 # specific AuthToken
1010 # specific AuthToken
1011 entry, allowed_token = entry.split('@', 1)
1011 entry, allowed_token = entry.split('@', 1)
1012 token_match = auth_token == allowed_token
1012 token_match = auth_token == allowed_token
1013
1013
1014 if fnmatch.fnmatch(view_name, entry) and token_match:
1014 if fnmatch.fnmatch(view_name, entry) and token_match:
1015 auth_token_access_valid = True
1015 auth_token_access_valid = True
1016 break
1016 break
1017
1017
1018 if auth_token_access_valid:
1018 if auth_token_access_valid:
1019 log.debug('view: `%s` matches entry in whitelist: %s',
1019 log.debug('view: `%s` matches entry in whitelist: %s',
1020 view_name, whitelist)
1020 view_name, whitelist)
1021
1021
1022 else:
1022 else:
1023 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
1023 msg = ('view: `%s` does *NOT* match any entry in whitelist: %s'
1024 % (view_name, whitelist))
1024 % (view_name, whitelist))
1025 if auth_token:
1025 if auth_token:
1026 # if we use auth token key and don't have access it's a warning
1026 # if we use auth token key and don't have access it's a warning
1027 log.warning(msg)
1027 log.warning(msg)
1028 else:
1028 else:
1029 log.debug(msg)
1029 log.debug(msg)
1030
1030
1031 return auth_token_access_valid
1031 return auth_token_access_valid
1032
1032
1033
1033
1034 class AuthUser(object):
1034 class AuthUser(object):
1035 """
1035 """
1036 A simple object that handles all attributes of user in RhodeCode
1036 A simple object that handles all attributes of user in RhodeCode
1037
1037
1038 It does lookup based on API key,given user, or user present in session
1038 It does lookup based on API key,given user, or user present in session
1039 Then it fills all required information for such user. It also checks if
1039 Then it fills all required information for such user. It also checks if
1040 anonymous access is enabled and if so, it returns default user as logged in
1040 anonymous access is enabled and if so, it returns default user as logged in
1041 """
1041 """
1042 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
1042 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
1043
1043
1044 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
1044 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
1045
1045
1046 self.user_id = user_id
1046 self.user_id = user_id
1047 self._api_key = api_key
1047 self._api_key = api_key
1048
1048
1049 self.api_key = None
1049 self.api_key = None
1050 self.username = username
1050 self.username = username
1051 self.ip_addr = ip_addr
1051 self.ip_addr = ip_addr
1052 self.name = ''
1052 self.name = ''
1053 self.lastname = ''
1053 self.lastname = ''
1054 self.first_name = ''
1054 self.first_name = ''
1055 self.last_name = ''
1055 self.last_name = ''
1056 self.email = ''
1056 self.email = ''
1057 self.is_authenticated = False
1057 self.is_authenticated = False
1058 self.admin = False
1058 self.admin = False
1059 self.inherit_default_permissions = False
1059 self.inherit_default_permissions = False
1060 self.password = ''
1060 self.password = ''
1061
1061
1062 self.anonymous_user = None # propagated on propagate_data
1062 self.anonymous_user = None # propagated on propagate_data
1063 self.propagate_data()
1063 self.propagate_data()
1064 self._instance = None
1064 self._instance = None
1065 self._permissions_scoped_cache = {} # used to bind scoped calculation
1065 self._permissions_scoped_cache = {} # used to bind scoped calculation
1066
1066
1067 @LazyProperty
1067 @LazyProperty
1068 def permissions(self):
1068 def permissions(self):
1069 return self.get_perms(user=self, cache=None)
1069 return self.get_perms(user=self, cache=None)
1070
1070
1071 @LazyProperty
1071 @LazyProperty
1072 def permissions_safe(self):
1072 def permissions_safe(self):
1073 """
1073 """
1074 Filtered permissions excluding not allowed repositories
1074 Filtered permissions excluding not allowed repositories
1075 """
1075 """
1076 perms = self.get_perms(user=self, cache=None)
1076 perms = self.get_perms(user=self, cache=None)
1077
1077
1078 perms['repositories'] = {
1078 perms['repositories'] = {
1079 k: v for k, v in perms['repositories'].items()
1079 k: v for k, v in perms['repositories'].items()
1080 if v != 'repository.none'}
1080 if v != 'repository.none'}
1081 perms['repositories_groups'] = {
1081 perms['repositories_groups'] = {
1082 k: v for k, v in perms['repositories_groups'].items()
1082 k: v for k, v in perms['repositories_groups'].items()
1083 if v != 'group.none'}
1083 if v != 'group.none'}
1084 perms['user_groups'] = {
1084 perms['user_groups'] = {
1085 k: v for k, v in perms['user_groups'].items()
1085 k: v for k, v in perms['user_groups'].items()
1086 if v != 'usergroup.none'}
1086 if v != 'usergroup.none'}
1087 perms['repository_branches'] = {
1087 perms['repository_branches'] = {
1088 k: v for k, v in perms['repository_branches'].iteritems()
1088 k: v for k, v in perms['repository_branches'].iteritems()
1089 if v != 'branch.none'}
1089 if v != 'branch.none'}
1090 return perms
1090 return perms
1091
1091
1092 @LazyProperty
1092 @LazyProperty
1093 def permissions_full_details(self):
1093 def permissions_full_details(self):
1094 return self.get_perms(
1094 return self.get_perms(
1095 user=self, cache=None, calculate_super_admin=True)
1095 user=self, cache=None, calculate_super_admin=True)
1096
1096
1097 def permissions_with_scope(self, scope):
1097 def permissions_with_scope(self, scope):
1098 """
1098 """
1099 Call the get_perms function with scoped data. The scope in that function
1099 Call the get_perms function with scoped data. The scope in that function
1100 narrows the SQL calls to the given ID of objects resulting in fetching
1100 narrows the SQL calls to the given ID of objects resulting in fetching
1101 Just particular permission we want to obtain. If scope is an empty dict
1101 Just particular permission we want to obtain. If scope is an empty dict
1102 then it basically narrows the scope to GLOBAL permissions only.
1102 then it basically narrows the scope to GLOBAL permissions only.
1103
1103
1104 :param scope: dict
1104 :param scope: dict
1105 """
1105 """
1106 if 'repo_name' in scope:
1106 if 'repo_name' in scope:
1107 obj = Repository.get_by_repo_name(scope['repo_name'])
1107 obj = Repository.get_by_repo_name(scope['repo_name'])
1108 if obj:
1108 if obj:
1109 scope['repo_id'] = obj.repo_id
1109 scope['repo_id'] = obj.repo_id
1110 _scope = collections.OrderedDict()
1110 _scope = collections.OrderedDict()
1111 _scope['repo_id'] = -1
1111 _scope['repo_id'] = -1
1112 _scope['user_group_id'] = -1
1112 _scope['user_group_id'] = -1
1113 _scope['repo_group_id'] = -1
1113 _scope['repo_group_id'] = -1
1114
1114
1115 for k in sorted(scope.keys()):
1115 for k in sorted(scope.keys()):
1116 _scope[k] = scope[k]
1116 _scope[k] = scope[k]
1117
1117
1118 # store in cache to mimic how the @LazyProperty works,
1118 # store in cache to mimic how the @LazyProperty works,
1119 # the difference here is that we use the unique key calculated
1119 # the difference here is that we use the unique key calculated
1120 # from params and values
1120 # from params and values
1121 return self.get_perms(user=self, cache=None, scope=_scope)
1121 return self.get_perms(user=self, cache=None, scope=_scope)
1122
1122
1123 def get_instance(self):
1123 def get_instance(self):
1124 return User.get(self.user_id)
1124 return User.get(self.user_id)
1125
1125
1126 def propagate_data(self):
1126 def propagate_data(self):
1127 """
1127 """
1128 Fills in user data and propagates values to this instance. Maps fetched
1128 Fills in user data and propagates values to this instance. Maps fetched
1129 user attributes to this class instance attributes
1129 user attributes to this class instance attributes
1130 """
1130 """
1131 log.debug('AuthUser: starting data propagation for new potential user')
1131 log.debug('AuthUser: starting data propagation for new potential user')
1132 user_model = UserModel()
1132 user_model = UserModel()
1133 anon_user = self.anonymous_user = User.get_default_user(cache=True)
1133 anon_user = self.anonymous_user = User.get_default_user(cache=True)
1134 is_user_loaded = False
1134 is_user_loaded = False
1135
1135
1136 # lookup by userid
1136 # lookup by userid
1137 if self.user_id is not None and self.user_id != anon_user.user_id:
1137 if self.user_id is not None and self.user_id != anon_user.user_id:
1138 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
1138 log.debug('Trying Auth User lookup by USER ID: `%s`', self.user_id)
1139 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
1139 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
1140
1140
1141 # try go get user by api key
1141 # try go get user by api key
1142 elif self._api_key and self._api_key != anon_user.api_key:
1142 elif self._api_key and self._api_key != anon_user.api_key:
1143 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
1143 log.debug('Trying Auth User lookup by API KEY: `%s`', self._api_key)
1144 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
1144 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
1145
1145
1146 # lookup by username
1146 # lookup by username
1147 elif self.username:
1147 elif self.username:
1148 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
1148 log.debug('Trying Auth User lookup by USER NAME: `%s`', self.username)
1149 is_user_loaded = user_model.fill_data(self, username=self.username)
1149 is_user_loaded = user_model.fill_data(self, username=self.username)
1150 else:
1150 else:
1151 log.debug('No data in %s that could been used to log in', self)
1151 log.debug('No data in %s that could been used to log in', self)
1152
1152
1153 if not is_user_loaded:
1153 if not is_user_loaded:
1154 log.debug(
1154 log.debug(
1155 'Failed to load user. Fallback to default user %s', anon_user)
1155 'Failed to load user. Fallback to default user %s', anon_user)
1156 # if we cannot authenticate user try anonymous
1156 # if we cannot authenticate user try anonymous
1157 if anon_user.active:
1157 if anon_user.active:
1158 log.debug('default user is active, using it as a session user')
1158 log.debug('default user is active, using it as a session user')
1159 user_model.fill_data(self, user_id=anon_user.user_id)
1159 user_model.fill_data(self, user_id=anon_user.user_id)
1160 # then we set this user is logged in
1160 # then we set this user is logged in
1161 self.is_authenticated = True
1161 self.is_authenticated = True
1162 else:
1162 else:
1163 log.debug('default user is NOT active')
1163 log.debug('default user is NOT active')
1164 # in case of disabled anonymous user we reset some of the
1164 # in case of disabled anonymous user we reset some of the
1165 # parameters so such user is "corrupted", skipping the fill_data
1165 # parameters so such user is "corrupted", skipping the fill_data
1166 for attr in ['user_id', 'username', 'admin', 'active']:
1166 for attr in ['user_id', 'username', 'admin', 'active']:
1167 setattr(self, attr, None)
1167 setattr(self, attr, None)
1168 self.is_authenticated = False
1168 self.is_authenticated = False
1169
1169
1170 if not self.username:
1170 if not self.username:
1171 self.username = 'None'
1171 self.username = 'None'
1172
1172
1173 log.debug('AuthUser: propagated user is now %s', self)
1173 log.debug('AuthUser: propagated user is now %s', self)
1174
1174
1175 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
1175 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
1176 calculate_super_admin=False, cache=None):
1176 calculate_super_admin=False, cache=None):
1177 """
1177 """
1178 Fills user permission attribute with permissions taken from database
1178 Fills user permission attribute with permissions taken from database
1179 works for permissions given for repositories, and for permissions that
1179 works for permissions given for repositories, and for permissions that
1180 are granted to groups
1180 are granted to groups
1181
1181
1182 :param user: instance of User object from database
1182 :param user: instance of User object from database
1183 :param explicit: In case there are permissions both for user and a group
1183 :param explicit: In case there are permissions both for user and a group
1184 that user is part of, explicit flag will defiine if user will
1184 that user is part of, explicit flag will defiine if user will
1185 explicitly override permissions from group, if it's False it will
1185 explicitly override permissions from group, if it's False it will
1186 make decision based on the algo
1186 make decision based on the algo
1187 :param algo: algorithm to decide what permission should be choose if
1187 :param algo: algorithm to decide what permission should be choose if
1188 it's multiple defined, eg user in two different groups. It also
1188 it's multiple defined, eg user in two different groups. It also
1189 decides if explicit flag is turned off how to specify the permission
1189 decides if explicit flag is turned off how to specify the permission
1190 for case when user is in a group + have defined separate permission
1190 for case when user is in a group + have defined separate permission
1191 :param calculate_super_admin: calculate permissions for super-admin in the
1191 :param calculate_super_admin: calculate permissions for super-admin in the
1192 same way as for regular user without speedups
1192 same way as for regular user without speedups
1193 :param cache: Use caching for calculation, None = let the cache backend decide
1193 :param cache: Use caching for calculation, None = let the cache backend decide
1194 """
1194 """
1195 user_id = user.user_id
1195 user_id = user.user_id
1196 user_is_admin = user.is_admin
1196 user_is_admin = user.is_admin
1197
1197
1198 # inheritance of global permissions like create repo/fork repo etc
1198 # inheritance of global permissions like create repo/fork repo etc
1199 user_inherit_default_permissions = user.inherit_default_permissions
1199 user_inherit_default_permissions = user.inherit_default_permissions
1200
1200
1201 cache_seconds = safe_int(
1201 cache_seconds = safe_int(
1202 rhodecode.CONFIG.get('rc_cache.cache_perms.expiration_time'))
1202 rhodecode.CONFIG.get('rc_cache.cache_perms.expiration_time'))
1203
1203
1204 if cache is None:
1204 if cache is None:
1205 # let the backend cache decide
1205 # let the backend cache decide
1206 cache_on = cache_seconds > 0
1206 cache_on = cache_seconds > 0
1207 else:
1207 else:
1208 cache_on = cache
1208 cache_on = cache
1209
1209
1210 log.debug(
1210 log.debug(
1211 'Computing PERMISSION tree for user %s scope `%s` '
1211 'Computing PERMISSION tree for user %s scope `%s` '
1212 'with caching: %s[TTL: %ss]', user, scope, cache_on, cache_seconds or 0)
1212 'with caching: %s[TTL: %ss]', user, scope, cache_on, cache_seconds or 0)
1213
1213
1214 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
1214 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
1215 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1215 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
1216
1216
1217 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
1217 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
1218 condition=cache_on)
1218 condition=cache_on)
1219 def compute_perm_tree(cache_name,
1219 def compute_perm_tree(cache_name,
1220 user_id, scope, user_is_admin,user_inherit_default_permissions,
1220 user_id, scope, user_is_admin,user_inherit_default_permissions,
1221 explicit, algo, calculate_super_admin):
1221 explicit, algo, calculate_super_admin):
1222 return _cached_perms_data(
1222 return _cached_perms_data(
1223 user_id, scope, user_is_admin, user_inherit_default_permissions,
1223 user_id, scope, user_is_admin, user_inherit_default_permissions,
1224 explicit, algo, calculate_super_admin)
1224 explicit, algo, calculate_super_admin)
1225
1225
1226 start = time.time()
1226 start = time.time()
1227 result = compute_perm_tree(
1227 result = compute_perm_tree(
1228 'permissions', user_id, scope, user_is_admin,
1228 'permissions', user_id, scope, user_is_admin,
1229 user_inherit_default_permissions, explicit, algo,
1229 user_inherit_default_permissions, explicit, algo,
1230 calculate_super_admin)
1230 calculate_super_admin)
1231
1231
1232 result_repr = []
1232 result_repr = []
1233 for k in result:
1233 for k in result:
1234 result_repr.append((k, len(result[k])))
1234 result_repr.append((k, len(result[k])))
1235 total = time.time() - start
1235 total = time.time() - start
1236 log.debug('PERMISSION tree for user %s computed in %.3fs: %s',
1236 log.debug('PERMISSION tree for user %s computed in %.4fs: %s',
1237 user, total, result_repr)
1237 user, total, result_repr)
1238
1238
1239 return result
1239 return result
1240
1240
1241 @property
1241 @property
1242 def is_default(self):
1242 def is_default(self):
1243 return self.username == User.DEFAULT_USER
1243 return self.username == User.DEFAULT_USER
1244
1244
1245 @property
1245 @property
1246 def is_admin(self):
1246 def is_admin(self):
1247 return self.admin
1247 return self.admin
1248
1248
1249 @property
1249 @property
1250 def is_user_object(self):
1250 def is_user_object(self):
1251 return self.user_id is not None
1251 return self.user_id is not None
1252
1252
1253 @property
1253 @property
1254 def repositories_admin(self):
1254 def repositories_admin(self):
1255 """
1255 """
1256 Returns list of repositories you're an admin of
1256 Returns list of repositories you're an admin of
1257 """
1257 """
1258 return [
1258 return [
1259 x[0] for x in self.permissions['repositories'].items()
1259 x[0] for x in self.permissions['repositories'].items()
1260 if x[1] == 'repository.admin']
1260 if x[1] == 'repository.admin']
1261
1261
1262 @property
1262 @property
1263 def repository_groups_admin(self):
1263 def repository_groups_admin(self):
1264 """
1264 """
1265 Returns list of repository groups you're an admin of
1265 Returns list of repository groups you're an admin of
1266 """
1266 """
1267 return [
1267 return [
1268 x[0] for x in self.permissions['repositories_groups'].items()
1268 x[0] for x in self.permissions['repositories_groups'].items()
1269 if x[1] == 'group.admin']
1269 if x[1] == 'group.admin']
1270
1270
1271 @property
1271 @property
1272 def user_groups_admin(self):
1272 def user_groups_admin(self):
1273 """
1273 """
1274 Returns list of user groups you're an admin of
1274 Returns list of user groups you're an admin of
1275 """
1275 """
1276 return [
1276 return [
1277 x[0] for x in self.permissions['user_groups'].items()
1277 x[0] for x in self.permissions['user_groups'].items()
1278 if x[1] == 'usergroup.admin']
1278 if x[1] == 'usergroup.admin']
1279
1279
1280 def repo_acl_ids(self, perms=None, name_filter=None, cache=False):
1280 def repo_acl_ids(self, perms=None, name_filter=None, cache=False):
1281 """
1281 """
1282 Returns list of repository ids that user have access to based on given
1282 Returns list of repository ids that user have access to based on given
1283 perms. The cache flag should be only used in cases that are used for
1283 perms. The cache flag should be only used in cases that are used for
1284 display purposes, NOT IN ANY CASE for permission checks.
1284 display purposes, NOT IN ANY CASE for permission checks.
1285 """
1285 """
1286 from rhodecode.model.scm import RepoList
1286 from rhodecode.model.scm import RepoList
1287 if not perms:
1287 if not perms:
1288 perms = [
1288 perms = [
1289 'repository.read', 'repository.write', 'repository.admin']
1289 'repository.read', 'repository.write', 'repository.admin']
1290
1290
1291 def _cached_repo_acl(user_id, perm_def, _name_filter):
1291 def _cached_repo_acl(user_id, perm_def, _name_filter):
1292 qry = Repository.query()
1292 qry = Repository.query()
1293 if _name_filter:
1293 if _name_filter:
1294 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1294 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1295 qry = qry.filter(
1295 qry = qry.filter(
1296 Repository.repo_name.ilike(ilike_expression))
1296 Repository.repo_name.ilike(ilike_expression))
1297
1297
1298 return [x.repo_id for x in
1298 return [x.repo_id for x in
1299 RepoList(qry, perm_set=perm_def)]
1299 RepoList(qry, perm_set=perm_def)]
1300
1300
1301 return _cached_repo_acl(self.user_id, perms, name_filter)
1301 return _cached_repo_acl(self.user_id, perms, name_filter)
1302
1302
1303 def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1303 def repo_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1304 """
1304 """
1305 Returns list of repository group ids that user have access to based on given
1305 Returns list of repository group ids that user have access to based on given
1306 perms. The cache flag should be only used in cases that are used for
1306 perms. The cache flag should be only used in cases that are used for
1307 display purposes, NOT IN ANY CASE for permission checks.
1307 display purposes, NOT IN ANY CASE for permission checks.
1308 """
1308 """
1309 from rhodecode.model.scm import RepoGroupList
1309 from rhodecode.model.scm import RepoGroupList
1310 if not perms:
1310 if not perms:
1311 perms = [
1311 perms = [
1312 'group.read', 'group.write', 'group.admin']
1312 'group.read', 'group.write', 'group.admin']
1313
1313
1314 def _cached_repo_group_acl(user_id, perm_def, _name_filter):
1314 def _cached_repo_group_acl(user_id, perm_def, _name_filter):
1315 qry = RepoGroup.query()
1315 qry = RepoGroup.query()
1316 if _name_filter:
1316 if _name_filter:
1317 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1317 ilike_expression = u'%{}%'.format(safe_unicode(_name_filter))
1318 qry = qry.filter(
1318 qry = qry.filter(
1319 RepoGroup.group_name.ilike(ilike_expression))
1319 RepoGroup.group_name.ilike(ilike_expression))
1320
1320
1321 return [x.group_id for x in
1321 return [x.group_id for x in
1322 RepoGroupList(qry, perm_set=perm_def)]
1322 RepoGroupList(qry, perm_set=perm_def)]
1323
1323
1324 return _cached_repo_group_acl(self.user_id, perms, name_filter)
1324 return _cached_repo_group_acl(self.user_id, perms, name_filter)
1325
1325
1326 def user_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1326 def user_group_acl_ids(self, perms=None, name_filter=None, cache=False):
1327 """
1327 """
1328 Returns list of user group ids that user have access to based on given
1328 Returns list of user group ids that user have access to based on given
1329 perms. The cache flag should be only used in cases that are used for
1329 perms. The cache flag should be only used in cases that are used for
1330 display purposes, NOT IN ANY CASE for permission checks.
1330 display purposes, NOT IN ANY CASE for permission checks.
1331 """
1331 """
1332 from rhodecode.model.scm import UserGroupList
1332 from rhodecode.model.scm import UserGroupList
1333 if not perms:
1333 if not perms:
1334 perms = [
1334 perms = [
1335 'usergroup.read', 'usergroup.write', 'usergroup.admin']
1335 'usergroup.read', 'usergroup.write', 'usergroup.admin']
1336
1336
1337 def _cached_user_group_acl(user_id, perm_def, name_filter):
1337 def _cached_user_group_acl(user_id, perm_def, name_filter):
1338 qry = UserGroup.query()
1338 qry = UserGroup.query()
1339 if name_filter:
1339 if name_filter:
1340 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1340 ilike_expression = u'%{}%'.format(safe_unicode(name_filter))
1341 qry = qry.filter(
1341 qry = qry.filter(
1342 UserGroup.users_group_name.ilike(ilike_expression))
1342 UserGroup.users_group_name.ilike(ilike_expression))
1343
1343
1344 return [x.users_group_id for x in
1344 return [x.users_group_id for x in
1345 UserGroupList(qry, perm_set=perm_def)]
1345 UserGroupList(qry, perm_set=perm_def)]
1346
1346
1347 return _cached_user_group_acl(self.user_id, perms, name_filter)
1347 return _cached_user_group_acl(self.user_id, perms, name_filter)
1348
1348
1349 @property
1349 @property
1350 def ip_allowed(self):
1350 def ip_allowed(self):
1351 """
1351 """
1352 Checks if ip_addr used in constructor is allowed from defined list of
1352 Checks if ip_addr used in constructor is allowed from defined list of
1353 allowed ip_addresses for user
1353 allowed ip_addresses for user
1354
1354
1355 :returns: boolean, True if ip is in allowed ip range
1355 :returns: boolean, True if ip is in allowed ip range
1356 """
1356 """
1357 # check IP
1357 # check IP
1358 inherit = self.inherit_default_permissions
1358 inherit = self.inherit_default_permissions
1359 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1359 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
1360 inherit_from_default=inherit)
1360 inherit_from_default=inherit)
1361 @property
1361 @property
1362 def personal_repo_group(self):
1362 def personal_repo_group(self):
1363 return RepoGroup.get_user_personal_repo_group(self.user_id)
1363 return RepoGroup.get_user_personal_repo_group(self.user_id)
1364
1364
1365 @LazyProperty
1365 @LazyProperty
1366 def feed_token(self):
1366 def feed_token(self):
1367 return self.get_instance().feed_token
1367 return self.get_instance().feed_token
1368
1368
1369 @classmethod
1369 @classmethod
1370 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1370 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1371 allowed_ips = AuthUser.get_allowed_ips(
1371 allowed_ips = AuthUser.get_allowed_ips(
1372 user_id, cache=True, inherit_from_default=inherit_from_default)
1372 user_id, cache=True, inherit_from_default=inherit_from_default)
1373 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1373 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1374 log.debug('IP:%s for user %s is in range of %s',
1374 log.debug('IP:%s for user %s is in range of %s',
1375 ip_addr, user_id, allowed_ips)
1375 ip_addr, user_id, allowed_ips)
1376 return True
1376 return True
1377 else:
1377 else:
1378 log.info('Access for IP:%s forbidden for user %s, '
1378 log.info('Access for IP:%s forbidden for user %s, '
1379 'not in %s', ip_addr, user_id, allowed_ips)
1379 'not in %s', ip_addr, user_id, allowed_ips)
1380 return False
1380 return False
1381
1381
1382 def get_branch_permissions(self, repo_name, perms=None):
1382 def get_branch_permissions(self, repo_name, perms=None):
1383 perms = perms or self.permissions_with_scope({'repo_name': repo_name})
1383 perms = perms or self.permissions_with_scope({'repo_name': repo_name})
1384 branch_perms = perms.get('repository_branches', {})
1384 branch_perms = perms.get('repository_branches', {})
1385 if not branch_perms:
1385 if not branch_perms:
1386 return {}
1386 return {}
1387 repo_branch_perms = branch_perms.get(repo_name)
1387 repo_branch_perms = branch_perms.get(repo_name)
1388 return repo_branch_perms or {}
1388 return repo_branch_perms or {}
1389
1389
1390 def get_rule_and_branch_permission(self, repo_name, branch_name):
1390 def get_rule_and_branch_permission(self, repo_name, branch_name):
1391 """
1391 """
1392 Check if this AuthUser has defined any permissions for branches. If any of
1392 Check if this AuthUser has defined any permissions for branches. If any of
1393 the rules match in order, we return the matching permissions
1393 the rules match in order, we return the matching permissions
1394 """
1394 """
1395
1395
1396 rule = default_perm = ''
1396 rule = default_perm = ''
1397
1397
1398 repo_branch_perms = self.get_branch_permissions(repo_name=repo_name)
1398 repo_branch_perms = self.get_branch_permissions(repo_name=repo_name)
1399 if not repo_branch_perms:
1399 if not repo_branch_perms:
1400 return rule, default_perm
1400 return rule, default_perm
1401
1401
1402 # now calculate the permissions
1402 # now calculate the permissions
1403 for pattern, branch_perm in repo_branch_perms.items():
1403 for pattern, branch_perm in repo_branch_perms.items():
1404 if fnmatch.fnmatch(branch_name, pattern):
1404 if fnmatch.fnmatch(branch_name, pattern):
1405 rule = '`{}`=>{}'.format(pattern, branch_perm)
1405 rule = '`{}`=>{}'.format(pattern, branch_perm)
1406 return rule, branch_perm
1406 return rule, branch_perm
1407
1407
1408 return rule, default_perm
1408 return rule, default_perm
1409
1409
1410 def __repr__(self):
1410 def __repr__(self):
1411 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1411 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1412 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1412 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1413
1413
1414 def set_authenticated(self, authenticated=True):
1414 def set_authenticated(self, authenticated=True):
1415 if self.user_id != self.anonymous_user.user_id:
1415 if self.user_id != self.anonymous_user.user_id:
1416 self.is_authenticated = authenticated
1416 self.is_authenticated = authenticated
1417
1417
1418 def get_cookie_store(self):
1418 def get_cookie_store(self):
1419 return {
1419 return {
1420 'username': self.username,
1420 'username': self.username,
1421 'password': md5(self.password or ''),
1421 'password': md5(self.password or ''),
1422 'user_id': self.user_id,
1422 'user_id': self.user_id,
1423 'is_authenticated': self.is_authenticated
1423 'is_authenticated': self.is_authenticated
1424 }
1424 }
1425
1425
1426 @classmethod
1426 @classmethod
1427 def from_cookie_store(cls, cookie_store):
1427 def from_cookie_store(cls, cookie_store):
1428 """
1428 """
1429 Creates AuthUser from a cookie store
1429 Creates AuthUser from a cookie store
1430
1430
1431 :param cls:
1431 :param cls:
1432 :param cookie_store:
1432 :param cookie_store:
1433 """
1433 """
1434 user_id = cookie_store.get('user_id')
1434 user_id = cookie_store.get('user_id')
1435 username = cookie_store.get('username')
1435 username = cookie_store.get('username')
1436 api_key = cookie_store.get('api_key')
1436 api_key = cookie_store.get('api_key')
1437 return AuthUser(user_id, api_key, username)
1437 return AuthUser(user_id, api_key, username)
1438
1438
1439 @classmethod
1439 @classmethod
1440 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1440 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1441 _set = set()
1441 _set = set()
1442
1442
1443 if inherit_from_default:
1443 if inherit_from_default:
1444 def_user_id = User.get_default_user(cache=True).user_id
1444 def_user_id = User.get_default_user(cache=True).user_id
1445 default_ips = UserIpMap.query().filter(UserIpMap.user_id == def_user_id)
1445 default_ips = UserIpMap.query().filter(UserIpMap.user_id == def_user_id)
1446 if cache:
1446 if cache:
1447 default_ips = default_ips.options(
1447 default_ips = default_ips.options(
1448 FromCache("sql_cache_short", "get_user_ips_default"))
1448 FromCache("sql_cache_short", "get_user_ips_default"))
1449
1449
1450 # populate from default user
1450 # populate from default user
1451 for ip in default_ips:
1451 for ip in default_ips:
1452 try:
1452 try:
1453 _set.add(ip.ip_addr)
1453 _set.add(ip.ip_addr)
1454 except ObjectDeletedError:
1454 except ObjectDeletedError:
1455 # since we use heavy caching sometimes it happens that
1455 # since we use heavy caching sometimes it happens that
1456 # we get deleted objects here, we just skip them
1456 # we get deleted objects here, we just skip them
1457 pass
1457 pass
1458
1458
1459 # NOTE:(marcink) we don't want to load any rules for empty
1459 # NOTE:(marcink) we don't want to load any rules for empty
1460 # user_id which is the case of access of non logged users when anonymous
1460 # user_id which is the case of access of non logged users when anonymous
1461 # access is disabled
1461 # access is disabled
1462 user_ips = []
1462 user_ips = []
1463 if user_id:
1463 if user_id:
1464 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1464 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1465 if cache:
1465 if cache:
1466 user_ips = user_ips.options(
1466 user_ips = user_ips.options(
1467 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1467 FromCache("sql_cache_short", "get_user_ips_%s" % user_id))
1468
1468
1469 for ip in user_ips:
1469 for ip in user_ips:
1470 try:
1470 try:
1471 _set.add(ip.ip_addr)
1471 _set.add(ip.ip_addr)
1472 except ObjectDeletedError:
1472 except ObjectDeletedError:
1473 # since we use heavy caching sometimes it happens that we get
1473 # since we use heavy caching sometimes it happens that we get
1474 # deleted objects here, we just skip them
1474 # deleted objects here, we just skip them
1475 pass
1475 pass
1476 return _set or {ip for ip in ['0.0.0.0/0', '::/0']}
1476 return _set or {ip for ip in ['0.0.0.0/0', '::/0']}
1477
1477
1478
1478
1479 def set_available_permissions(settings):
1479 def set_available_permissions(settings):
1480 """
1480 """
1481 This function will propagate pyramid settings with all available defined
1481 This function will propagate pyramid settings with all available defined
1482 permission given in db. We don't want to check each time from db for new
1482 permission given in db. We don't want to check each time from db for new
1483 permissions since adding a new permission also requires application restart
1483 permissions since adding a new permission also requires application restart
1484 ie. to decorate new views with the newly created permission
1484 ie. to decorate new views with the newly created permission
1485
1485
1486 :param settings: current pyramid registry.settings
1486 :param settings: current pyramid registry.settings
1487
1487
1488 """
1488 """
1489 log.debug('auth: getting information about all available permissions')
1489 log.debug('auth: getting information about all available permissions')
1490 try:
1490 try:
1491 sa = meta.Session
1491 sa = meta.Session
1492 all_perms = sa.query(Permission).all()
1492 all_perms = sa.query(Permission).all()
1493 settings.setdefault('available_permissions',
1493 settings.setdefault('available_permissions',
1494 [x.permission_name for x in all_perms])
1494 [x.permission_name for x in all_perms])
1495 log.debug('auth: set available permissions')
1495 log.debug('auth: set available permissions')
1496 except Exception:
1496 except Exception:
1497 log.exception('Failed to fetch permissions from the database.')
1497 log.exception('Failed to fetch permissions from the database.')
1498 raise
1498 raise
1499
1499
1500
1500
1501 def get_csrf_token(session, force_new=False, save_if_missing=True):
1501 def get_csrf_token(session, force_new=False, save_if_missing=True):
1502 """
1502 """
1503 Return the current authentication token, creating one if one doesn't
1503 Return the current authentication token, creating one if one doesn't
1504 already exist and the save_if_missing flag is present.
1504 already exist and the save_if_missing flag is present.
1505
1505
1506 :param session: pass in the pyramid session, else we use the global ones
1506 :param session: pass in the pyramid session, else we use the global ones
1507 :param force_new: force to re-generate the token and store it in session
1507 :param force_new: force to re-generate the token and store it in session
1508 :param save_if_missing: save the newly generated token if it's missing in
1508 :param save_if_missing: save the newly generated token if it's missing in
1509 session
1509 session
1510 """
1510 """
1511 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1511 # NOTE(marcink): probably should be replaced with below one from pyramid 1.9
1512 # from pyramid.csrf import get_csrf_token
1512 # from pyramid.csrf import get_csrf_token
1513
1513
1514 if (csrf_token_key not in session and save_if_missing) or force_new:
1514 if (csrf_token_key not in session and save_if_missing) or force_new:
1515 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1515 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1516 session[csrf_token_key] = token
1516 session[csrf_token_key] = token
1517 if hasattr(session, 'save'):
1517 if hasattr(session, 'save'):
1518 session.save()
1518 session.save()
1519 return session.get(csrf_token_key)
1519 return session.get(csrf_token_key)
1520
1520
1521
1521
1522 def get_request(perm_class_instance):
1522 def get_request(perm_class_instance):
1523 from pyramid.threadlocal import get_current_request
1523 from pyramid.threadlocal import get_current_request
1524 pyramid_request = get_current_request()
1524 pyramid_request = get_current_request()
1525 return pyramid_request
1525 return pyramid_request
1526
1526
1527
1527
1528 # CHECK DECORATORS
1528 # CHECK DECORATORS
1529 class CSRFRequired(object):
1529 class CSRFRequired(object):
1530 """
1530 """
1531 Decorator for authenticating a form
1531 Decorator for authenticating a form
1532
1532
1533 This decorator uses an authorization token stored in the client's
1533 This decorator uses an authorization token stored in the client's
1534 session for prevention of certain Cross-site request forgery (CSRF)
1534 session for prevention of certain Cross-site request forgery (CSRF)
1535 attacks (See
1535 attacks (See
1536 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1536 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1537 information).
1537 information).
1538
1538
1539 For use with the ``webhelpers.secure_form`` helper functions.
1539 For use with the ``webhelpers.secure_form`` helper functions.
1540
1540
1541 """
1541 """
1542 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1542 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1543 except_methods=None):
1543 except_methods=None):
1544 self.token = token
1544 self.token = token
1545 self.header = header
1545 self.header = header
1546 self.except_methods = except_methods or []
1546 self.except_methods = except_methods or []
1547
1547
1548 def __call__(self, func):
1548 def __call__(self, func):
1549 return get_cython_compat_decorator(self.__wrapper, func)
1549 return get_cython_compat_decorator(self.__wrapper, func)
1550
1550
1551 def _get_csrf(self, _request):
1551 def _get_csrf(self, _request):
1552 return _request.POST.get(self.token, _request.headers.get(self.header))
1552 return _request.POST.get(self.token, _request.headers.get(self.header))
1553
1553
1554 def check_csrf(self, _request, cur_token):
1554 def check_csrf(self, _request, cur_token):
1555 supplied_token = self._get_csrf(_request)
1555 supplied_token = self._get_csrf(_request)
1556 return supplied_token and supplied_token == cur_token
1556 return supplied_token and supplied_token == cur_token
1557
1557
1558 def _get_request(self):
1558 def _get_request(self):
1559 return get_request(self)
1559 return get_request(self)
1560
1560
1561 def __wrapper(self, func, *fargs, **fkwargs):
1561 def __wrapper(self, func, *fargs, **fkwargs):
1562 request = self._get_request()
1562 request = self._get_request()
1563
1563
1564 if request.method in self.except_methods:
1564 if request.method in self.except_methods:
1565 return func(*fargs, **fkwargs)
1565 return func(*fargs, **fkwargs)
1566
1566
1567 cur_token = get_csrf_token(request.session, save_if_missing=False)
1567 cur_token = get_csrf_token(request.session, save_if_missing=False)
1568 if self.check_csrf(request, cur_token):
1568 if self.check_csrf(request, cur_token):
1569 if request.POST.get(self.token):
1569 if request.POST.get(self.token):
1570 del request.POST[self.token]
1570 del request.POST[self.token]
1571 return func(*fargs, **fkwargs)
1571 return func(*fargs, **fkwargs)
1572 else:
1572 else:
1573 reason = 'token-missing'
1573 reason = 'token-missing'
1574 supplied_token = self._get_csrf(request)
1574 supplied_token = self._get_csrf(request)
1575 if supplied_token and cur_token != supplied_token:
1575 if supplied_token and cur_token != supplied_token:
1576 reason = 'token-mismatch [%s:%s]' % (
1576 reason = 'token-mismatch [%s:%s]' % (
1577 cur_token or ''[:6], supplied_token or ''[:6])
1577 cur_token or ''[:6], supplied_token or ''[:6])
1578
1578
1579 csrf_message = \
1579 csrf_message = \
1580 ("Cross-site request forgery detected, request denied. See "
1580 ("Cross-site request forgery detected, request denied. See "
1581 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1581 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1582 "more information.")
1582 "more information.")
1583 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1583 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1584 'REMOTE_ADDR:%s, HEADERS:%s' % (
1584 'REMOTE_ADDR:%s, HEADERS:%s' % (
1585 request, reason, request.remote_addr, request.headers))
1585 request, reason, request.remote_addr, request.headers))
1586
1586
1587 raise HTTPForbidden(explanation=csrf_message)
1587 raise HTTPForbidden(explanation=csrf_message)
1588
1588
1589
1589
1590 class LoginRequired(object):
1590 class LoginRequired(object):
1591 """
1591 """
1592 Must be logged in to execute this function else
1592 Must be logged in to execute this function else
1593 redirect to login page
1593 redirect to login page
1594
1594
1595 :param api_access: if enabled this checks only for valid auth token
1595 :param api_access: if enabled this checks only for valid auth token
1596 and grants access based on valid token
1596 and grants access based on valid token
1597 """
1597 """
1598 def __init__(self, auth_token_access=None):
1598 def __init__(self, auth_token_access=None):
1599 self.auth_token_access = auth_token_access
1599 self.auth_token_access = auth_token_access
1600
1600
1601 def __call__(self, func):
1601 def __call__(self, func):
1602 return get_cython_compat_decorator(self.__wrapper, func)
1602 return get_cython_compat_decorator(self.__wrapper, func)
1603
1603
1604 def _get_request(self):
1604 def _get_request(self):
1605 return get_request(self)
1605 return get_request(self)
1606
1606
1607 def __wrapper(self, func, *fargs, **fkwargs):
1607 def __wrapper(self, func, *fargs, **fkwargs):
1608 from rhodecode.lib import helpers as h
1608 from rhodecode.lib import helpers as h
1609 cls = fargs[0]
1609 cls = fargs[0]
1610 user = cls._rhodecode_user
1610 user = cls._rhodecode_user
1611 request = self._get_request()
1611 request = self._get_request()
1612 _ = request.translate
1612 _ = request.translate
1613
1613
1614 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1614 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1615 log.debug('Starting login restriction checks for user: %s', user)
1615 log.debug('Starting login restriction checks for user: %s', user)
1616 # check if our IP is allowed
1616 # check if our IP is allowed
1617 ip_access_valid = True
1617 ip_access_valid = True
1618 if not user.ip_allowed:
1618 if not user.ip_allowed:
1619 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1619 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1620 category='warning')
1620 category='warning')
1621 ip_access_valid = False
1621 ip_access_valid = False
1622
1622
1623 # check if we used an APIKEY and it's a valid one
1623 # check if we used an APIKEY and it's a valid one
1624 # defined white-list of controllers which API access will be enabled
1624 # defined white-list of controllers which API access will be enabled
1625 _auth_token = request.GET.get(
1625 _auth_token = request.GET.get(
1626 'auth_token', '') or request.GET.get('api_key', '')
1626 'auth_token', '') or request.GET.get('api_key', '')
1627 auth_token_access_valid = allowed_auth_token_access(
1627 auth_token_access_valid = allowed_auth_token_access(
1628 loc, auth_token=_auth_token)
1628 loc, auth_token=_auth_token)
1629
1629
1630 # explicit controller is enabled or API is in our whitelist
1630 # explicit controller is enabled or API is in our whitelist
1631 if self.auth_token_access or auth_token_access_valid:
1631 if self.auth_token_access or auth_token_access_valid:
1632 log.debug('Checking AUTH TOKEN access for %s', cls)
1632 log.debug('Checking AUTH TOKEN access for %s', cls)
1633 db_user = user.get_instance()
1633 db_user = user.get_instance()
1634
1634
1635 if db_user:
1635 if db_user:
1636 if self.auth_token_access:
1636 if self.auth_token_access:
1637 roles = self.auth_token_access
1637 roles = self.auth_token_access
1638 else:
1638 else:
1639 roles = [UserApiKeys.ROLE_HTTP]
1639 roles = [UserApiKeys.ROLE_HTTP]
1640 token_match = db_user.authenticate_by_token(
1640 token_match = db_user.authenticate_by_token(
1641 _auth_token, roles=roles)
1641 _auth_token, roles=roles)
1642 else:
1642 else:
1643 log.debug('Unable to fetch db instance for auth user: %s', user)
1643 log.debug('Unable to fetch db instance for auth user: %s', user)
1644 token_match = False
1644 token_match = False
1645
1645
1646 if _auth_token and token_match:
1646 if _auth_token and token_match:
1647 auth_token_access_valid = True
1647 auth_token_access_valid = True
1648 log.debug('AUTH TOKEN ****%s is VALID', _auth_token[-4:])
1648 log.debug('AUTH TOKEN ****%s is VALID', _auth_token[-4:])
1649 else:
1649 else:
1650 auth_token_access_valid = False
1650 auth_token_access_valid = False
1651 if not _auth_token:
1651 if not _auth_token:
1652 log.debug("AUTH TOKEN *NOT* present in request")
1652 log.debug("AUTH TOKEN *NOT* present in request")
1653 else:
1653 else:
1654 log.warning("AUTH TOKEN ****%s *NOT* valid", _auth_token[-4:])
1654 log.warning("AUTH TOKEN ****%s *NOT* valid", _auth_token[-4:])
1655
1655
1656 log.debug('Checking if %s is authenticated @ %s', user.username, loc)
1656 log.debug('Checking if %s is authenticated @ %s', user.username, loc)
1657 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1657 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1658 else 'AUTH_TOKEN_AUTH'
1658 else 'AUTH_TOKEN_AUTH'
1659
1659
1660 if ip_access_valid and (
1660 if ip_access_valid and (
1661 user.is_authenticated or auth_token_access_valid):
1661 user.is_authenticated or auth_token_access_valid):
1662 log.info('user %s authenticating with:%s IS authenticated on func %s',
1662 log.info('user %s authenticating with:%s IS authenticated on func %s',
1663 user, reason, loc)
1663 user, reason, loc)
1664
1664
1665 return func(*fargs, **fkwargs)
1665 return func(*fargs, **fkwargs)
1666 else:
1666 else:
1667 log.warning(
1667 log.warning(
1668 'user %s authenticating with:%s NOT authenticated on '
1668 'user %s authenticating with:%s NOT authenticated on '
1669 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s',
1669 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s',
1670 user, reason, loc, ip_access_valid, auth_token_access_valid)
1670 user, reason, loc, ip_access_valid, auth_token_access_valid)
1671 # we preserve the get PARAM
1671 # we preserve the get PARAM
1672 came_from = get_came_from(request)
1672 came_from = get_came_from(request)
1673
1673
1674 log.debug('redirecting to login page with %s', came_from)
1674 log.debug('redirecting to login page with %s', came_from)
1675 raise HTTPFound(
1675 raise HTTPFound(
1676 h.route_path('login', _query={'came_from': came_from}))
1676 h.route_path('login', _query={'came_from': came_from}))
1677
1677
1678
1678
1679 class NotAnonymous(object):
1679 class NotAnonymous(object):
1680 """
1680 """
1681 Must be logged in to execute this function else
1681 Must be logged in to execute this function else
1682 redirect to login page
1682 redirect to login page
1683 """
1683 """
1684
1684
1685 def __call__(self, func):
1685 def __call__(self, func):
1686 return get_cython_compat_decorator(self.__wrapper, func)
1686 return get_cython_compat_decorator(self.__wrapper, func)
1687
1687
1688 def _get_request(self):
1688 def _get_request(self):
1689 return get_request(self)
1689 return get_request(self)
1690
1690
1691 def __wrapper(self, func, *fargs, **fkwargs):
1691 def __wrapper(self, func, *fargs, **fkwargs):
1692 import rhodecode.lib.helpers as h
1692 import rhodecode.lib.helpers as h
1693 cls = fargs[0]
1693 cls = fargs[0]
1694 self.user = cls._rhodecode_user
1694 self.user = cls._rhodecode_user
1695 request = self._get_request()
1695 request = self._get_request()
1696 _ = request.translate
1696 _ = request.translate
1697 log.debug('Checking if user is not anonymous @%s', cls)
1697 log.debug('Checking if user is not anonymous @%s', cls)
1698
1698
1699 anonymous = self.user.username == User.DEFAULT_USER
1699 anonymous = self.user.username == User.DEFAULT_USER
1700
1700
1701 if anonymous:
1701 if anonymous:
1702 came_from = get_came_from(request)
1702 came_from = get_came_from(request)
1703 h.flash(_('You need to be a registered user to '
1703 h.flash(_('You need to be a registered user to '
1704 'perform this action'),
1704 'perform this action'),
1705 category='warning')
1705 category='warning')
1706 raise HTTPFound(
1706 raise HTTPFound(
1707 h.route_path('login', _query={'came_from': came_from}))
1707 h.route_path('login', _query={'came_from': came_from}))
1708 else:
1708 else:
1709 return func(*fargs, **fkwargs)
1709 return func(*fargs, **fkwargs)
1710
1710
1711
1711
1712 class PermsDecorator(object):
1712 class PermsDecorator(object):
1713 """
1713 """
1714 Base class for controller decorators, we extract the current user from
1714 Base class for controller decorators, we extract the current user from
1715 the class itself, which has it stored in base controllers
1715 the class itself, which has it stored in base controllers
1716 """
1716 """
1717
1717
1718 def __init__(self, *required_perms):
1718 def __init__(self, *required_perms):
1719 self.required_perms = set(required_perms)
1719 self.required_perms = set(required_perms)
1720
1720
1721 def __call__(self, func):
1721 def __call__(self, func):
1722 return get_cython_compat_decorator(self.__wrapper, func)
1722 return get_cython_compat_decorator(self.__wrapper, func)
1723
1723
1724 def _get_request(self):
1724 def _get_request(self):
1725 return get_request(self)
1725 return get_request(self)
1726
1726
1727 def __wrapper(self, func, *fargs, **fkwargs):
1727 def __wrapper(self, func, *fargs, **fkwargs):
1728 import rhodecode.lib.helpers as h
1728 import rhodecode.lib.helpers as h
1729 cls = fargs[0]
1729 cls = fargs[0]
1730 _user = cls._rhodecode_user
1730 _user = cls._rhodecode_user
1731 request = self._get_request()
1731 request = self._get_request()
1732 _ = request.translate
1732 _ = request.translate
1733
1733
1734 log.debug('checking %s permissions %s for %s %s',
1734 log.debug('checking %s permissions %s for %s %s',
1735 self.__class__.__name__, self.required_perms, cls, _user)
1735 self.__class__.__name__, self.required_perms, cls, _user)
1736
1736
1737 if self.check_permissions(_user):
1737 if self.check_permissions(_user):
1738 log.debug('Permission granted for %s %s', cls, _user)
1738 log.debug('Permission granted for %s %s', cls, _user)
1739 return func(*fargs, **fkwargs)
1739 return func(*fargs, **fkwargs)
1740
1740
1741 else:
1741 else:
1742 log.debug('Permission denied for %s %s', cls, _user)
1742 log.debug('Permission denied for %s %s', cls, _user)
1743 anonymous = _user.username == User.DEFAULT_USER
1743 anonymous = _user.username == User.DEFAULT_USER
1744
1744
1745 if anonymous:
1745 if anonymous:
1746 came_from = get_came_from(self._get_request())
1746 came_from = get_came_from(self._get_request())
1747 h.flash(_('You need to be signed in to view this page'),
1747 h.flash(_('You need to be signed in to view this page'),
1748 category='warning')
1748 category='warning')
1749 raise HTTPFound(
1749 raise HTTPFound(
1750 h.route_path('login', _query={'came_from': came_from}))
1750 h.route_path('login', _query={'came_from': came_from}))
1751
1751
1752 else:
1752 else:
1753 # redirect with 404 to prevent resource discovery
1753 # redirect with 404 to prevent resource discovery
1754 raise HTTPNotFound()
1754 raise HTTPNotFound()
1755
1755
1756 def check_permissions(self, user):
1756 def check_permissions(self, user):
1757 """Dummy function for overriding"""
1757 """Dummy function for overriding"""
1758 raise NotImplementedError(
1758 raise NotImplementedError(
1759 'You have to write this function in child class')
1759 'You have to write this function in child class')
1760
1760
1761
1761
1762 class HasPermissionAllDecorator(PermsDecorator):
1762 class HasPermissionAllDecorator(PermsDecorator):
1763 """
1763 """
1764 Checks for access permission for all given predicates. All of them
1764 Checks for access permission for all given predicates. All of them
1765 have to be meet in order to fulfill the request
1765 have to be meet in order to fulfill the request
1766 """
1766 """
1767
1767
1768 def check_permissions(self, user):
1768 def check_permissions(self, user):
1769 perms = user.permissions_with_scope({})
1769 perms = user.permissions_with_scope({})
1770 if self.required_perms.issubset(perms['global']):
1770 if self.required_perms.issubset(perms['global']):
1771 return True
1771 return True
1772 return False
1772 return False
1773
1773
1774
1774
1775 class HasPermissionAnyDecorator(PermsDecorator):
1775 class HasPermissionAnyDecorator(PermsDecorator):
1776 """
1776 """
1777 Checks for access permission for any of given predicates. In order to
1777 Checks for access permission for any of given predicates. In order to
1778 fulfill the request any of predicates must be meet
1778 fulfill the request any of predicates must be meet
1779 """
1779 """
1780
1780
1781 def check_permissions(self, user):
1781 def check_permissions(self, user):
1782 perms = user.permissions_with_scope({})
1782 perms = user.permissions_with_scope({})
1783 if self.required_perms.intersection(perms['global']):
1783 if self.required_perms.intersection(perms['global']):
1784 return True
1784 return True
1785 return False
1785 return False
1786
1786
1787
1787
1788 class HasRepoPermissionAllDecorator(PermsDecorator):
1788 class HasRepoPermissionAllDecorator(PermsDecorator):
1789 """
1789 """
1790 Checks for access permission for all given predicates for specific
1790 Checks for access permission for all given predicates for specific
1791 repository. All of them have to be meet in order to fulfill the request
1791 repository. All of them have to be meet in order to fulfill the request
1792 """
1792 """
1793 def _get_repo_name(self):
1793 def _get_repo_name(self):
1794 _request = self._get_request()
1794 _request = self._get_request()
1795 return get_repo_slug(_request)
1795 return get_repo_slug(_request)
1796
1796
1797 def check_permissions(self, user):
1797 def check_permissions(self, user):
1798 perms = user.permissions
1798 perms = user.permissions
1799 repo_name = self._get_repo_name()
1799 repo_name = self._get_repo_name()
1800
1800
1801 try:
1801 try:
1802 user_perms = {perms['repositories'][repo_name]}
1802 user_perms = {perms['repositories'][repo_name]}
1803 except KeyError:
1803 except KeyError:
1804 log.debug('cannot locate repo with name: `%s` in permissions defs',
1804 log.debug('cannot locate repo with name: `%s` in permissions defs',
1805 repo_name)
1805 repo_name)
1806 return False
1806 return False
1807
1807
1808 log.debug('checking `%s` permissions for repo `%s`',
1808 log.debug('checking `%s` permissions for repo `%s`',
1809 user_perms, repo_name)
1809 user_perms, repo_name)
1810 if self.required_perms.issubset(user_perms):
1810 if self.required_perms.issubset(user_perms):
1811 return True
1811 return True
1812 return False
1812 return False
1813
1813
1814
1814
1815 class HasRepoPermissionAnyDecorator(PermsDecorator):
1815 class HasRepoPermissionAnyDecorator(PermsDecorator):
1816 """
1816 """
1817 Checks for access permission for any of given predicates for specific
1817 Checks for access permission for any of given predicates for specific
1818 repository. In order to fulfill the request any of predicates must be meet
1818 repository. In order to fulfill the request any of predicates must be meet
1819 """
1819 """
1820 def _get_repo_name(self):
1820 def _get_repo_name(self):
1821 _request = self._get_request()
1821 _request = self._get_request()
1822 return get_repo_slug(_request)
1822 return get_repo_slug(_request)
1823
1823
1824 def check_permissions(self, user):
1824 def check_permissions(self, user):
1825 perms = user.permissions
1825 perms = user.permissions
1826 repo_name = self._get_repo_name()
1826 repo_name = self._get_repo_name()
1827
1827
1828 try:
1828 try:
1829 user_perms = {perms['repositories'][repo_name]}
1829 user_perms = {perms['repositories'][repo_name]}
1830 except KeyError:
1830 except KeyError:
1831 log.debug(
1831 log.debug(
1832 'cannot locate repo with name: `%s` in permissions defs',
1832 'cannot locate repo with name: `%s` in permissions defs',
1833 repo_name)
1833 repo_name)
1834 return False
1834 return False
1835
1835
1836 log.debug('checking `%s` permissions for repo `%s`',
1836 log.debug('checking `%s` permissions for repo `%s`',
1837 user_perms, repo_name)
1837 user_perms, repo_name)
1838 if self.required_perms.intersection(user_perms):
1838 if self.required_perms.intersection(user_perms):
1839 return True
1839 return True
1840 return False
1840 return False
1841
1841
1842
1842
1843 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1843 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1844 """
1844 """
1845 Checks for access permission for all given predicates for specific
1845 Checks for access permission for all given predicates for specific
1846 repository group. All of them have to be meet in order to
1846 repository group. All of them have to be meet in order to
1847 fulfill the request
1847 fulfill the request
1848 """
1848 """
1849 def _get_repo_group_name(self):
1849 def _get_repo_group_name(self):
1850 _request = self._get_request()
1850 _request = self._get_request()
1851 return get_repo_group_slug(_request)
1851 return get_repo_group_slug(_request)
1852
1852
1853 def check_permissions(self, user):
1853 def check_permissions(self, user):
1854 perms = user.permissions
1854 perms = user.permissions
1855 group_name = self._get_repo_group_name()
1855 group_name = self._get_repo_group_name()
1856 try:
1856 try:
1857 user_perms = {perms['repositories_groups'][group_name]}
1857 user_perms = {perms['repositories_groups'][group_name]}
1858 except KeyError:
1858 except KeyError:
1859 log.debug(
1859 log.debug(
1860 'cannot locate repo group with name: `%s` in permissions defs',
1860 'cannot locate repo group with name: `%s` in permissions defs',
1861 group_name)
1861 group_name)
1862 return False
1862 return False
1863
1863
1864 log.debug('checking `%s` permissions for repo group `%s`',
1864 log.debug('checking `%s` permissions for repo group `%s`',
1865 user_perms, group_name)
1865 user_perms, group_name)
1866 if self.required_perms.issubset(user_perms):
1866 if self.required_perms.issubset(user_perms):
1867 return True
1867 return True
1868 return False
1868 return False
1869
1869
1870
1870
1871 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1871 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1872 """
1872 """
1873 Checks for access permission for any of given predicates for specific
1873 Checks for access permission for any of given predicates for specific
1874 repository group. In order to fulfill the request any
1874 repository group. In order to fulfill the request any
1875 of predicates must be met
1875 of predicates must be met
1876 """
1876 """
1877 def _get_repo_group_name(self):
1877 def _get_repo_group_name(self):
1878 _request = self._get_request()
1878 _request = self._get_request()
1879 return get_repo_group_slug(_request)
1879 return get_repo_group_slug(_request)
1880
1880
1881 def check_permissions(self, user):
1881 def check_permissions(self, user):
1882 perms = user.permissions
1882 perms = user.permissions
1883 group_name = self._get_repo_group_name()
1883 group_name = self._get_repo_group_name()
1884
1884
1885 try:
1885 try:
1886 user_perms = {perms['repositories_groups'][group_name]}
1886 user_perms = {perms['repositories_groups'][group_name]}
1887 except KeyError:
1887 except KeyError:
1888 log.debug(
1888 log.debug(
1889 'cannot locate repo group with name: `%s` in permissions defs',
1889 'cannot locate repo group with name: `%s` in permissions defs',
1890 group_name)
1890 group_name)
1891 return False
1891 return False
1892
1892
1893 log.debug('checking `%s` permissions for repo group `%s`',
1893 log.debug('checking `%s` permissions for repo group `%s`',
1894 user_perms, group_name)
1894 user_perms, group_name)
1895 if self.required_perms.intersection(user_perms):
1895 if self.required_perms.intersection(user_perms):
1896 return True
1896 return True
1897 return False
1897 return False
1898
1898
1899
1899
1900 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1900 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1901 """
1901 """
1902 Checks for access permission for all given predicates for specific
1902 Checks for access permission for all given predicates for specific
1903 user group. All of them have to be meet in order to fulfill the request
1903 user group. All of them have to be meet in order to fulfill the request
1904 """
1904 """
1905 def _get_user_group_name(self):
1905 def _get_user_group_name(self):
1906 _request = self._get_request()
1906 _request = self._get_request()
1907 return get_user_group_slug(_request)
1907 return get_user_group_slug(_request)
1908
1908
1909 def check_permissions(self, user):
1909 def check_permissions(self, user):
1910 perms = user.permissions
1910 perms = user.permissions
1911 group_name = self._get_user_group_name()
1911 group_name = self._get_user_group_name()
1912 try:
1912 try:
1913 user_perms = {perms['user_groups'][group_name]}
1913 user_perms = {perms['user_groups'][group_name]}
1914 except KeyError:
1914 except KeyError:
1915 return False
1915 return False
1916
1916
1917 if self.required_perms.issubset(user_perms):
1917 if self.required_perms.issubset(user_perms):
1918 return True
1918 return True
1919 return False
1919 return False
1920
1920
1921
1921
1922 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1922 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1923 """
1923 """
1924 Checks for access permission for any of given predicates for specific
1924 Checks for access permission for any of given predicates for specific
1925 user group. In order to fulfill the request any of predicates must be meet
1925 user group. In order to fulfill the request any of predicates must be meet
1926 """
1926 """
1927 def _get_user_group_name(self):
1927 def _get_user_group_name(self):
1928 _request = self._get_request()
1928 _request = self._get_request()
1929 return get_user_group_slug(_request)
1929 return get_user_group_slug(_request)
1930
1930
1931 def check_permissions(self, user):
1931 def check_permissions(self, user):
1932 perms = user.permissions
1932 perms = user.permissions
1933 group_name = self._get_user_group_name()
1933 group_name = self._get_user_group_name()
1934 try:
1934 try:
1935 user_perms = {perms['user_groups'][group_name]}
1935 user_perms = {perms['user_groups'][group_name]}
1936 except KeyError:
1936 except KeyError:
1937 return False
1937 return False
1938
1938
1939 if self.required_perms.intersection(user_perms):
1939 if self.required_perms.intersection(user_perms):
1940 return True
1940 return True
1941 return False
1941 return False
1942
1942
1943
1943
1944 # CHECK FUNCTIONS
1944 # CHECK FUNCTIONS
1945 class PermsFunction(object):
1945 class PermsFunction(object):
1946 """Base function for other check functions"""
1946 """Base function for other check functions"""
1947
1947
1948 def __init__(self, *perms):
1948 def __init__(self, *perms):
1949 self.required_perms = set(perms)
1949 self.required_perms = set(perms)
1950 self.repo_name = None
1950 self.repo_name = None
1951 self.repo_group_name = None
1951 self.repo_group_name = None
1952 self.user_group_name = None
1952 self.user_group_name = None
1953
1953
1954 def __bool__(self):
1954 def __bool__(self):
1955 frame = inspect.currentframe()
1955 frame = inspect.currentframe()
1956 stack_trace = traceback.format_stack(frame)
1956 stack_trace = traceback.format_stack(frame)
1957 log.error('Checking bool value on a class instance of perm '
1957 log.error('Checking bool value on a class instance of perm '
1958 'function is not allowed: %s', ''.join(stack_trace))
1958 'function is not allowed: %s', ''.join(stack_trace))
1959 # rather than throwing errors, here we always return False so if by
1959 # rather than throwing errors, here we always return False so if by
1960 # accident someone checks truth for just an instance it will always end
1960 # accident someone checks truth for just an instance it will always end
1961 # up in returning False
1961 # up in returning False
1962 return False
1962 return False
1963 __nonzero__ = __bool__
1963 __nonzero__ = __bool__
1964
1964
1965 def __call__(self, check_location='', user=None):
1965 def __call__(self, check_location='', user=None):
1966 if not user:
1966 if not user:
1967 log.debug('Using user attribute from global request')
1967 log.debug('Using user attribute from global request')
1968 request = self._get_request()
1968 request = self._get_request()
1969 user = request.user
1969 user = request.user
1970
1970
1971 # init auth user if not already given
1971 # init auth user if not already given
1972 if not isinstance(user, AuthUser):
1972 if not isinstance(user, AuthUser):
1973 log.debug('Wrapping user %s into AuthUser', user)
1973 log.debug('Wrapping user %s into AuthUser', user)
1974 user = AuthUser(user.user_id)
1974 user = AuthUser(user.user_id)
1975
1975
1976 cls_name = self.__class__.__name__
1976 cls_name = self.__class__.__name__
1977 check_scope = self._get_check_scope(cls_name)
1977 check_scope = self._get_check_scope(cls_name)
1978 check_location = check_location or 'unspecified location'
1978 check_location = check_location or 'unspecified location'
1979
1979
1980 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1980 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1981 self.required_perms, user, check_scope, check_location)
1981 self.required_perms, user, check_scope, check_location)
1982 if not user:
1982 if not user:
1983 log.warning('Empty user given for permission check')
1983 log.warning('Empty user given for permission check')
1984 return False
1984 return False
1985
1985
1986 if self.check_permissions(user):
1986 if self.check_permissions(user):
1987 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1987 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1988 check_scope, user, check_location)
1988 check_scope, user, check_location)
1989 return True
1989 return True
1990
1990
1991 else:
1991 else:
1992 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1992 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1993 check_scope, user, check_location)
1993 check_scope, user, check_location)
1994 return False
1994 return False
1995
1995
1996 def _get_request(self):
1996 def _get_request(self):
1997 return get_request(self)
1997 return get_request(self)
1998
1998
1999 def _get_check_scope(self, cls_name):
1999 def _get_check_scope(self, cls_name):
2000 return {
2000 return {
2001 'HasPermissionAll': 'GLOBAL',
2001 'HasPermissionAll': 'GLOBAL',
2002 'HasPermissionAny': 'GLOBAL',
2002 'HasPermissionAny': 'GLOBAL',
2003 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
2003 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
2004 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
2004 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
2005 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
2005 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
2006 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
2006 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
2007 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
2007 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
2008 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
2008 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
2009 }.get(cls_name, '?:%s' % cls_name)
2009 }.get(cls_name, '?:%s' % cls_name)
2010
2010
2011 def check_permissions(self, user):
2011 def check_permissions(self, user):
2012 """Dummy function for overriding"""
2012 """Dummy function for overriding"""
2013 raise Exception('You have to write this function in child class')
2013 raise Exception('You have to write this function in child class')
2014
2014
2015
2015
2016 class HasPermissionAll(PermsFunction):
2016 class HasPermissionAll(PermsFunction):
2017 def check_permissions(self, user):
2017 def check_permissions(self, user):
2018 perms = user.permissions_with_scope({})
2018 perms = user.permissions_with_scope({})
2019 if self.required_perms.issubset(perms.get('global')):
2019 if self.required_perms.issubset(perms.get('global')):
2020 return True
2020 return True
2021 return False
2021 return False
2022
2022
2023
2023
2024 class HasPermissionAny(PermsFunction):
2024 class HasPermissionAny(PermsFunction):
2025 def check_permissions(self, user):
2025 def check_permissions(self, user):
2026 perms = user.permissions_with_scope({})
2026 perms = user.permissions_with_scope({})
2027 if self.required_perms.intersection(perms.get('global')):
2027 if self.required_perms.intersection(perms.get('global')):
2028 return True
2028 return True
2029 return False
2029 return False
2030
2030
2031
2031
2032 class HasRepoPermissionAll(PermsFunction):
2032 class HasRepoPermissionAll(PermsFunction):
2033 def __call__(self, repo_name=None, check_location='', user=None):
2033 def __call__(self, repo_name=None, check_location='', user=None):
2034 self.repo_name = repo_name
2034 self.repo_name = repo_name
2035 return super(HasRepoPermissionAll, self).__call__(check_location, user)
2035 return super(HasRepoPermissionAll, self).__call__(check_location, user)
2036
2036
2037 def _get_repo_name(self):
2037 def _get_repo_name(self):
2038 if not self.repo_name:
2038 if not self.repo_name:
2039 _request = self._get_request()
2039 _request = self._get_request()
2040 self.repo_name = get_repo_slug(_request)
2040 self.repo_name = get_repo_slug(_request)
2041 return self.repo_name
2041 return self.repo_name
2042
2042
2043 def check_permissions(self, user):
2043 def check_permissions(self, user):
2044 self.repo_name = self._get_repo_name()
2044 self.repo_name = self._get_repo_name()
2045 perms = user.permissions
2045 perms = user.permissions
2046 try:
2046 try:
2047 user_perms = {perms['repositories'][self.repo_name]}
2047 user_perms = {perms['repositories'][self.repo_name]}
2048 except KeyError:
2048 except KeyError:
2049 return False
2049 return False
2050 if self.required_perms.issubset(user_perms):
2050 if self.required_perms.issubset(user_perms):
2051 return True
2051 return True
2052 return False
2052 return False
2053
2053
2054
2054
2055 class HasRepoPermissionAny(PermsFunction):
2055 class HasRepoPermissionAny(PermsFunction):
2056 def __call__(self, repo_name=None, check_location='', user=None):
2056 def __call__(self, repo_name=None, check_location='', user=None):
2057 self.repo_name = repo_name
2057 self.repo_name = repo_name
2058 return super(HasRepoPermissionAny, self).__call__(check_location, user)
2058 return super(HasRepoPermissionAny, self).__call__(check_location, user)
2059
2059
2060 def _get_repo_name(self):
2060 def _get_repo_name(self):
2061 if not self.repo_name:
2061 if not self.repo_name:
2062 _request = self._get_request()
2062 _request = self._get_request()
2063 self.repo_name = get_repo_slug(_request)
2063 self.repo_name = get_repo_slug(_request)
2064 return self.repo_name
2064 return self.repo_name
2065
2065
2066 def check_permissions(self, user):
2066 def check_permissions(self, user):
2067 self.repo_name = self._get_repo_name()
2067 self.repo_name = self._get_repo_name()
2068 perms = user.permissions
2068 perms = user.permissions
2069 try:
2069 try:
2070 user_perms = {perms['repositories'][self.repo_name]}
2070 user_perms = {perms['repositories'][self.repo_name]}
2071 except KeyError:
2071 except KeyError:
2072 return False
2072 return False
2073 if self.required_perms.intersection(user_perms):
2073 if self.required_perms.intersection(user_perms):
2074 return True
2074 return True
2075 return False
2075 return False
2076
2076
2077
2077
2078 class HasRepoGroupPermissionAny(PermsFunction):
2078 class HasRepoGroupPermissionAny(PermsFunction):
2079 def __call__(self, group_name=None, check_location='', user=None):
2079 def __call__(self, group_name=None, check_location='', user=None):
2080 self.repo_group_name = group_name
2080 self.repo_group_name = group_name
2081 return super(HasRepoGroupPermissionAny, self).__call__(check_location, user)
2081 return super(HasRepoGroupPermissionAny, self).__call__(check_location, user)
2082
2082
2083 def check_permissions(self, user):
2083 def check_permissions(self, user):
2084 perms = user.permissions
2084 perms = user.permissions
2085 try:
2085 try:
2086 user_perms = {perms['repositories_groups'][self.repo_group_name]}
2086 user_perms = {perms['repositories_groups'][self.repo_group_name]}
2087 except KeyError:
2087 except KeyError:
2088 return False
2088 return False
2089 if self.required_perms.intersection(user_perms):
2089 if self.required_perms.intersection(user_perms):
2090 return True
2090 return True
2091 return False
2091 return False
2092
2092
2093
2093
2094 class HasRepoGroupPermissionAll(PermsFunction):
2094 class HasRepoGroupPermissionAll(PermsFunction):
2095 def __call__(self, group_name=None, check_location='', user=None):
2095 def __call__(self, group_name=None, check_location='', user=None):
2096 self.repo_group_name = group_name
2096 self.repo_group_name = group_name
2097 return super(HasRepoGroupPermissionAll, self).__call__(check_location, user)
2097 return super(HasRepoGroupPermissionAll, self).__call__(check_location, user)
2098
2098
2099 def check_permissions(self, user):
2099 def check_permissions(self, user):
2100 perms = user.permissions
2100 perms = user.permissions
2101 try:
2101 try:
2102 user_perms = {perms['repositories_groups'][self.repo_group_name]}
2102 user_perms = {perms['repositories_groups'][self.repo_group_name]}
2103 except KeyError:
2103 except KeyError:
2104 return False
2104 return False
2105 if self.required_perms.issubset(user_perms):
2105 if self.required_perms.issubset(user_perms):
2106 return True
2106 return True
2107 return False
2107 return False
2108
2108
2109
2109
2110 class HasUserGroupPermissionAny(PermsFunction):
2110 class HasUserGroupPermissionAny(PermsFunction):
2111 def __call__(self, user_group_name=None, check_location='', user=None):
2111 def __call__(self, user_group_name=None, check_location='', user=None):
2112 self.user_group_name = user_group_name
2112 self.user_group_name = user_group_name
2113 return super(HasUserGroupPermissionAny, self).__call__(check_location, user)
2113 return super(HasUserGroupPermissionAny, self).__call__(check_location, user)
2114
2114
2115 def check_permissions(self, user):
2115 def check_permissions(self, user):
2116 perms = user.permissions
2116 perms = user.permissions
2117 try:
2117 try:
2118 user_perms = {perms['user_groups'][self.user_group_name]}
2118 user_perms = {perms['user_groups'][self.user_group_name]}
2119 except KeyError:
2119 except KeyError:
2120 return False
2120 return False
2121 if self.required_perms.intersection(user_perms):
2121 if self.required_perms.intersection(user_perms):
2122 return True
2122 return True
2123 return False
2123 return False
2124
2124
2125
2125
2126 class HasUserGroupPermissionAll(PermsFunction):
2126 class HasUserGroupPermissionAll(PermsFunction):
2127 def __call__(self, user_group_name=None, check_location='', user=None):
2127 def __call__(self, user_group_name=None, check_location='', user=None):
2128 self.user_group_name = user_group_name
2128 self.user_group_name = user_group_name
2129 return super(HasUserGroupPermissionAll, self).__call__(check_location, user)
2129 return super(HasUserGroupPermissionAll, self).__call__(check_location, user)
2130
2130
2131 def check_permissions(self, user):
2131 def check_permissions(self, user):
2132 perms = user.permissions
2132 perms = user.permissions
2133 try:
2133 try:
2134 user_perms = {perms['user_groups'][self.user_group_name]}
2134 user_perms = {perms['user_groups'][self.user_group_name]}
2135 except KeyError:
2135 except KeyError:
2136 return False
2136 return False
2137 if self.required_perms.issubset(user_perms):
2137 if self.required_perms.issubset(user_perms):
2138 return True
2138 return True
2139 return False
2139 return False
2140
2140
2141
2141
2142 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
2142 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
2143 class HasPermissionAnyMiddleware(object):
2143 class HasPermissionAnyMiddleware(object):
2144 def __init__(self, *perms):
2144 def __init__(self, *perms):
2145 self.required_perms = set(perms)
2145 self.required_perms = set(perms)
2146
2146
2147 def __call__(self, auth_user, repo_name):
2147 def __call__(self, auth_user, repo_name):
2148 # repo_name MUST be unicode, since we handle keys in permission
2148 # repo_name MUST be unicode, since we handle keys in permission
2149 # dict by unicode
2149 # dict by unicode
2150 repo_name = safe_unicode(repo_name)
2150 repo_name = safe_unicode(repo_name)
2151 log.debug(
2151 log.debug(
2152 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
2152 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
2153 self.required_perms, auth_user, repo_name)
2153 self.required_perms, auth_user, repo_name)
2154
2154
2155 if self.check_permissions(auth_user, repo_name):
2155 if self.check_permissions(auth_user, repo_name):
2156 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
2156 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
2157 repo_name, auth_user, 'PermissionMiddleware')
2157 repo_name, auth_user, 'PermissionMiddleware')
2158 return True
2158 return True
2159
2159
2160 else:
2160 else:
2161 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
2161 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
2162 repo_name, auth_user, 'PermissionMiddleware')
2162 repo_name, auth_user, 'PermissionMiddleware')
2163 return False
2163 return False
2164
2164
2165 def check_permissions(self, user, repo_name):
2165 def check_permissions(self, user, repo_name):
2166 perms = user.permissions_with_scope({'repo_name': repo_name})
2166 perms = user.permissions_with_scope({'repo_name': repo_name})
2167
2167
2168 try:
2168 try:
2169 user_perms = {perms['repositories'][repo_name]}
2169 user_perms = {perms['repositories'][repo_name]}
2170 except Exception:
2170 except Exception:
2171 log.exception('Error while accessing user permissions')
2171 log.exception('Error while accessing user permissions')
2172 return False
2172 return False
2173
2173
2174 if self.required_perms.intersection(user_perms):
2174 if self.required_perms.intersection(user_perms):
2175 return True
2175 return True
2176 return False
2176 return False
2177
2177
2178
2178
2179 # SPECIAL VERSION TO HANDLE API AUTH
2179 # SPECIAL VERSION TO HANDLE API AUTH
2180 class _BaseApiPerm(object):
2180 class _BaseApiPerm(object):
2181 def __init__(self, *perms):
2181 def __init__(self, *perms):
2182 self.required_perms = set(perms)
2182 self.required_perms = set(perms)
2183
2183
2184 def __call__(self, check_location=None, user=None, repo_name=None,
2184 def __call__(self, check_location=None, user=None, repo_name=None,
2185 group_name=None, user_group_name=None):
2185 group_name=None, user_group_name=None):
2186 cls_name = self.__class__.__name__
2186 cls_name = self.__class__.__name__
2187 check_scope = 'global:%s' % (self.required_perms,)
2187 check_scope = 'global:%s' % (self.required_perms,)
2188 if repo_name:
2188 if repo_name:
2189 check_scope += ', repo_name:%s' % (repo_name,)
2189 check_scope += ', repo_name:%s' % (repo_name,)
2190
2190
2191 if group_name:
2191 if group_name:
2192 check_scope += ', repo_group_name:%s' % (group_name,)
2192 check_scope += ', repo_group_name:%s' % (group_name,)
2193
2193
2194 if user_group_name:
2194 if user_group_name:
2195 check_scope += ', user_group_name:%s' % (user_group_name,)
2195 check_scope += ', user_group_name:%s' % (user_group_name,)
2196
2196
2197 log.debug('checking cls:%s %s %s @ %s',
2197 log.debug('checking cls:%s %s %s @ %s',
2198 cls_name, self.required_perms, check_scope, check_location)
2198 cls_name, self.required_perms, check_scope, check_location)
2199 if not user:
2199 if not user:
2200 log.debug('Empty User passed into arguments')
2200 log.debug('Empty User passed into arguments')
2201 return False
2201 return False
2202
2202
2203 # process user
2203 # process user
2204 if not isinstance(user, AuthUser):
2204 if not isinstance(user, AuthUser):
2205 user = AuthUser(user.user_id)
2205 user = AuthUser(user.user_id)
2206 if not check_location:
2206 if not check_location:
2207 check_location = 'unspecified'
2207 check_location = 'unspecified'
2208 if self.check_permissions(user.permissions, repo_name, group_name,
2208 if self.check_permissions(user.permissions, repo_name, group_name,
2209 user_group_name):
2209 user_group_name):
2210 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2210 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
2211 check_scope, user, check_location)
2211 check_scope, user, check_location)
2212 return True
2212 return True
2213
2213
2214 else:
2214 else:
2215 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2215 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
2216 check_scope, user, check_location)
2216 check_scope, user, check_location)
2217 return False
2217 return False
2218
2218
2219 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2219 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2220 user_group_name=None):
2220 user_group_name=None):
2221 """
2221 """
2222 implement in child class should return True if permissions are ok,
2222 implement in child class should return True if permissions are ok,
2223 False otherwise
2223 False otherwise
2224
2224
2225 :param perm_defs: dict with permission definitions
2225 :param perm_defs: dict with permission definitions
2226 :param repo_name: repo name
2226 :param repo_name: repo name
2227 """
2227 """
2228 raise NotImplementedError()
2228 raise NotImplementedError()
2229
2229
2230
2230
2231 class HasPermissionAllApi(_BaseApiPerm):
2231 class HasPermissionAllApi(_BaseApiPerm):
2232 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2232 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2233 user_group_name=None):
2233 user_group_name=None):
2234 if self.required_perms.issubset(perm_defs.get('global')):
2234 if self.required_perms.issubset(perm_defs.get('global')):
2235 return True
2235 return True
2236 return False
2236 return False
2237
2237
2238
2238
2239 class HasPermissionAnyApi(_BaseApiPerm):
2239 class HasPermissionAnyApi(_BaseApiPerm):
2240 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2240 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2241 user_group_name=None):
2241 user_group_name=None):
2242 if self.required_perms.intersection(perm_defs.get('global')):
2242 if self.required_perms.intersection(perm_defs.get('global')):
2243 return True
2243 return True
2244 return False
2244 return False
2245
2245
2246
2246
2247 class HasRepoPermissionAllApi(_BaseApiPerm):
2247 class HasRepoPermissionAllApi(_BaseApiPerm):
2248 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2248 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2249 user_group_name=None):
2249 user_group_name=None):
2250 try:
2250 try:
2251 _user_perms = {perm_defs['repositories'][repo_name]}
2251 _user_perms = {perm_defs['repositories'][repo_name]}
2252 except KeyError:
2252 except KeyError:
2253 log.warning(traceback.format_exc())
2253 log.warning(traceback.format_exc())
2254 return False
2254 return False
2255 if self.required_perms.issubset(_user_perms):
2255 if self.required_perms.issubset(_user_perms):
2256 return True
2256 return True
2257 return False
2257 return False
2258
2258
2259
2259
2260 class HasRepoPermissionAnyApi(_BaseApiPerm):
2260 class HasRepoPermissionAnyApi(_BaseApiPerm):
2261 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2261 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2262 user_group_name=None):
2262 user_group_name=None):
2263 try:
2263 try:
2264 _user_perms = {perm_defs['repositories'][repo_name]}
2264 _user_perms = {perm_defs['repositories'][repo_name]}
2265 except KeyError:
2265 except KeyError:
2266 log.warning(traceback.format_exc())
2266 log.warning(traceback.format_exc())
2267 return False
2267 return False
2268 if self.required_perms.intersection(_user_perms):
2268 if self.required_perms.intersection(_user_perms):
2269 return True
2269 return True
2270 return False
2270 return False
2271
2271
2272
2272
2273 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
2273 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
2274 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2274 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2275 user_group_name=None):
2275 user_group_name=None):
2276 try:
2276 try:
2277 _user_perms = {perm_defs['repositories_groups'][group_name]}
2277 _user_perms = {perm_defs['repositories_groups'][group_name]}
2278 except KeyError:
2278 except KeyError:
2279 log.warning(traceback.format_exc())
2279 log.warning(traceback.format_exc())
2280 return False
2280 return False
2281 if self.required_perms.intersection(_user_perms):
2281 if self.required_perms.intersection(_user_perms):
2282 return True
2282 return True
2283 return False
2283 return False
2284
2284
2285
2285
2286 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
2286 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
2287 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2287 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2288 user_group_name=None):
2288 user_group_name=None):
2289 try:
2289 try:
2290 _user_perms = {perm_defs['repositories_groups'][group_name]}
2290 _user_perms = {perm_defs['repositories_groups'][group_name]}
2291 except KeyError:
2291 except KeyError:
2292 log.warning(traceback.format_exc())
2292 log.warning(traceback.format_exc())
2293 return False
2293 return False
2294 if self.required_perms.issubset(_user_perms):
2294 if self.required_perms.issubset(_user_perms):
2295 return True
2295 return True
2296 return False
2296 return False
2297
2297
2298
2298
2299 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
2299 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
2300 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2300 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
2301 user_group_name=None):
2301 user_group_name=None):
2302 try:
2302 try:
2303 _user_perms = {perm_defs['user_groups'][user_group_name]}
2303 _user_perms = {perm_defs['user_groups'][user_group_name]}
2304 except KeyError:
2304 except KeyError:
2305 log.warning(traceback.format_exc())
2305 log.warning(traceback.format_exc())
2306 return False
2306 return False
2307 if self.required_perms.intersection(_user_perms):
2307 if self.required_perms.intersection(_user_perms):
2308 return True
2308 return True
2309 return False
2309 return False
2310
2310
2311
2311
2312 def check_ip_access(source_ip, allowed_ips=None):
2312 def check_ip_access(source_ip, allowed_ips=None):
2313 """
2313 """
2314 Checks if source_ip is a subnet of any of allowed_ips.
2314 Checks if source_ip is a subnet of any of allowed_ips.
2315
2315
2316 :param source_ip:
2316 :param source_ip:
2317 :param allowed_ips: list of allowed ips together with mask
2317 :param allowed_ips: list of allowed ips together with mask
2318 """
2318 """
2319 log.debug('checking if ip:%s is subnet of %s', source_ip, allowed_ips)
2319 log.debug('checking if ip:%s is subnet of %s', source_ip, allowed_ips)
2320 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
2320 source_ip_address = ipaddress.ip_address(safe_unicode(source_ip))
2321 if isinstance(allowed_ips, (tuple, list, set)):
2321 if isinstance(allowed_ips, (tuple, list, set)):
2322 for ip in allowed_ips:
2322 for ip in allowed_ips:
2323 ip = safe_unicode(ip)
2323 ip = safe_unicode(ip)
2324 try:
2324 try:
2325 network_address = ipaddress.ip_network(ip, strict=False)
2325 network_address = ipaddress.ip_network(ip, strict=False)
2326 if source_ip_address in network_address:
2326 if source_ip_address in network_address:
2327 log.debug('IP %s is network %s', source_ip_address, network_address)
2327 log.debug('IP %s is network %s', source_ip_address, network_address)
2328 return True
2328 return True
2329 # for any case we cannot determine the IP, don't crash just
2329 # for any case we cannot determine the IP, don't crash just
2330 # skip it and log as error, we want to say forbidden still when
2330 # skip it and log as error, we want to say forbidden still when
2331 # sending bad IP
2331 # sending bad IP
2332 except Exception:
2332 except Exception:
2333 log.error(traceback.format_exc())
2333 log.error(traceback.format_exc())
2334 continue
2334 continue
2335 return False
2335 return False
2336
2336
2337
2337
2338 def get_cython_compat_decorator(wrapper, func):
2338 def get_cython_compat_decorator(wrapper, func):
2339 """
2339 """
2340 Creates a cython compatible decorator. The previously used
2340 Creates a cython compatible decorator. The previously used
2341 decorator.decorator() function seems to be incompatible with cython.
2341 decorator.decorator() function seems to be incompatible with cython.
2342
2342
2343 :param wrapper: __wrapper method of the decorator class
2343 :param wrapper: __wrapper method of the decorator class
2344 :param func: decorated function
2344 :param func: decorated function
2345 """
2345 """
2346 @wraps(func)
2346 @wraps(func)
2347 def local_wrapper(*args, **kwds):
2347 def local_wrapper(*args, **kwds):
2348 return wrapper(func, *args, **kwds)
2348 return wrapper(func, *args, **kwds)
2349 local_wrapper.__wrapped__ = func
2349 local_wrapper.__wrapped__ = func
2350 return local_wrapper
2350 return local_wrapper
2351
2351
2352
2352
@@ -1,4758 +1,4758 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import hashlib
28 import hashlib
29 import logging
29 import logging
30 import datetime
30 import datetime
31 import warnings
31 import warnings
32 import ipaddress
32 import ipaddress
33 import functools
33 import functools
34 import traceback
34 import traceback
35 import collections
35 import collections
36
36
37 from sqlalchemy import (
37 from sqlalchemy import (
38 or_, and_, not_, func, TypeDecorator, event,
38 or_, and_, not_, func, TypeDecorator, event,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 Text, Float, PickleType)
41 Text, Float, PickleType)
42 from sqlalchemy.sql.expression import true, false
42 from sqlalchemy.sql.expression import true, false
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
44 from sqlalchemy.orm import (
44 from sqlalchemy.orm import (
45 relationship, joinedload, class_mapper, validates, aliased)
45 relationship, joinedload, class_mapper, validates, aliased)
46 from sqlalchemy.ext.declarative import declared_attr
46 from sqlalchemy.ext.declarative import declared_attr
47 from sqlalchemy.ext.hybrid import hybrid_property
47 from sqlalchemy.ext.hybrid import hybrid_property
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
49 from sqlalchemy.dialects.mysql import LONGTEXT
49 from sqlalchemy.dialects.mysql import LONGTEXT
50 from zope.cachedescriptors.property import Lazy as LazyProperty
50 from zope.cachedescriptors.property import Lazy as LazyProperty
51 from pyramid import compat
51 from pyramid import compat
52 from pyramid.threadlocal import get_current_request
52 from pyramid.threadlocal import get_current_request
53
53
54 from rhodecode.translation import _
54 from rhodecode.translation import _
55 from rhodecode.lib.vcs import get_vcs_instance
55 from rhodecode.lib.vcs import get_vcs_instance
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
57 from rhodecode.lib.utils2 import (
57 from rhodecode.lib.utils2 import (
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
60 glob2re, StrictAttributeDict, cleaned_uri)
60 glob2re, StrictAttributeDict, cleaned_uri)
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
62 JsonRaw
62 JsonRaw
63 from rhodecode.lib.ext_json import json
63 from rhodecode.lib.ext_json import json
64 from rhodecode.lib.caching_query import FromCache
64 from rhodecode.lib.caching_query import FromCache
65 from rhodecode.lib.encrypt import AESCipher
65 from rhodecode.lib.encrypt import AESCipher
66
66
67 from rhodecode.model.meta import Base, Session
67 from rhodecode.model.meta import Base, Session
68
68
69 URL_SEP = '/'
69 URL_SEP = '/'
70 log = logging.getLogger(__name__)
70 log = logging.getLogger(__name__)
71
71
72 # =============================================================================
72 # =============================================================================
73 # BASE CLASSES
73 # BASE CLASSES
74 # =============================================================================
74 # =============================================================================
75
75
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
77 # beaker.session.secret if first is not set.
77 # beaker.session.secret if first is not set.
78 # and initialized at environment.py
78 # and initialized at environment.py
79 ENCRYPTION_KEY = None
79 ENCRYPTION_KEY = None
80
80
81 # used to sort permissions by types, '#' used here is not allowed to be in
81 # used to sort permissions by types, '#' used here is not allowed to be in
82 # usernames, and it's very early in sorted string.printable table.
82 # usernames, and it's very early in sorted string.printable table.
83 PERMISSION_TYPE_SORT = {
83 PERMISSION_TYPE_SORT = {
84 'admin': '####',
84 'admin': '####',
85 'write': '###',
85 'write': '###',
86 'read': '##',
86 'read': '##',
87 'none': '#',
87 'none': '#',
88 }
88 }
89
89
90
90
91 def display_user_sort(obj):
91 def display_user_sort(obj):
92 """
92 """
93 Sort function used to sort permissions in .permissions() function of
93 Sort function used to sort permissions in .permissions() function of
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
95 of all other resources
95 of all other resources
96 """
96 """
97
97
98 if obj.username == User.DEFAULT_USER:
98 if obj.username == User.DEFAULT_USER:
99 return '#####'
99 return '#####'
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
101 return prefix + obj.username
101 return prefix + obj.username
102
102
103
103
104 def display_user_group_sort(obj):
104 def display_user_group_sort(obj):
105 """
105 """
106 Sort function used to sort permissions in .permissions() function of
106 Sort function used to sort permissions in .permissions() function of
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
108 of all other resources
108 of all other resources
109 """
109 """
110
110
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
112 return prefix + obj.users_group_name
112 return prefix + obj.users_group_name
113
113
114
114
115 def _hash_key(k):
115 def _hash_key(k):
116 return sha1_safe(k)
116 return sha1_safe(k)
117
117
118
118
119 def in_filter_generator(qry, items, limit=500):
119 def in_filter_generator(qry, items, limit=500):
120 """
120 """
121 Splits IN() into multiple with OR
121 Splits IN() into multiple with OR
122 e.g.::
122 e.g.::
123 cnt = Repository.query().filter(
123 cnt = Repository.query().filter(
124 or_(
124 or_(
125 *in_filter_generator(Repository.repo_id, range(100000))
125 *in_filter_generator(Repository.repo_id, range(100000))
126 )).count()
126 )).count()
127 """
127 """
128 if not items:
128 if not items:
129 # empty list will cause empty query which might cause security issues
129 # empty list will cause empty query which might cause security issues
130 # this can lead to hidden unpleasant results
130 # this can lead to hidden unpleasant results
131 items = [-1]
131 items = [-1]
132
132
133 parts = []
133 parts = []
134 for chunk in xrange(0, len(items), limit):
134 for chunk in xrange(0, len(items), limit):
135 parts.append(
135 parts.append(
136 qry.in_(items[chunk: chunk + limit])
136 qry.in_(items[chunk: chunk + limit])
137 )
137 )
138
138
139 return parts
139 return parts
140
140
141
141
142 base_table_args = {
142 base_table_args = {
143 'extend_existing': True,
143 'extend_existing': True,
144 'mysql_engine': 'InnoDB',
144 'mysql_engine': 'InnoDB',
145 'mysql_charset': 'utf8',
145 'mysql_charset': 'utf8',
146 'sqlite_autoincrement': True
146 'sqlite_autoincrement': True
147 }
147 }
148
148
149
149
150 class EncryptedTextValue(TypeDecorator):
150 class EncryptedTextValue(TypeDecorator):
151 """
151 """
152 Special column for encrypted long text data, use like::
152 Special column for encrypted long text data, use like::
153
153
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
155
155
156 This column is intelligent so if value is in unencrypted form it return
156 This column is intelligent so if value is in unencrypted form it return
157 unencrypted form, but on save it always encrypts
157 unencrypted form, but on save it always encrypts
158 """
158 """
159 impl = Text
159 impl = Text
160
160
161 def process_bind_param(self, value, dialect):
161 def process_bind_param(self, value, dialect):
162 if not value:
162 if not value:
163 return value
163 return value
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
165 # protect against double encrypting if someone manually starts
165 # protect against double encrypting if someone manually starts
166 # doing
166 # doing
167 raise ValueError('value needs to be in unencrypted format, ie. '
167 raise ValueError('value needs to be in unencrypted format, ie. '
168 'not starting with enc$aes')
168 'not starting with enc$aes')
169 return 'enc$aes_hmac$%s' % AESCipher(
169 return 'enc$aes_hmac$%s' % AESCipher(
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
171
171
172 def process_result_value(self, value, dialect):
172 def process_result_value(self, value, dialect):
173 import rhodecode
173 import rhodecode
174
174
175 if not value:
175 if not value:
176 return value
176 return value
177
177
178 parts = value.split('$', 3)
178 parts = value.split('$', 3)
179 if not len(parts) == 3:
179 if not len(parts) == 3:
180 # probably not encrypted values
180 # probably not encrypted values
181 return value
181 return value
182 else:
182 else:
183 if parts[0] != 'enc':
183 if parts[0] != 'enc':
184 # parts ok but without our header ?
184 # parts ok but without our header ?
185 return value
185 return value
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
187 'rhodecode.encrypted_values.strict') or True)
187 'rhodecode.encrypted_values.strict') or True)
188 # at that stage we know it's our encryption
188 # at that stage we know it's our encryption
189 if parts[1] == 'aes':
189 if parts[1] == 'aes':
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
191 elif parts[1] == 'aes_hmac':
191 elif parts[1] == 'aes_hmac':
192 decrypted_data = AESCipher(
192 decrypted_data = AESCipher(
193 ENCRYPTION_KEY, hmac=True,
193 ENCRYPTION_KEY, hmac=True,
194 strict_verification=enc_strict_mode).decrypt(parts[2])
194 strict_verification=enc_strict_mode).decrypt(parts[2])
195 else:
195 else:
196 raise ValueError(
196 raise ValueError(
197 'Encryption type part is wrong, must be `aes` '
197 'Encryption type part is wrong, must be `aes` '
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
199 return decrypted_data
199 return decrypted_data
200
200
201
201
202 class BaseModel(object):
202 class BaseModel(object):
203 """
203 """
204 Base Model for all classes
204 Base Model for all classes
205 """
205 """
206
206
207 @classmethod
207 @classmethod
208 def _get_keys(cls):
208 def _get_keys(cls):
209 """return column names for this model """
209 """return column names for this model """
210 return class_mapper(cls).c.keys()
210 return class_mapper(cls).c.keys()
211
211
212 def get_dict(self):
212 def get_dict(self):
213 """
213 """
214 return dict with keys and values corresponding
214 return dict with keys and values corresponding
215 to this model data """
215 to this model data """
216
216
217 d = {}
217 d = {}
218 for k in self._get_keys():
218 for k in self._get_keys():
219 d[k] = getattr(self, k)
219 d[k] = getattr(self, k)
220
220
221 # also use __json__() if present to get additional fields
221 # also use __json__() if present to get additional fields
222 _json_attr = getattr(self, '__json__', None)
222 _json_attr = getattr(self, '__json__', None)
223 if _json_attr:
223 if _json_attr:
224 # update with attributes from __json__
224 # update with attributes from __json__
225 if callable(_json_attr):
225 if callable(_json_attr):
226 _json_attr = _json_attr()
226 _json_attr = _json_attr()
227 for k, val in _json_attr.iteritems():
227 for k, val in _json_attr.iteritems():
228 d[k] = val
228 d[k] = val
229 return d
229 return d
230
230
231 def get_appstruct(self):
231 def get_appstruct(self):
232 """return list with keys and values tuples corresponding
232 """return list with keys and values tuples corresponding
233 to this model data """
233 to this model data """
234
234
235 lst = []
235 lst = []
236 for k in self._get_keys():
236 for k in self._get_keys():
237 lst.append((k, getattr(self, k),))
237 lst.append((k, getattr(self, k),))
238 return lst
238 return lst
239
239
240 def populate_obj(self, populate_dict):
240 def populate_obj(self, populate_dict):
241 """populate model with data from given populate_dict"""
241 """populate model with data from given populate_dict"""
242
242
243 for k in self._get_keys():
243 for k in self._get_keys():
244 if k in populate_dict:
244 if k in populate_dict:
245 setattr(self, k, populate_dict[k])
245 setattr(self, k, populate_dict[k])
246
246
247 @classmethod
247 @classmethod
248 def query(cls):
248 def query(cls):
249 return Session().query(cls)
249 return Session().query(cls)
250
250
251 @classmethod
251 @classmethod
252 def get(cls, id_):
252 def get(cls, id_):
253 if id_:
253 if id_:
254 return cls.query().get(id_)
254 return cls.query().get(id_)
255
255
256 @classmethod
256 @classmethod
257 def get_or_404(cls, id_):
257 def get_or_404(cls, id_):
258 from pyramid.httpexceptions import HTTPNotFound
258 from pyramid.httpexceptions import HTTPNotFound
259
259
260 try:
260 try:
261 id_ = int(id_)
261 id_ = int(id_)
262 except (TypeError, ValueError):
262 except (TypeError, ValueError):
263 raise HTTPNotFound()
263 raise HTTPNotFound()
264
264
265 res = cls.query().get(id_)
265 res = cls.query().get(id_)
266 if not res:
266 if not res:
267 raise HTTPNotFound()
267 raise HTTPNotFound()
268 return res
268 return res
269
269
270 @classmethod
270 @classmethod
271 def getAll(cls):
271 def getAll(cls):
272 # deprecated and left for backward compatibility
272 # deprecated and left for backward compatibility
273 return cls.get_all()
273 return cls.get_all()
274
274
275 @classmethod
275 @classmethod
276 def get_all(cls):
276 def get_all(cls):
277 return cls.query().all()
277 return cls.query().all()
278
278
279 @classmethod
279 @classmethod
280 def delete(cls, id_):
280 def delete(cls, id_):
281 obj = cls.query().get(id_)
281 obj = cls.query().get(id_)
282 Session().delete(obj)
282 Session().delete(obj)
283
283
284 @classmethod
284 @classmethod
285 def identity_cache(cls, session, attr_name, value):
285 def identity_cache(cls, session, attr_name, value):
286 exist_in_session = []
286 exist_in_session = []
287 for (item_cls, pkey), instance in session.identity_map.items():
287 for (item_cls, pkey), instance in session.identity_map.items():
288 if cls == item_cls and getattr(instance, attr_name) == value:
288 if cls == item_cls and getattr(instance, attr_name) == value:
289 exist_in_session.append(instance)
289 exist_in_session.append(instance)
290 if exist_in_session:
290 if exist_in_session:
291 if len(exist_in_session) == 1:
291 if len(exist_in_session) == 1:
292 return exist_in_session[0]
292 return exist_in_session[0]
293 log.exception(
293 log.exception(
294 'multiple objects with attr %s and '
294 'multiple objects with attr %s and '
295 'value %s found with same name: %r',
295 'value %s found with same name: %r',
296 attr_name, value, exist_in_session)
296 attr_name, value, exist_in_session)
297
297
298 def __repr__(self):
298 def __repr__(self):
299 if hasattr(self, '__unicode__'):
299 if hasattr(self, '__unicode__'):
300 # python repr needs to return str
300 # python repr needs to return str
301 try:
301 try:
302 return safe_str(self.__unicode__())
302 return safe_str(self.__unicode__())
303 except UnicodeDecodeError:
303 except UnicodeDecodeError:
304 pass
304 pass
305 return '<DB:%s>' % (self.__class__.__name__)
305 return '<DB:%s>' % (self.__class__.__name__)
306
306
307
307
308 class RhodeCodeSetting(Base, BaseModel):
308 class RhodeCodeSetting(Base, BaseModel):
309 __tablename__ = 'rhodecode_settings'
309 __tablename__ = 'rhodecode_settings'
310 __table_args__ = (
310 __table_args__ = (
311 UniqueConstraint('app_settings_name'),
311 UniqueConstraint('app_settings_name'),
312 base_table_args
312 base_table_args
313 )
313 )
314
314
315 SETTINGS_TYPES = {
315 SETTINGS_TYPES = {
316 'str': safe_str,
316 'str': safe_str,
317 'int': safe_int,
317 'int': safe_int,
318 'unicode': safe_unicode,
318 'unicode': safe_unicode,
319 'bool': str2bool,
319 'bool': str2bool,
320 'list': functools.partial(aslist, sep=',')
320 'list': functools.partial(aslist, sep=',')
321 }
321 }
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
323 GLOBAL_CONF_KEY = 'app_settings'
323 GLOBAL_CONF_KEY = 'app_settings'
324
324
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
329
329
330 def __init__(self, key='', val='', type='unicode'):
330 def __init__(self, key='', val='', type='unicode'):
331 self.app_settings_name = key
331 self.app_settings_name = key
332 self.app_settings_type = type
332 self.app_settings_type = type
333 self.app_settings_value = val
333 self.app_settings_value = val
334
334
335 @validates('_app_settings_value')
335 @validates('_app_settings_value')
336 def validate_settings_value(self, key, val):
336 def validate_settings_value(self, key, val):
337 assert type(val) == unicode
337 assert type(val) == unicode
338 return val
338 return val
339
339
340 @hybrid_property
340 @hybrid_property
341 def app_settings_value(self):
341 def app_settings_value(self):
342 v = self._app_settings_value
342 v = self._app_settings_value
343 _type = self.app_settings_type
343 _type = self.app_settings_type
344 if _type:
344 if _type:
345 _type = self.app_settings_type.split('.')[0]
345 _type = self.app_settings_type.split('.')[0]
346 # decode the encrypted value
346 # decode the encrypted value
347 if 'encrypted' in self.app_settings_type:
347 if 'encrypted' in self.app_settings_type:
348 cipher = EncryptedTextValue()
348 cipher = EncryptedTextValue()
349 v = safe_unicode(cipher.process_result_value(v, None))
349 v = safe_unicode(cipher.process_result_value(v, None))
350
350
351 converter = self.SETTINGS_TYPES.get(_type) or \
351 converter = self.SETTINGS_TYPES.get(_type) or \
352 self.SETTINGS_TYPES['unicode']
352 self.SETTINGS_TYPES['unicode']
353 return converter(v)
353 return converter(v)
354
354
355 @app_settings_value.setter
355 @app_settings_value.setter
356 def app_settings_value(self, val):
356 def app_settings_value(self, val):
357 """
357 """
358 Setter that will always make sure we use unicode in app_settings_value
358 Setter that will always make sure we use unicode in app_settings_value
359
359
360 :param val:
360 :param val:
361 """
361 """
362 val = safe_unicode(val)
362 val = safe_unicode(val)
363 # encode the encrypted value
363 # encode the encrypted value
364 if 'encrypted' in self.app_settings_type:
364 if 'encrypted' in self.app_settings_type:
365 cipher = EncryptedTextValue()
365 cipher = EncryptedTextValue()
366 val = safe_unicode(cipher.process_bind_param(val, None))
366 val = safe_unicode(cipher.process_bind_param(val, None))
367 self._app_settings_value = val
367 self._app_settings_value = val
368
368
369 @hybrid_property
369 @hybrid_property
370 def app_settings_type(self):
370 def app_settings_type(self):
371 return self._app_settings_type
371 return self._app_settings_type
372
372
373 @app_settings_type.setter
373 @app_settings_type.setter
374 def app_settings_type(self, val):
374 def app_settings_type(self, val):
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
376 raise Exception('type must be one of %s got %s'
376 raise Exception('type must be one of %s got %s'
377 % (self.SETTINGS_TYPES.keys(), val))
377 % (self.SETTINGS_TYPES.keys(), val))
378 self._app_settings_type = val
378 self._app_settings_type = val
379
379
380 @classmethod
380 @classmethod
381 def get_by_prefix(cls, prefix):
381 def get_by_prefix(cls, prefix):
382 return RhodeCodeSetting.query()\
382 return RhodeCodeSetting.query()\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
384 .all()
384 .all()
385
385
386 def __unicode__(self):
386 def __unicode__(self):
387 return u"<%s('%s:%s[%s]')>" % (
387 return u"<%s('%s:%s[%s]')>" % (
388 self.__class__.__name__,
388 self.__class__.__name__,
389 self.app_settings_name, self.app_settings_value,
389 self.app_settings_name, self.app_settings_value,
390 self.app_settings_type
390 self.app_settings_type
391 )
391 )
392
392
393
393
394 class RhodeCodeUi(Base, BaseModel):
394 class RhodeCodeUi(Base, BaseModel):
395 __tablename__ = 'rhodecode_ui'
395 __tablename__ = 'rhodecode_ui'
396 __table_args__ = (
396 __table_args__ = (
397 UniqueConstraint('ui_key'),
397 UniqueConstraint('ui_key'),
398 base_table_args
398 base_table_args
399 )
399 )
400
400
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
402 # HG
402 # HG
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
404 HOOK_PULL = 'outgoing.pull_logger'
404 HOOK_PULL = 'outgoing.pull_logger'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
407 HOOK_PUSH = 'changegroup.push_logger'
407 HOOK_PUSH = 'changegroup.push_logger'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
409
409
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
411 # git part is currently hardcoded.
411 # git part is currently hardcoded.
412
412
413 # SVN PATTERNS
413 # SVN PATTERNS
414 SVN_BRANCH_ID = 'vcs_svn_branch'
414 SVN_BRANCH_ID = 'vcs_svn_branch'
415 SVN_TAG_ID = 'vcs_svn_tag'
415 SVN_TAG_ID = 'vcs_svn_tag'
416
416
417 ui_id = Column(
417 ui_id = Column(
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
419 primary_key=True)
419 primary_key=True)
420 ui_section = Column(
420 ui_section = Column(
421 "ui_section", String(255), nullable=True, unique=None, default=None)
421 "ui_section", String(255), nullable=True, unique=None, default=None)
422 ui_key = Column(
422 ui_key = Column(
423 "ui_key", String(255), nullable=True, unique=None, default=None)
423 "ui_key", String(255), nullable=True, unique=None, default=None)
424 ui_value = Column(
424 ui_value = Column(
425 "ui_value", String(255), nullable=True, unique=None, default=None)
425 "ui_value", String(255), nullable=True, unique=None, default=None)
426 ui_active = Column(
426 ui_active = Column(
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
428
428
429 def __repr__(self):
429 def __repr__(self):
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
431 self.ui_key, self.ui_value)
431 self.ui_key, self.ui_value)
432
432
433
433
434 class RepoRhodeCodeSetting(Base, BaseModel):
434 class RepoRhodeCodeSetting(Base, BaseModel):
435 __tablename__ = 'repo_rhodecode_settings'
435 __tablename__ = 'repo_rhodecode_settings'
436 __table_args__ = (
436 __table_args__ = (
437 UniqueConstraint(
437 UniqueConstraint(
438 'app_settings_name', 'repository_id',
438 'app_settings_name', 'repository_id',
439 name='uq_repo_rhodecode_setting_name_repo_id'),
439 name='uq_repo_rhodecode_setting_name_repo_id'),
440 base_table_args
440 base_table_args
441 )
441 )
442
442
443 repository_id = Column(
443 repository_id = Column(
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
445 nullable=False)
445 nullable=False)
446 app_settings_id = Column(
446 app_settings_id = Column(
447 "app_settings_id", Integer(), nullable=False, unique=True,
447 "app_settings_id", Integer(), nullable=False, unique=True,
448 default=None, primary_key=True)
448 default=None, primary_key=True)
449 app_settings_name = Column(
449 app_settings_name = Column(
450 "app_settings_name", String(255), nullable=True, unique=None,
450 "app_settings_name", String(255), nullable=True, unique=None,
451 default=None)
451 default=None)
452 _app_settings_value = Column(
452 _app_settings_value = Column(
453 "app_settings_value", String(4096), nullable=True, unique=None,
453 "app_settings_value", String(4096), nullable=True, unique=None,
454 default=None)
454 default=None)
455 _app_settings_type = Column(
455 _app_settings_type = Column(
456 "app_settings_type", String(255), nullable=True, unique=None,
456 "app_settings_type", String(255), nullable=True, unique=None,
457 default=None)
457 default=None)
458
458
459 repository = relationship('Repository')
459 repository = relationship('Repository')
460
460
461 def __init__(self, repository_id, key='', val='', type='unicode'):
461 def __init__(self, repository_id, key='', val='', type='unicode'):
462 self.repository_id = repository_id
462 self.repository_id = repository_id
463 self.app_settings_name = key
463 self.app_settings_name = key
464 self.app_settings_type = type
464 self.app_settings_type = type
465 self.app_settings_value = val
465 self.app_settings_value = val
466
466
467 @validates('_app_settings_value')
467 @validates('_app_settings_value')
468 def validate_settings_value(self, key, val):
468 def validate_settings_value(self, key, val):
469 assert type(val) == unicode
469 assert type(val) == unicode
470 return val
470 return val
471
471
472 @hybrid_property
472 @hybrid_property
473 def app_settings_value(self):
473 def app_settings_value(self):
474 v = self._app_settings_value
474 v = self._app_settings_value
475 type_ = self.app_settings_type
475 type_ = self.app_settings_type
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
478 return converter(v)
478 return converter(v)
479
479
480 @app_settings_value.setter
480 @app_settings_value.setter
481 def app_settings_value(self, val):
481 def app_settings_value(self, val):
482 """
482 """
483 Setter that will always make sure we use unicode in app_settings_value
483 Setter that will always make sure we use unicode in app_settings_value
484
484
485 :param val:
485 :param val:
486 """
486 """
487 self._app_settings_value = safe_unicode(val)
487 self._app_settings_value = safe_unicode(val)
488
488
489 @hybrid_property
489 @hybrid_property
490 def app_settings_type(self):
490 def app_settings_type(self):
491 return self._app_settings_type
491 return self._app_settings_type
492
492
493 @app_settings_type.setter
493 @app_settings_type.setter
494 def app_settings_type(self, val):
494 def app_settings_type(self, val):
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
496 if val not in SETTINGS_TYPES:
496 if val not in SETTINGS_TYPES:
497 raise Exception('type must be one of %s got %s'
497 raise Exception('type must be one of %s got %s'
498 % (SETTINGS_TYPES.keys(), val))
498 % (SETTINGS_TYPES.keys(), val))
499 self._app_settings_type = val
499 self._app_settings_type = val
500
500
501 def __unicode__(self):
501 def __unicode__(self):
502 return u"<%s('%s:%s:%s[%s]')>" % (
502 return u"<%s('%s:%s:%s[%s]')>" % (
503 self.__class__.__name__, self.repository.repo_name,
503 self.__class__.__name__, self.repository.repo_name,
504 self.app_settings_name, self.app_settings_value,
504 self.app_settings_name, self.app_settings_value,
505 self.app_settings_type
505 self.app_settings_type
506 )
506 )
507
507
508
508
509 class RepoRhodeCodeUi(Base, BaseModel):
509 class RepoRhodeCodeUi(Base, BaseModel):
510 __tablename__ = 'repo_rhodecode_ui'
510 __tablename__ = 'repo_rhodecode_ui'
511 __table_args__ = (
511 __table_args__ = (
512 UniqueConstraint(
512 UniqueConstraint(
513 'repository_id', 'ui_section', 'ui_key',
513 'repository_id', 'ui_section', 'ui_key',
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
515 base_table_args
515 base_table_args
516 )
516 )
517
517
518 repository_id = Column(
518 repository_id = Column(
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
520 nullable=False)
520 nullable=False)
521 ui_id = Column(
521 ui_id = Column(
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
523 primary_key=True)
523 primary_key=True)
524 ui_section = Column(
524 ui_section = Column(
525 "ui_section", String(255), nullable=True, unique=None, default=None)
525 "ui_section", String(255), nullable=True, unique=None, default=None)
526 ui_key = Column(
526 ui_key = Column(
527 "ui_key", String(255), nullable=True, unique=None, default=None)
527 "ui_key", String(255), nullable=True, unique=None, default=None)
528 ui_value = Column(
528 ui_value = Column(
529 "ui_value", String(255), nullable=True, unique=None, default=None)
529 "ui_value", String(255), nullable=True, unique=None, default=None)
530 ui_active = Column(
530 ui_active = Column(
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
532
532
533 repository = relationship('Repository')
533 repository = relationship('Repository')
534
534
535 def __repr__(self):
535 def __repr__(self):
536 return '<%s[%s:%s]%s=>%s]>' % (
536 return '<%s[%s:%s]%s=>%s]>' % (
537 self.__class__.__name__, self.repository.repo_name,
537 self.__class__.__name__, self.repository.repo_name,
538 self.ui_section, self.ui_key, self.ui_value)
538 self.ui_section, self.ui_key, self.ui_value)
539
539
540
540
541 class User(Base, BaseModel):
541 class User(Base, BaseModel):
542 __tablename__ = 'users'
542 __tablename__ = 'users'
543 __table_args__ = (
543 __table_args__ = (
544 UniqueConstraint('username'), UniqueConstraint('email'),
544 UniqueConstraint('username'), UniqueConstraint('email'),
545 Index('u_username_idx', 'username'),
545 Index('u_username_idx', 'username'),
546 Index('u_email_idx', 'email'),
546 Index('u_email_idx', 'email'),
547 base_table_args
547 base_table_args
548 )
548 )
549
549
550 DEFAULT_USER = 'default'
550 DEFAULT_USER = 'default'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
553
553
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
564
564
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
571
571
572 user_log = relationship('UserLog')
572 user_log = relationship('UserLog')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
574
574
575 repositories = relationship('Repository')
575 repositories = relationship('Repository')
576 repository_groups = relationship('RepoGroup')
576 repository_groups = relationship('RepoGroup')
577 user_groups = relationship('UserGroup')
577 user_groups = relationship('UserGroup')
578
578
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
581
581
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
585
585
586 group_member = relationship('UserGroupMember', cascade='all')
586 group_member = relationship('UserGroupMember', cascade='all')
587
587
588 notifications = relationship('UserNotification', cascade='all')
588 notifications = relationship('UserNotification', cascade='all')
589 # notifications assigned to this user
589 # notifications assigned to this user
590 user_created_notifications = relationship('Notification', cascade='all')
590 user_created_notifications = relationship('Notification', cascade='all')
591 # comments created by this user
591 # comments created by this user
592 user_comments = relationship('ChangesetComment', cascade='all')
592 user_comments = relationship('ChangesetComment', cascade='all')
593 # user profile extra info
593 # user profile extra info
594 user_emails = relationship('UserEmailMap', cascade='all')
594 user_emails = relationship('UserEmailMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
598
598
599 # gists
599 # gists
600 user_gists = relationship('Gist', cascade='all')
600 user_gists = relationship('Gist', cascade='all')
601 # user pull requests
601 # user pull requests
602 user_pull_requests = relationship('PullRequest', cascade='all')
602 user_pull_requests = relationship('PullRequest', cascade='all')
603 # external identities
603 # external identities
604 extenal_identities = relationship(
604 extenal_identities = relationship(
605 'ExternalIdentity',
605 'ExternalIdentity',
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
607 cascade='all')
607 cascade='all')
608 # review rules
608 # review rules
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
610
610
611 def __unicode__(self):
611 def __unicode__(self):
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
613 self.user_id, self.username)
613 self.user_id, self.username)
614
614
615 @hybrid_property
615 @hybrid_property
616 def email(self):
616 def email(self):
617 return self._email
617 return self._email
618
618
619 @email.setter
619 @email.setter
620 def email(self, val):
620 def email(self, val):
621 self._email = val.lower() if val else None
621 self._email = val.lower() if val else None
622
622
623 @hybrid_property
623 @hybrid_property
624 def first_name(self):
624 def first_name(self):
625 from rhodecode.lib import helpers as h
625 from rhodecode.lib import helpers as h
626 if self.name:
626 if self.name:
627 return h.escape(self.name)
627 return h.escape(self.name)
628 return self.name
628 return self.name
629
629
630 @hybrid_property
630 @hybrid_property
631 def last_name(self):
631 def last_name(self):
632 from rhodecode.lib import helpers as h
632 from rhodecode.lib import helpers as h
633 if self.lastname:
633 if self.lastname:
634 return h.escape(self.lastname)
634 return h.escape(self.lastname)
635 return self.lastname
635 return self.lastname
636
636
637 @hybrid_property
637 @hybrid_property
638 def api_key(self):
638 def api_key(self):
639 """
639 """
640 Fetch if exist an auth-token with role ALL connected to this user
640 Fetch if exist an auth-token with role ALL connected to this user
641 """
641 """
642 user_auth_token = UserApiKeys.query()\
642 user_auth_token = UserApiKeys.query()\
643 .filter(UserApiKeys.user_id == self.user_id)\
643 .filter(UserApiKeys.user_id == self.user_id)\
644 .filter(or_(UserApiKeys.expires == -1,
644 .filter(or_(UserApiKeys.expires == -1,
645 UserApiKeys.expires >= time.time()))\
645 UserApiKeys.expires >= time.time()))\
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
647 if user_auth_token:
647 if user_auth_token:
648 user_auth_token = user_auth_token.api_key
648 user_auth_token = user_auth_token.api_key
649
649
650 return user_auth_token
650 return user_auth_token
651
651
652 @api_key.setter
652 @api_key.setter
653 def api_key(self, val):
653 def api_key(self, val):
654 # don't allow to set API key this is deprecated for now
654 # don't allow to set API key this is deprecated for now
655 self._api_key = None
655 self._api_key = None
656
656
657 @property
657 @property
658 def reviewer_pull_requests(self):
658 def reviewer_pull_requests(self):
659 return PullRequestReviewers.query() \
659 return PullRequestReviewers.query() \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
662 .all()
662 .all()
663
663
664 @property
664 @property
665 def firstname(self):
665 def firstname(self):
666 # alias for future
666 # alias for future
667 return self.name
667 return self.name
668
668
669 @property
669 @property
670 def emails(self):
670 def emails(self):
671 other = UserEmailMap.query()\
671 other = UserEmailMap.query()\
672 .filter(UserEmailMap.user == self) \
672 .filter(UserEmailMap.user == self) \
673 .order_by(UserEmailMap.email_id.asc()) \
673 .order_by(UserEmailMap.email_id.asc()) \
674 .all()
674 .all()
675 return [self.email] + [x.email for x in other]
675 return [self.email] + [x.email for x in other]
676
676
677 @property
677 @property
678 def auth_tokens(self):
678 def auth_tokens(self):
679 auth_tokens = self.get_auth_tokens()
679 auth_tokens = self.get_auth_tokens()
680 return [x.api_key for x in auth_tokens]
680 return [x.api_key for x in auth_tokens]
681
681
682 def get_auth_tokens(self):
682 def get_auth_tokens(self):
683 return UserApiKeys.query()\
683 return UserApiKeys.query()\
684 .filter(UserApiKeys.user == self)\
684 .filter(UserApiKeys.user == self)\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
686 .all()
686 .all()
687
687
688 @LazyProperty
688 @LazyProperty
689 def feed_token(self):
689 def feed_token(self):
690 return self.get_feed_token()
690 return self.get_feed_token()
691
691
692 def get_feed_token(self, cache=True):
692 def get_feed_token(self, cache=True):
693 feed_tokens = UserApiKeys.query()\
693 feed_tokens = UserApiKeys.query()\
694 .filter(UserApiKeys.user == self)\
694 .filter(UserApiKeys.user == self)\
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
696 if cache:
696 if cache:
697 feed_tokens = feed_tokens.options(
697 feed_tokens = feed_tokens.options(
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
699
699
700 feed_tokens = feed_tokens.all()
700 feed_tokens = feed_tokens.all()
701 if feed_tokens:
701 if feed_tokens:
702 return feed_tokens[0].api_key
702 return feed_tokens[0].api_key
703 return 'NO_FEED_TOKEN_AVAILABLE'
703 return 'NO_FEED_TOKEN_AVAILABLE'
704
704
705 @classmethod
705 @classmethod
706 def get(cls, user_id, cache=False):
706 def get(cls, user_id, cache=False):
707 if not user_id:
707 if not user_id:
708 return
708 return
709
709
710 user = cls.query()
710 user = cls.query()
711 if cache:
711 if cache:
712 user = user.options(
712 user = user.options(
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
714 return user.get(user_id)
714 return user.get(user_id)
715
715
716 @classmethod
716 @classmethod
717 def extra_valid_auth_tokens(cls, user, role=None):
717 def extra_valid_auth_tokens(cls, user, role=None):
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
719 .filter(or_(UserApiKeys.expires == -1,
719 .filter(or_(UserApiKeys.expires == -1,
720 UserApiKeys.expires >= time.time()))
720 UserApiKeys.expires >= time.time()))
721 if role:
721 if role:
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
724 return tokens.all()
724 return tokens.all()
725
725
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
727 from rhodecode.lib import auth
727 from rhodecode.lib import auth
728
728
729 log.debug('Trying to authenticate user: %s via auth-token, '
729 log.debug('Trying to authenticate user: %s via auth-token, '
730 'and roles: %s', self, roles)
730 'and roles: %s', self, roles)
731
731
732 if not auth_token:
732 if not auth_token:
733 return False
733 return False
734
734
735 crypto_backend = auth.crypto_backend()
735 crypto_backend = auth.crypto_backend()
736
736
737 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
737 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
738 tokens_q = UserApiKeys.query()\
738 tokens_q = UserApiKeys.query()\
739 .filter(UserApiKeys.user_id == self.user_id)\
739 .filter(UserApiKeys.user_id == self.user_id)\
740 .filter(or_(UserApiKeys.expires == -1,
740 .filter(or_(UserApiKeys.expires == -1,
741 UserApiKeys.expires >= time.time()))
741 UserApiKeys.expires >= time.time()))
742
742
743 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
743 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
744
744
745 plain_tokens = []
745 plain_tokens = []
746 hash_tokens = []
746 hash_tokens = []
747
747
748 user_tokens = tokens_q.all()
748 user_tokens = tokens_q.all()
749 log.debug('Found %s user tokens to check for authentication', len(user_tokens))
749 log.debug('Found %s user tokens to check for authentication', len(user_tokens))
750 for token in user_tokens:
750 for token in user_tokens:
751 log.debug('AUTH_TOKEN: checking if user token with id `%s` matches',
751 log.debug('AUTH_TOKEN: checking if user token with id `%s` matches',
752 token.user_api_key_id)
752 token.user_api_key_id)
753 # verify scope first, since it's way faster than hash calculation of
753 # verify scope first, since it's way faster than hash calculation of
754 # encrypted tokens
754 # encrypted tokens
755 if token.repo_id:
755 if token.repo_id:
756 # token has a scope, we need to verify it
756 # token has a scope, we need to verify it
757 if scope_repo_id != token.repo_id:
757 if scope_repo_id != token.repo_id:
758 log.debug(
758 log.debug(
759 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
759 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
760 'and calling scope is:%s, skipping further checks',
760 'and calling scope is:%s, skipping further checks',
761 token.repo, scope_repo_id)
761 token.repo, scope_repo_id)
762 # token has a scope, and it doesn't match, skip token
762 # token has a scope, and it doesn't match, skip token
763 continue
763 continue
764
764
765 if token.api_key.startswith(crypto_backend.ENC_PREF):
765 if token.api_key.startswith(crypto_backend.ENC_PREF):
766 hash_tokens.append(token.api_key)
766 hash_tokens.append(token.api_key)
767 else:
767 else:
768 plain_tokens.append(token.api_key)
768 plain_tokens.append(token.api_key)
769
769
770 is_plain_match = auth_token in plain_tokens
770 is_plain_match = auth_token in plain_tokens
771 if is_plain_match:
771 if is_plain_match:
772 return True
772 return True
773
773
774 for hashed in hash_tokens:
774 for hashed in hash_tokens:
775 # NOTE(marcink): this is expensive to calculate, but most secure
775 # NOTE(marcink): this is expensive to calculate, but most secure
776 match = crypto_backend.hash_check(auth_token, hashed)
776 match = crypto_backend.hash_check(auth_token, hashed)
777 if match:
777 if match:
778 return True
778 return True
779
779
780 return False
780 return False
781
781
782 @property
782 @property
783 def ip_addresses(self):
783 def ip_addresses(self):
784 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
784 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
785 return [x.ip_addr for x in ret]
785 return [x.ip_addr for x in ret]
786
786
787 @property
787 @property
788 def username_and_name(self):
788 def username_and_name(self):
789 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
789 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
790
790
791 @property
791 @property
792 def username_or_name_or_email(self):
792 def username_or_name_or_email(self):
793 full_name = self.full_name if self.full_name is not ' ' else None
793 full_name = self.full_name if self.full_name is not ' ' else None
794 return self.username or full_name or self.email
794 return self.username or full_name or self.email
795
795
796 @property
796 @property
797 def full_name(self):
797 def full_name(self):
798 return '%s %s' % (self.first_name, self.last_name)
798 return '%s %s' % (self.first_name, self.last_name)
799
799
800 @property
800 @property
801 def full_name_or_username(self):
801 def full_name_or_username(self):
802 return ('%s %s' % (self.first_name, self.last_name)
802 return ('%s %s' % (self.first_name, self.last_name)
803 if (self.first_name and self.last_name) else self.username)
803 if (self.first_name and self.last_name) else self.username)
804
804
805 @property
805 @property
806 def full_contact(self):
806 def full_contact(self):
807 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
807 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
808
808
809 @property
809 @property
810 def short_contact(self):
810 def short_contact(self):
811 return '%s %s' % (self.first_name, self.last_name)
811 return '%s %s' % (self.first_name, self.last_name)
812
812
813 @property
813 @property
814 def is_admin(self):
814 def is_admin(self):
815 return self.admin
815 return self.admin
816
816
817 def AuthUser(self, **kwargs):
817 def AuthUser(self, **kwargs):
818 """
818 """
819 Returns instance of AuthUser for this user
819 Returns instance of AuthUser for this user
820 """
820 """
821 from rhodecode.lib.auth import AuthUser
821 from rhodecode.lib.auth import AuthUser
822 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
822 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
823
823
824 @hybrid_property
824 @hybrid_property
825 def user_data(self):
825 def user_data(self):
826 if not self._user_data:
826 if not self._user_data:
827 return {}
827 return {}
828
828
829 try:
829 try:
830 return json.loads(self._user_data)
830 return json.loads(self._user_data)
831 except TypeError:
831 except TypeError:
832 return {}
832 return {}
833
833
834 @user_data.setter
834 @user_data.setter
835 def user_data(self, val):
835 def user_data(self, val):
836 if not isinstance(val, dict):
836 if not isinstance(val, dict):
837 raise Exception('user_data must be dict, got %s' % type(val))
837 raise Exception('user_data must be dict, got %s' % type(val))
838 try:
838 try:
839 self._user_data = json.dumps(val)
839 self._user_data = json.dumps(val)
840 except Exception:
840 except Exception:
841 log.error(traceback.format_exc())
841 log.error(traceback.format_exc())
842
842
843 @classmethod
843 @classmethod
844 def get_by_username(cls, username, case_insensitive=False,
844 def get_by_username(cls, username, case_insensitive=False,
845 cache=False, identity_cache=False):
845 cache=False, identity_cache=False):
846 session = Session()
846 session = Session()
847
847
848 if case_insensitive:
848 if case_insensitive:
849 q = cls.query().filter(
849 q = cls.query().filter(
850 func.lower(cls.username) == func.lower(username))
850 func.lower(cls.username) == func.lower(username))
851 else:
851 else:
852 q = cls.query().filter(cls.username == username)
852 q = cls.query().filter(cls.username == username)
853
853
854 if cache:
854 if cache:
855 if identity_cache:
855 if identity_cache:
856 val = cls.identity_cache(session, 'username', username)
856 val = cls.identity_cache(session, 'username', username)
857 if val:
857 if val:
858 return val
858 return val
859 else:
859 else:
860 cache_key = "get_user_by_name_%s" % _hash_key(username)
860 cache_key = "get_user_by_name_%s" % _hash_key(username)
861 q = q.options(
861 q = q.options(
862 FromCache("sql_cache_short", cache_key))
862 FromCache("sql_cache_short", cache_key))
863
863
864 return q.scalar()
864 return q.scalar()
865
865
866 @classmethod
866 @classmethod
867 def get_by_auth_token(cls, auth_token, cache=False):
867 def get_by_auth_token(cls, auth_token, cache=False):
868 q = UserApiKeys.query()\
868 q = UserApiKeys.query()\
869 .filter(UserApiKeys.api_key == auth_token)\
869 .filter(UserApiKeys.api_key == auth_token)\
870 .filter(or_(UserApiKeys.expires == -1,
870 .filter(or_(UserApiKeys.expires == -1,
871 UserApiKeys.expires >= time.time()))
871 UserApiKeys.expires >= time.time()))
872 if cache:
872 if cache:
873 q = q.options(
873 q = q.options(
874 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
874 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
875
875
876 match = q.first()
876 match = q.first()
877 if match:
877 if match:
878 return match.user
878 return match.user
879
879
880 @classmethod
880 @classmethod
881 def get_by_email(cls, email, case_insensitive=False, cache=False):
881 def get_by_email(cls, email, case_insensitive=False, cache=False):
882
882
883 if case_insensitive:
883 if case_insensitive:
884 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
884 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
885
885
886 else:
886 else:
887 q = cls.query().filter(cls.email == email)
887 q = cls.query().filter(cls.email == email)
888
888
889 email_key = _hash_key(email)
889 email_key = _hash_key(email)
890 if cache:
890 if cache:
891 q = q.options(
891 q = q.options(
892 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
892 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
893
893
894 ret = q.scalar()
894 ret = q.scalar()
895 if ret is None:
895 if ret is None:
896 q = UserEmailMap.query()
896 q = UserEmailMap.query()
897 # try fetching in alternate email map
897 # try fetching in alternate email map
898 if case_insensitive:
898 if case_insensitive:
899 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
899 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
900 else:
900 else:
901 q = q.filter(UserEmailMap.email == email)
901 q = q.filter(UserEmailMap.email == email)
902 q = q.options(joinedload(UserEmailMap.user))
902 q = q.options(joinedload(UserEmailMap.user))
903 if cache:
903 if cache:
904 q = q.options(
904 q = q.options(
905 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
905 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
906 ret = getattr(q.scalar(), 'user', None)
906 ret = getattr(q.scalar(), 'user', None)
907
907
908 return ret
908 return ret
909
909
910 @classmethod
910 @classmethod
911 def get_from_cs_author(cls, author):
911 def get_from_cs_author(cls, author):
912 """
912 """
913 Tries to get User objects out of commit author string
913 Tries to get User objects out of commit author string
914
914
915 :param author:
915 :param author:
916 """
916 """
917 from rhodecode.lib.helpers import email, author_name
917 from rhodecode.lib.helpers import email, author_name
918 # Valid email in the attribute passed, see if they're in the system
918 # Valid email in the attribute passed, see if they're in the system
919 _email = email(author)
919 _email = email(author)
920 if _email:
920 if _email:
921 user = cls.get_by_email(_email, case_insensitive=True)
921 user = cls.get_by_email(_email, case_insensitive=True)
922 if user:
922 if user:
923 return user
923 return user
924 # Maybe we can match by username?
924 # Maybe we can match by username?
925 _author = author_name(author)
925 _author = author_name(author)
926 user = cls.get_by_username(_author, case_insensitive=True)
926 user = cls.get_by_username(_author, case_insensitive=True)
927 if user:
927 if user:
928 return user
928 return user
929
929
930 def update_userdata(self, **kwargs):
930 def update_userdata(self, **kwargs):
931 usr = self
931 usr = self
932 old = usr.user_data
932 old = usr.user_data
933 old.update(**kwargs)
933 old.update(**kwargs)
934 usr.user_data = old
934 usr.user_data = old
935 Session().add(usr)
935 Session().add(usr)
936 log.debug('updated userdata with ', kwargs)
936 log.debug('updated userdata with ', kwargs)
937
937
938 def update_lastlogin(self):
938 def update_lastlogin(self):
939 """Update user lastlogin"""
939 """Update user lastlogin"""
940 self.last_login = datetime.datetime.now()
940 self.last_login = datetime.datetime.now()
941 Session().add(self)
941 Session().add(self)
942 log.debug('updated user %s lastlogin', self.username)
942 log.debug('updated user %s lastlogin', self.username)
943
943
944 def update_password(self, new_password):
944 def update_password(self, new_password):
945 from rhodecode.lib.auth import get_crypt_password
945 from rhodecode.lib.auth import get_crypt_password
946
946
947 self.password = get_crypt_password(new_password)
947 self.password = get_crypt_password(new_password)
948 Session().add(self)
948 Session().add(self)
949
949
950 @classmethod
950 @classmethod
951 def get_first_super_admin(cls):
951 def get_first_super_admin(cls):
952 user = User.query()\
952 user = User.query()\
953 .filter(User.admin == true()) \
953 .filter(User.admin == true()) \
954 .order_by(User.user_id.asc()) \
954 .order_by(User.user_id.asc()) \
955 .first()
955 .first()
956
956
957 if user is None:
957 if user is None:
958 raise Exception('FATAL: Missing administrative account!')
958 raise Exception('FATAL: Missing administrative account!')
959 return user
959 return user
960
960
961 @classmethod
961 @classmethod
962 def get_all_super_admins(cls):
962 def get_all_super_admins(cls):
963 """
963 """
964 Returns all admin accounts sorted by username
964 Returns all admin accounts sorted by username
965 """
965 """
966 return User.query().filter(User.admin == true())\
966 return User.query().filter(User.admin == true())\
967 .order_by(User.username.asc()).all()
967 .order_by(User.username.asc()).all()
968
968
969 @classmethod
969 @classmethod
970 def get_default_user(cls, cache=False, refresh=False):
970 def get_default_user(cls, cache=False, refresh=False):
971 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
971 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
972 if user is None:
972 if user is None:
973 raise Exception('FATAL: Missing default account!')
973 raise Exception('FATAL: Missing default account!')
974 if refresh:
974 if refresh:
975 # The default user might be based on outdated state which
975 # The default user might be based on outdated state which
976 # has been loaded from the cache.
976 # has been loaded from the cache.
977 # A call to refresh() ensures that the
977 # A call to refresh() ensures that the
978 # latest state from the database is used.
978 # latest state from the database is used.
979 Session().refresh(user)
979 Session().refresh(user)
980 return user
980 return user
981
981
982 def _get_default_perms(self, user, suffix=''):
982 def _get_default_perms(self, user, suffix=''):
983 from rhodecode.model.permission import PermissionModel
983 from rhodecode.model.permission import PermissionModel
984 return PermissionModel().get_default_perms(user.user_perms, suffix)
984 return PermissionModel().get_default_perms(user.user_perms, suffix)
985
985
986 def get_default_perms(self, suffix=''):
986 def get_default_perms(self, suffix=''):
987 return self._get_default_perms(self, suffix)
987 return self._get_default_perms(self, suffix)
988
988
989 def get_api_data(self, include_secrets=False, details='full'):
989 def get_api_data(self, include_secrets=False, details='full'):
990 """
990 """
991 Common function for generating user related data for API
991 Common function for generating user related data for API
992
992
993 :param include_secrets: By default secrets in the API data will be replaced
993 :param include_secrets: By default secrets in the API data will be replaced
994 by a placeholder value to prevent exposing this data by accident. In case
994 by a placeholder value to prevent exposing this data by accident. In case
995 this data shall be exposed, set this flag to ``True``.
995 this data shall be exposed, set this flag to ``True``.
996
996
997 :param details: details can be 'basic|full' basic gives only a subset of
997 :param details: details can be 'basic|full' basic gives only a subset of
998 the available user information that includes user_id, name and emails.
998 the available user information that includes user_id, name and emails.
999 """
999 """
1000 user = self
1000 user = self
1001 user_data = self.user_data
1001 user_data = self.user_data
1002 data = {
1002 data = {
1003 'user_id': user.user_id,
1003 'user_id': user.user_id,
1004 'username': user.username,
1004 'username': user.username,
1005 'firstname': user.name,
1005 'firstname': user.name,
1006 'lastname': user.lastname,
1006 'lastname': user.lastname,
1007 'email': user.email,
1007 'email': user.email,
1008 'emails': user.emails,
1008 'emails': user.emails,
1009 }
1009 }
1010 if details == 'basic':
1010 if details == 'basic':
1011 return data
1011 return data
1012
1012
1013 auth_token_length = 40
1013 auth_token_length = 40
1014 auth_token_replacement = '*' * auth_token_length
1014 auth_token_replacement = '*' * auth_token_length
1015
1015
1016 extras = {
1016 extras = {
1017 'auth_tokens': [auth_token_replacement],
1017 'auth_tokens': [auth_token_replacement],
1018 'active': user.active,
1018 'active': user.active,
1019 'admin': user.admin,
1019 'admin': user.admin,
1020 'extern_type': user.extern_type,
1020 'extern_type': user.extern_type,
1021 'extern_name': user.extern_name,
1021 'extern_name': user.extern_name,
1022 'last_login': user.last_login,
1022 'last_login': user.last_login,
1023 'last_activity': user.last_activity,
1023 'last_activity': user.last_activity,
1024 'ip_addresses': user.ip_addresses,
1024 'ip_addresses': user.ip_addresses,
1025 'language': user_data.get('language')
1025 'language': user_data.get('language')
1026 }
1026 }
1027 data.update(extras)
1027 data.update(extras)
1028
1028
1029 if include_secrets:
1029 if include_secrets:
1030 data['auth_tokens'] = user.auth_tokens
1030 data['auth_tokens'] = user.auth_tokens
1031 return data
1031 return data
1032
1032
1033 def __json__(self):
1033 def __json__(self):
1034 data = {
1034 data = {
1035 'full_name': self.full_name,
1035 'full_name': self.full_name,
1036 'full_name_or_username': self.full_name_or_username,
1036 'full_name_or_username': self.full_name_or_username,
1037 'short_contact': self.short_contact,
1037 'short_contact': self.short_contact,
1038 'full_contact': self.full_contact,
1038 'full_contact': self.full_contact,
1039 }
1039 }
1040 data.update(self.get_api_data())
1040 data.update(self.get_api_data())
1041 return data
1041 return data
1042
1042
1043
1043
1044 class UserApiKeys(Base, BaseModel):
1044 class UserApiKeys(Base, BaseModel):
1045 __tablename__ = 'user_api_keys'
1045 __tablename__ = 'user_api_keys'
1046 __table_args__ = (
1046 __table_args__ = (
1047 Index('uak_api_key_idx', 'api_key', unique=True),
1047 Index('uak_api_key_idx', 'api_key', unique=True),
1048 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1048 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1049 base_table_args
1049 base_table_args
1050 )
1050 )
1051 __mapper_args__ = {}
1051 __mapper_args__ = {}
1052
1052
1053 # ApiKey role
1053 # ApiKey role
1054 ROLE_ALL = 'token_role_all'
1054 ROLE_ALL = 'token_role_all'
1055 ROLE_HTTP = 'token_role_http'
1055 ROLE_HTTP = 'token_role_http'
1056 ROLE_VCS = 'token_role_vcs'
1056 ROLE_VCS = 'token_role_vcs'
1057 ROLE_API = 'token_role_api'
1057 ROLE_API = 'token_role_api'
1058 ROLE_FEED = 'token_role_feed'
1058 ROLE_FEED = 'token_role_feed'
1059 ROLE_PASSWORD_RESET = 'token_password_reset'
1059 ROLE_PASSWORD_RESET = 'token_password_reset'
1060
1060
1061 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1061 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1062
1062
1063 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1063 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1064 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1064 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1065 api_key = Column("api_key", String(255), nullable=False, unique=True)
1065 api_key = Column("api_key", String(255), nullable=False, unique=True)
1066 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1066 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1067 expires = Column('expires', Float(53), nullable=False)
1067 expires = Column('expires', Float(53), nullable=False)
1068 role = Column('role', String(255), nullable=True)
1068 role = Column('role', String(255), nullable=True)
1069 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1069 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1070
1070
1071 # scope columns
1071 # scope columns
1072 repo_id = Column(
1072 repo_id = Column(
1073 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1073 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1074 nullable=True, unique=None, default=None)
1074 nullable=True, unique=None, default=None)
1075 repo = relationship('Repository', lazy='joined')
1075 repo = relationship('Repository', lazy='joined')
1076
1076
1077 repo_group_id = Column(
1077 repo_group_id = Column(
1078 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1078 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1079 nullable=True, unique=None, default=None)
1079 nullable=True, unique=None, default=None)
1080 repo_group = relationship('RepoGroup', lazy='joined')
1080 repo_group = relationship('RepoGroup', lazy='joined')
1081
1081
1082 user = relationship('User', lazy='joined')
1082 user = relationship('User', lazy='joined')
1083
1083
1084 def __unicode__(self):
1084 def __unicode__(self):
1085 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1085 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1086
1086
1087 def __json__(self):
1087 def __json__(self):
1088 data = {
1088 data = {
1089 'auth_token': self.api_key,
1089 'auth_token': self.api_key,
1090 'role': self.role,
1090 'role': self.role,
1091 'scope': self.scope_humanized,
1091 'scope': self.scope_humanized,
1092 'expired': self.expired
1092 'expired': self.expired
1093 }
1093 }
1094 return data
1094 return data
1095
1095
1096 def get_api_data(self, include_secrets=False):
1096 def get_api_data(self, include_secrets=False):
1097 data = self.__json__()
1097 data = self.__json__()
1098 if include_secrets:
1098 if include_secrets:
1099 return data
1099 return data
1100 else:
1100 else:
1101 data['auth_token'] = self.token_obfuscated
1101 data['auth_token'] = self.token_obfuscated
1102 return data
1102 return data
1103
1103
1104 @hybrid_property
1104 @hybrid_property
1105 def description_safe(self):
1105 def description_safe(self):
1106 from rhodecode.lib import helpers as h
1106 from rhodecode.lib import helpers as h
1107 return h.escape(self.description)
1107 return h.escape(self.description)
1108
1108
1109 @property
1109 @property
1110 def expired(self):
1110 def expired(self):
1111 if self.expires == -1:
1111 if self.expires == -1:
1112 return False
1112 return False
1113 return time.time() > self.expires
1113 return time.time() > self.expires
1114
1114
1115 @classmethod
1115 @classmethod
1116 def _get_role_name(cls, role):
1116 def _get_role_name(cls, role):
1117 return {
1117 return {
1118 cls.ROLE_ALL: _('all'),
1118 cls.ROLE_ALL: _('all'),
1119 cls.ROLE_HTTP: _('http/web interface'),
1119 cls.ROLE_HTTP: _('http/web interface'),
1120 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1120 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1121 cls.ROLE_API: _('api calls'),
1121 cls.ROLE_API: _('api calls'),
1122 cls.ROLE_FEED: _('feed access'),
1122 cls.ROLE_FEED: _('feed access'),
1123 }.get(role, role)
1123 }.get(role, role)
1124
1124
1125 @property
1125 @property
1126 def role_humanized(self):
1126 def role_humanized(self):
1127 return self._get_role_name(self.role)
1127 return self._get_role_name(self.role)
1128
1128
1129 def _get_scope(self):
1129 def _get_scope(self):
1130 if self.repo:
1130 if self.repo:
1131 return repr(self.repo)
1131 return repr(self.repo)
1132 if self.repo_group:
1132 if self.repo_group:
1133 return repr(self.repo_group) + ' (recursive)'
1133 return repr(self.repo_group) + ' (recursive)'
1134 return 'global'
1134 return 'global'
1135
1135
1136 @property
1136 @property
1137 def scope_humanized(self):
1137 def scope_humanized(self):
1138 return self._get_scope()
1138 return self._get_scope()
1139
1139
1140 @property
1140 @property
1141 def token_obfuscated(self):
1141 def token_obfuscated(self):
1142 if self.api_key:
1142 if self.api_key:
1143 return self.api_key[:4] + "****"
1143 return self.api_key[:4] + "****"
1144
1144
1145
1145
1146 class UserEmailMap(Base, BaseModel):
1146 class UserEmailMap(Base, BaseModel):
1147 __tablename__ = 'user_email_map'
1147 __tablename__ = 'user_email_map'
1148 __table_args__ = (
1148 __table_args__ = (
1149 Index('uem_email_idx', 'email'),
1149 Index('uem_email_idx', 'email'),
1150 UniqueConstraint('email'),
1150 UniqueConstraint('email'),
1151 base_table_args
1151 base_table_args
1152 )
1152 )
1153 __mapper_args__ = {}
1153 __mapper_args__ = {}
1154
1154
1155 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1155 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1156 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1156 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1157 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1157 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1158 user = relationship('User', lazy='joined')
1158 user = relationship('User', lazy='joined')
1159
1159
1160 @validates('_email')
1160 @validates('_email')
1161 def validate_email(self, key, email):
1161 def validate_email(self, key, email):
1162 # check if this email is not main one
1162 # check if this email is not main one
1163 main_email = Session().query(User).filter(User.email == email).scalar()
1163 main_email = Session().query(User).filter(User.email == email).scalar()
1164 if main_email is not None:
1164 if main_email is not None:
1165 raise AttributeError('email %s is present is user table' % email)
1165 raise AttributeError('email %s is present is user table' % email)
1166 return email
1166 return email
1167
1167
1168 @hybrid_property
1168 @hybrid_property
1169 def email(self):
1169 def email(self):
1170 return self._email
1170 return self._email
1171
1171
1172 @email.setter
1172 @email.setter
1173 def email(self, val):
1173 def email(self, val):
1174 self._email = val.lower() if val else None
1174 self._email = val.lower() if val else None
1175
1175
1176
1176
1177 class UserIpMap(Base, BaseModel):
1177 class UserIpMap(Base, BaseModel):
1178 __tablename__ = 'user_ip_map'
1178 __tablename__ = 'user_ip_map'
1179 __table_args__ = (
1179 __table_args__ = (
1180 UniqueConstraint('user_id', 'ip_addr'),
1180 UniqueConstraint('user_id', 'ip_addr'),
1181 base_table_args
1181 base_table_args
1182 )
1182 )
1183 __mapper_args__ = {}
1183 __mapper_args__ = {}
1184
1184
1185 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1185 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1186 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1186 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1187 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1187 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1188 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1188 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1189 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1189 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1190 user = relationship('User', lazy='joined')
1190 user = relationship('User', lazy='joined')
1191
1191
1192 @hybrid_property
1192 @hybrid_property
1193 def description_safe(self):
1193 def description_safe(self):
1194 from rhodecode.lib import helpers as h
1194 from rhodecode.lib import helpers as h
1195 return h.escape(self.description)
1195 return h.escape(self.description)
1196
1196
1197 @classmethod
1197 @classmethod
1198 def _get_ip_range(cls, ip_addr):
1198 def _get_ip_range(cls, ip_addr):
1199 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1199 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1200 return [str(net.network_address), str(net.broadcast_address)]
1200 return [str(net.network_address), str(net.broadcast_address)]
1201
1201
1202 def __json__(self):
1202 def __json__(self):
1203 return {
1203 return {
1204 'ip_addr': self.ip_addr,
1204 'ip_addr': self.ip_addr,
1205 'ip_range': self._get_ip_range(self.ip_addr),
1205 'ip_range': self._get_ip_range(self.ip_addr),
1206 }
1206 }
1207
1207
1208 def __unicode__(self):
1208 def __unicode__(self):
1209 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1209 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1210 self.user_id, self.ip_addr)
1210 self.user_id, self.ip_addr)
1211
1211
1212
1212
1213 class UserSshKeys(Base, BaseModel):
1213 class UserSshKeys(Base, BaseModel):
1214 __tablename__ = 'user_ssh_keys'
1214 __tablename__ = 'user_ssh_keys'
1215 __table_args__ = (
1215 __table_args__ = (
1216 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1216 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1217
1217
1218 UniqueConstraint('ssh_key_fingerprint'),
1218 UniqueConstraint('ssh_key_fingerprint'),
1219
1219
1220 base_table_args
1220 base_table_args
1221 )
1221 )
1222 __mapper_args__ = {}
1222 __mapper_args__ = {}
1223
1223
1224 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1224 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1225 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1225 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1226 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1226 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1227
1227
1228 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1228 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1229
1229
1230 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1230 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1231 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1231 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1232 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1232 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1233
1233
1234 user = relationship('User', lazy='joined')
1234 user = relationship('User', lazy='joined')
1235
1235
1236 def __json__(self):
1236 def __json__(self):
1237 data = {
1237 data = {
1238 'ssh_fingerprint': self.ssh_key_fingerprint,
1238 'ssh_fingerprint': self.ssh_key_fingerprint,
1239 'description': self.description,
1239 'description': self.description,
1240 'created_on': self.created_on
1240 'created_on': self.created_on
1241 }
1241 }
1242 return data
1242 return data
1243
1243
1244 def get_api_data(self):
1244 def get_api_data(self):
1245 data = self.__json__()
1245 data = self.__json__()
1246 return data
1246 return data
1247
1247
1248
1248
1249 class UserLog(Base, BaseModel):
1249 class UserLog(Base, BaseModel):
1250 __tablename__ = 'user_logs'
1250 __tablename__ = 'user_logs'
1251 __table_args__ = (
1251 __table_args__ = (
1252 base_table_args,
1252 base_table_args,
1253 )
1253 )
1254
1254
1255 VERSION_1 = 'v1'
1255 VERSION_1 = 'v1'
1256 VERSION_2 = 'v2'
1256 VERSION_2 = 'v2'
1257 VERSIONS = [VERSION_1, VERSION_2]
1257 VERSIONS = [VERSION_1, VERSION_2]
1258
1258
1259 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1259 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1260 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1260 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1261 username = Column("username", String(255), nullable=True, unique=None, default=None)
1261 username = Column("username", String(255), nullable=True, unique=None, default=None)
1262 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1262 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1263 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1263 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1264 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1264 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1265 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1265 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1266 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1266 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1267
1267
1268 version = Column("version", String(255), nullable=True, default=VERSION_1)
1268 version = Column("version", String(255), nullable=True, default=VERSION_1)
1269 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1269 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1270 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1270 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1271
1271
1272 def __unicode__(self):
1272 def __unicode__(self):
1273 return u"<%s('id:%s:%s')>" % (
1273 return u"<%s('id:%s:%s')>" % (
1274 self.__class__.__name__, self.repository_name, self.action)
1274 self.__class__.__name__, self.repository_name, self.action)
1275
1275
1276 def __json__(self):
1276 def __json__(self):
1277 return {
1277 return {
1278 'user_id': self.user_id,
1278 'user_id': self.user_id,
1279 'username': self.username,
1279 'username': self.username,
1280 'repository_id': self.repository_id,
1280 'repository_id': self.repository_id,
1281 'repository_name': self.repository_name,
1281 'repository_name': self.repository_name,
1282 'user_ip': self.user_ip,
1282 'user_ip': self.user_ip,
1283 'action_date': self.action_date,
1283 'action_date': self.action_date,
1284 'action': self.action,
1284 'action': self.action,
1285 }
1285 }
1286
1286
1287 @hybrid_property
1287 @hybrid_property
1288 def entry_id(self):
1288 def entry_id(self):
1289 return self.user_log_id
1289 return self.user_log_id
1290
1290
1291 @property
1291 @property
1292 def action_as_day(self):
1292 def action_as_day(self):
1293 return datetime.date(*self.action_date.timetuple()[:3])
1293 return datetime.date(*self.action_date.timetuple()[:3])
1294
1294
1295 user = relationship('User')
1295 user = relationship('User')
1296 repository = relationship('Repository', cascade='')
1296 repository = relationship('Repository', cascade='')
1297
1297
1298
1298
1299 class UserGroup(Base, BaseModel):
1299 class UserGroup(Base, BaseModel):
1300 __tablename__ = 'users_groups'
1300 __tablename__ = 'users_groups'
1301 __table_args__ = (
1301 __table_args__ = (
1302 base_table_args,
1302 base_table_args,
1303 )
1303 )
1304
1304
1305 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1305 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1306 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1306 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1307 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1307 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1308 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1308 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1309 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1309 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1310 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1310 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1311 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1311 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1312 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1312 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1313
1313
1314 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1314 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1315 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1315 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1316 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1316 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1317 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1317 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1318 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1318 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1319 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1319 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1320
1320
1321 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1321 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1322 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1322 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1323
1323
1324 @classmethod
1324 @classmethod
1325 def _load_group_data(cls, column):
1325 def _load_group_data(cls, column):
1326 if not column:
1326 if not column:
1327 return {}
1327 return {}
1328
1328
1329 try:
1329 try:
1330 return json.loads(column) or {}
1330 return json.loads(column) or {}
1331 except TypeError:
1331 except TypeError:
1332 return {}
1332 return {}
1333
1333
1334 @hybrid_property
1334 @hybrid_property
1335 def description_safe(self):
1335 def description_safe(self):
1336 from rhodecode.lib import helpers as h
1336 from rhodecode.lib import helpers as h
1337 return h.escape(self.user_group_description)
1337 return h.escape(self.user_group_description)
1338
1338
1339 @hybrid_property
1339 @hybrid_property
1340 def group_data(self):
1340 def group_data(self):
1341 return self._load_group_data(self._group_data)
1341 return self._load_group_data(self._group_data)
1342
1342
1343 @group_data.expression
1343 @group_data.expression
1344 def group_data(self, **kwargs):
1344 def group_data(self, **kwargs):
1345 return self._group_data
1345 return self._group_data
1346
1346
1347 @group_data.setter
1347 @group_data.setter
1348 def group_data(self, val):
1348 def group_data(self, val):
1349 try:
1349 try:
1350 self._group_data = json.dumps(val)
1350 self._group_data = json.dumps(val)
1351 except Exception:
1351 except Exception:
1352 log.error(traceback.format_exc())
1352 log.error(traceback.format_exc())
1353
1353
1354 @classmethod
1354 @classmethod
1355 def _load_sync(cls, group_data):
1355 def _load_sync(cls, group_data):
1356 if group_data:
1356 if group_data:
1357 return group_data.get('extern_type')
1357 return group_data.get('extern_type')
1358
1358
1359 @property
1359 @property
1360 def sync(self):
1360 def sync(self):
1361 return self._load_sync(self.group_data)
1361 return self._load_sync(self.group_data)
1362
1362
1363 def __unicode__(self):
1363 def __unicode__(self):
1364 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1364 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1365 self.users_group_id,
1365 self.users_group_id,
1366 self.users_group_name)
1366 self.users_group_name)
1367
1367
1368 @classmethod
1368 @classmethod
1369 def get_by_group_name(cls, group_name, cache=False,
1369 def get_by_group_name(cls, group_name, cache=False,
1370 case_insensitive=False):
1370 case_insensitive=False):
1371 if case_insensitive:
1371 if case_insensitive:
1372 q = cls.query().filter(func.lower(cls.users_group_name) ==
1372 q = cls.query().filter(func.lower(cls.users_group_name) ==
1373 func.lower(group_name))
1373 func.lower(group_name))
1374
1374
1375 else:
1375 else:
1376 q = cls.query().filter(cls.users_group_name == group_name)
1376 q = cls.query().filter(cls.users_group_name == group_name)
1377 if cache:
1377 if cache:
1378 q = q.options(
1378 q = q.options(
1379 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1379 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1380 return q.scalar()
1380 return q.scalar()
1381
1381
1382 @classmethod
1382 @classmethod
1383 def get(cls, user_group_id, cache=False):
1383 def get(cls, user_group_id, cache=False):
1384 if not user_group_id:
1384 if not user_group_id:
1385 return
1385 return
1386
1386
1387 user_group = cls.query()
1387 user_group = cls.query()
1388 if cache:
1388 if cache:
1389 user_group = user_group.options(
1389 user_group = user_group.options(
1390 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1390 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1391 return user_group.get(user_group_id)
1391 return user_group.get(user_group_id)
1392
1392
1393 def permissions(self, with_admins=True, with_owner=True):
1393 def permissions(self, with_admins=True, with_owner=True):
1394 """
1394 """
1395 Permissions for user groups
1395 Permissions for user groups
1396 """
1396 """
1397 _admin_perm = 'usergroup.admin'
1397 _admin_perm = 'usergroup.admin'
1398
1398
1399 owner_row = []
1399 owner_row = []
1400 if with_owner:
1400 if with_owner:
1401 usr = AttributeDict(self.user.get_dict())
1401 usr = AttributeDict(self.user.get_dict())
1402 usr.owner_row = True
1402 usr.owner_row = True
1403 usr.permission = _admin_perm
1403 usr.permission = _admin_perm
1404 owner_row.append(usr)
1404 owner_row.append(usr)
1405
1405
1406 super_admin_ids = []
1406 super_admin_ids = []
1407 super_admin_rows = []
1407 super_admin_rows = []
1408 if with_admins:
1408 if with_admins:
1409 for usr in User.get_all_super_admins():
1409 for usr in User.get_all_super_admins():
1410 super_admin_ids.append(usr.user_id)
1410 super_admin_ids.append(usr.user_id)
1411 # if this admin is also owner, don't double the record
1411 # if this admin is also owner, don't double the record
1412 if usr.user_id == owner_row[0].user_id:
1412 if usr.user_id == owner_row[0].user_id:
1413 owner_row[0].admin_row = True
1413 owner_row[0].admin_row = True
1414 else:
1414 else:
1415 usr = AttributeDict(usr.get_dict())
1415 usr = AttributeDict(usr.get_dict())
1416 usr.admin_row = True
1416 usr.admin_row = True
1417 usr.permission = _admin_perm
1417 usr.permission = _admin_perm
1418 super_admin_rows.append(usr)
1418 super_admin_rows.append(usr)
1419
1419
1420 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1420 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1421 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1421 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1422 joinedload(UserUserGroupToPerm.user),
1422 joinedload(UserUserGroupToPerm.user),
1423 joinedload(UserUserGroupToPerm.permission),)
1423 joinedload(UserUserGroupToPerm.permission),)
1424
1424
1425 # get owners and admins and permissions. We do a trick of re-writing
1425 # get owners and admins and permissions. We do a trick of re-writing
1426 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1426 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1427 # has a global reference and changing one object propagates to all
1427 # has a global reference and changing one object propagates to all
1428 # others. This means if admin is also an owner admin_row that change
1428 # others. This means if admin is also an owner admin_row that change
1429 # would propagate to both objects
1429 # would propagate to both objects
1430 perm_rows = []
1430 perm_rows = []
1431 for _usr in q.all():
1431 for _usr in q.all():
1432 usr = AttributeDict(_usr.user.get_dict())
1432 usr = AttributeDict(_usr.user.get_dict())
1433 # if this user is also owner/admin, mark as duplicate record
1433 # if this user is also owner/admin, mark as duplicate record
1434 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1434 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1435 usr.duplicate_perm = True
1435 usr.duplicate_perm = True
1436 usr.permission = _usr.permission.permission_name
1436 usr.permission = _usr.permission.permission_name
1437 perm_rows.append(usr)
1437 perm_rows.append(usr)
1438
1438
1439 # filter the perm rows by 'default' first and then sort them by
1439 # filter the perm rows by 'default' first and then sort them by
1440 # admin,write,read,none permissions sorted again alphabetically in
1440 # admin,write,read,none permissions sorted again alphabetically in
1441 # each group
1441 # each group
1442 perm_rows = sorted(perm_rows, key=display_user_sort)
1442 perm_rows = sorted(perm_rows, key=display_user_sort)
1443
1443
1444 return super_admin_rows + owner_row + perm_rows
1444 return super_admin_rows + owner_row + perm_rows
1445
1445
1446 def permission_user_groups(self):
1446 def permission_user_groups(self):
1447 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1447 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1448 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1448 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1449 joinedload(UserGroupUserGroupToPerm.target_user_group),
1449 joinedload(UserGroupUserGroupToPerm.target_user_group),
1450 joinedload(UserGroupUserGroupToPerm.permission),)
1450 joinedload(UserGroupUserGroupToPerm.permission),)
1451
1451
1452 perm_rows = []
1452 perm_rows = []
1453 for _user_group in q.all():
1453 for _user_group in q.all():
1454 usr = AttributeDict(_user_group.user_group.get_dict())
1454 usr = AttributeDict(_user_group.user_group.get_dict())
1455 usr.permission = _user_group.permission.permission_name
1455 usr.permission = _user_group.permission.permission_name
1456 perm_rows.append(usr)
1456 perm_rows.append(usr)
1457
1457
1458 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1458 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1459 return perm_rows
1459 return perm_rows
1460
1460
1461 def _get_default_perms(self, user_group, suffix=''):
1461 def _get_default_perms(self, user_group, suffix=''):
1462 from rhodecode.model.permission import PermissionModel
1462 from rhodecode.model.permission import PermissionModel
1463 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1463 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1464
1464
1465 def get_default_perms(self, suffix=''):
1465 def get_default_perms(self, suffix=''):
1466 return self._get_default_perms(self, suffix)
1466 return self._get_default_perms(self, suffix)
1467
1467
1468 def get_api_data(self, with_group_members=True, include_secrets=False):
1468 def get_api_data(self, with_group_members=True, include_secrets=False):
1469 """
1469 """
1470 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1470 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1471 basically forwarded.
1471 basically forwarded.
1472
1472
1473 """
1473 """
1474 user_group = self
1474 user_group = self
1475 data = {
1475 data = {
1476 'users_group_id': user_group.users_group_id,
1476 'users_group_id': user_group.users_group_id,
1477 'group_name': user_group.users_group_name,
1477 'group_name': user_group.users_group_name,
1478 'group_description': user_group.user_group_description,
1478 'group_description': user_group.user_group_description,
1479 'active': user_group.users_group_active,
1479 'active': user_group.users_group_active,
1480 'owner': user_group.user.username,
1480 'owner': user_group.user.username,
1481 'sync': user_group.sync,
1481 'sync': user_group.sync,
1482 'owner_email': user_group.user.email,
1482 'owner_email': user_group.user.email,
1483 }
1483 }
1484
1484
1485 if with_group_members:
1485 if with_group_members:
1486 users = []
1486 users = []
1487 for user in user_group.members:
1487 for user in user_group.members:
1488 user = user.user
1488 user = user.user
1489 users.append(user.get_api_data(include_secrets=include_secrets))
1489 users.append(user.get_api_data(include_secrets=include_secrets))
1490 data['users'] = users
1490 data['users'] = users
1491
1491
1492 return data
1492 return data
1493
1493
1494
1494
1495 class UserGroupMember(Base, BaseModel):
1495 class UserGroupMember(Base, BaseModel):
1496 __tablename__ = 'users_groups_members'
1496 __tablename__ = 'users_groups_members'
1497 __table_args__ = (
1497 __table_args__ = (
1498 base_table_args,
1498 base_table_args,
1499 )
1499 )
1500
1500
1501 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1501 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1502 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1502 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1503 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1503 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1504
1504
1505 user = relationship('User', lazy='joined')
1505 user = relationship('User', lazy='joined')
1506 users_group = relationship('UserGroup')
1506 users_group = relationship('UserGroup')
1507
1507
1508 def __init__(self, gr_id='', u_id=''):
1508 def __init__(self, gr_id='', u_id=''):
1509 self.users_group_id = gr_id
1509 self.users_group_id = gr_id
1510 self.user_id = u_id
1510 self.user_id = u_id
1511
1511
1512
1512
1513 class RepositoryField(Base, BaseModel):
1513 class RepositoryField(Base, BaseModel):
1514 __tablename__ = 'repositories_fields'
1514 __tablename__ = 'repositories_fields'
1515 __table_args__ = (
1515 __table_args__ = (
1516 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1516 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1517 base_table_args,
1517 base_table_args,
1518 )
1518 )
1519
1519
1520 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1520 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1521
1521
1522 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1522 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1523 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1523 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1524 field_key = Column("field_key", String(250))
1524 field_key = Column("field_key", String(250))
1525 field_label = Column("field_label", String(1024), nullable=False)
1525 field_label = Column("field_label", String(1024), nullable=False)
1526 field_value = Column("field_value", String(10000), nullable=False)
1526 field_value = Column("field_value", String(10000), nullable=False)
1527 field_desc = Column("field_desc", String(1024), nullable=False)
1527 field_desc = Column("field_desc", String(1024), nullable=False)
1528 field_type = Column("field_type", String(255), nullable=False, unique=None)
1528 field_type = Column("field_type", String(255), nullable=False, unique=None)
1529 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1529 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1530
1530
1531 repository = relationship('Repository')
1531 repository = relationship('Repository')
1532
1532
1533 @property
1533 @property
1534 def field_key_prefixed(self):
1534 def field_key_prefixed(self):
1535 return 'ex_%s' % self.field_key
1535 return 'ex_%s' % self.field_key
1536
1536
1537 @classmethod
1537 @classmethod
1538 def un_prefix_key(cls, key):
1538 def un_prefix_key(cls, key):
1539 if key.startswith(cls.PREFIX):
1539 if key.startswith(cls.PREFIX):
1540 return key[len(cls.PREFIX):]
1540 return key[len(cls.PREFIX):]
1541 return key
1541 return key
1542
1542
1543 @classmethod
1543 @classmethod
1544 def get_by_key_name(cls, key, repo):
1544 def get_by_key_name(cls, key, repo):
1545 row = cls.query()\
1545 row = cls.query()\
1546 .filter(cls.repository == repo)\
1546 .filter(cls.repository == repo)\
1547 .filter(cls.field_key == key).scalar()
1547 .filter(cls.field_key == key).scalar()
1548 return row
1548 return row
1549
1549
1550
1550
1551 class Repository(Base, BaseModel):
1551 class Repository(Base, BaseModel):
1552 __tablename__ = 'repositories'
1552 __tablename__ = 'repositories'
1553 __table_args__ = (
1553 __table_args__ = (
1554 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1554 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1555 base_table_args,
1555 base_table_args,
1556 )
1556 )
1557 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1557 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1558 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1558 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1559 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1559 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1560
1560
1561 STATE_CREATED = 'repo_state_created'
1561 STATE_CREATED = 'repo_state_created'
1562 STATE_PENDING = 'repo_state_pending'
1562 STATE_PENDING = 'repo_state_pending'
1563 STATE_ERROR = 'repo_state_error'
1563 STATE_ERROR = 'repo_state_error'
1564
1564
1565 LOCK_AUTOMATIC = 'lock_auto'
1565 LOCK_AUTOMATIC = 'lock_auto'
1566 LOCK_API = 'lock_api'
1566 LOCK_API = 'lock_api'
1567 LOCK_WEB = 'lock_web'
1567 LOCK_WEB = 'lock_web'
1568 LOCK_PULL = 'lock_pull'
1568 LOCK_PULL = 'lock_pull'
1569
1569
1570 NAME_SEP = URL_SEP
1570 NAME_SEP = URL_SEP
1571
1571
1572 repo_id = Column(
1572 repo_id = Column(
1573 "repo_id", Integer(), nullable=False, unique=True, default=None,
1573 "repo_id", Integer(), nullable=False, unique=True, default=None,
1574 primary_key=True)
1574 primary_key=True)
1575 _repo_name = Column(
1575 _repo_name = Column(
1576 "repo_name", Text(), nullable=False, default=None)
1576 "repo_name", Text(), nullable=False, default=None)
1577 _repo_name_hash = Column(
1577 _repo_name_hash = Column(
1578 "repo_name_hash", String(255), nullable=False, unique=True)
1578 "repo_name_hash", String(255), nullable=False, unique=True)
1579 repo_state = Column("repo_state", String(255), nullable=True)
1579 repo_state = Column("repo_state", String(255), nullable=True)
1580
1580
1581 clone_uri = Column(
1581 clone_uri = Column(
1582 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1582 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1583 default=None)
1583 default=None)
1584 push_uri = Column(
1584 push_uri = Column(
1585 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1585 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1586 default=None)
1586 default=None)
1587 repo_type = Column(
1587 repo_type = Column(
1588 "repo_type", String(255), nullable=False, unique=False, default=None)
1588 "repo_type", String(255), nullable=False, unique=False, default=None)
1589 user_id = Column(
1589 user_id = Column(
1590 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1590 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1591 unique=False, default=None)
1591 unique=False, default=None)
1592 private = Column(
1592 private = Column(
1593 "private", Boolean(), nullable=True, unique=None, default=None)
1593 "private", Boolean(), nullable=True, unique=None, default=None)
1594 archived = Column(
1594 archived = Column(
1595 "archived", Boolean(), nullable=True, unique=None, default=None)
1595 "archived", Boolean(), nullable=True, unique=None, default=None)
1596 enable_statistics = Column(
1596 enable_statistics = Column(
1597 "statistics", Boolean(), nullable=True, unique=None, default=True)
1597 "statistics", Boolean(), nullable=True, unique=None, default=True)
1598 enable_downloads = Column(
1598 enable_downloads = Column(
1599 "downloads", Boolean(), nullable=True, unique=None, default=True)
1599 "downloads", Boolean(), nullable=True, unique=None, default=True)
1600 description = Column(
1600 description = Column(
1601 "description", String(10000), nullable=True, unique=None, default=None)
1601 "description", String(10000), nullable=True, unique=None, default=None)
1602 created_on = Column(
1602 created_on = Column(
1603 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1603 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1604 default=datetime.datetime.now)
1604 default=datetime.datetime.now)
1605 updated_on = Column(
1605 updated_on = Column(
1606 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1606 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1607 default=datetime.datetime.now)
1607 default=datetime.datetime.now)
1608 _landing_revision = Column(
1608 _landing_revision = Column(
1609 "landing_revision", String(255), nullable=False, unique=False,
1609 "landing_revision", String(255), nullable=False, unique=False,
1610 default=None)
1610 default=None)
1611 enable_locking = Column(
1611 enable_locking = Column(
1612 "enable_locking", Boolean(), nullable=False, unique=None,
1612 "enable_locking", Boolean(), nullable=False, unique=None,
1613 default=False)
1613 default=False)
1614 _locked = Column(
1614 _locked = Column(
1615 "locked", String(255), nullable=True, unique=False, default=None)
1615 "locked", String(255), nullable=True, unique=False, default=None)
1616 _changeset_cache = Column(
1616 _changeset_cache = Column(
1617 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1617 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1618
1618
1619 fork_id = Column(
1619 fork_id = Column(
1620 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1620 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1621 nullable=True, unique=False, default=None)
1621 nullable=True, unique=False, default=None)
1622 group_id = Column(
1622 group_id = Column(
1623 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1623 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1624 unique=False, default=None)
1624 unique=False, default=None)
1625
1625
1626 user = relationship('User', lazy='joined')
1626 user = relationship('User', lazy='joined')
1627 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1627 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1628 group = relationship('RepoGroup', lazy='joined')
1628 group = relationship('RepoGroup', lazy='joined')
1629 repo_to_perm = relationship(
1629 repo_to_perm = relationship(
1630 'UserRepoToPerm', cascade='all',
1630 'UserRepoToPerm', cascade='all',
1631 order_by='UserRepoToPerm.repo_to_perm_id')
1631 order_by='UserRepoToPerm.repo_to_perm_id')
1632 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1632 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1633 stats = relationship('Statistics', cascade='all', uselist=False)
1633 stats = relationship('Statistics', cascade='all', uselist=False)
1634
1634
1635 followers = relationship(
1635 followers = relationship(
1636 'UserFollowing',
1636 'UserFollowing',
1637 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1637 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1638 cascade='all')
1638 cascade='all')
1639 extra_fields = relationship(
1639 extra_fields = relationship(
1640 'RepositoryField', cascade="all, delete, delete-orphan")
1640 'RepositoryField', cascade="all, delete, delete-orphan")
1641 logs = relationship('UserLog')
1641 logs = relationship('UserLog')
1642 comments = relationship(
1642 comments = relationship(
1643 'ChangesetComment', cascade="all, delete, delete-orphan")
1643 'ChangesetComment', cascade="all, delete, delete-orphan")
1644 pull_requests_source = relationship(
1644 pull_requests_source = relationship(
1645 'PullRequest',
1645 'PullRequest',
1646 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1646 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1647 cascade="all, delete, delete-orphan")
1647 cascade="all, delete, delete-orphan")
1648 pull_requests_target = relationship(
1648 pull_requests_target = relationship(
1649 'PullRequest',
1649 'PullRequest',
1650 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1650 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1651 cascade="all, delete, delete-orphan")
1651 cascade="all, delete, delete-orphan")
1652 ui = relationship('RepoRhodeCodeUi', cascade="all")
1652 ui = relationship('RepoRhodeCodeUi', cascade="all")
1653 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1653 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1654 integrations = relationship('Integration',
1654 integrations = relationship('Integration',
1655 cascade="all, delete, delete-orphan")
1655 cascade="all, delete, delete-orphan")
1656
1656
1657 scoped_tokens = relationship('UserApiKeys', cascade="all")
1657 scoped_tokens = relationship('UserApiKeys', cascade="all")
1658
1658
1659 def __unicode__(self):
1659 def __unicode__(self):
1660 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1660 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1661 safe_unicode(self.repo_name))
1661 safe_unicode(self.repo_name))
1662
1662
1663 @hybrid_property
1663 @hybrid_property
1664 def description_safe(self):
1664 def description_safe(self):
1665 from rhodecode.lib import helpers as h
1665 from rhodecode.lib import helpers as h
1666 return h.escape(self.description)
1666 return h.escape(self.description)
1667
1667
1668 @hybrid_property
1668 @hybrid_property
1669 def landing_rev(self):
1669 def landing_rev(self):
1670 # always should return [rev_type, rev]
1670 # always should return [rev_type, rev]
1671 if self._landing_revision:
1671 if self._landing_revision:
1672 _rev_info = self._landing_revision.split(':')
1672 _rev_info = self._landing_revision.split(':')
1673 if len(_rev_info) < 2:
1673 if len(_rev_info) < 2:
1674 _rev_info.insert(0, 'rev')
1674 _rev_info.insert(0, 'rev')
1675 return [_rev_info[0], _rev_info[1]]
1675 return [_rev_info[0], _rev_info[1]]
1676 return [None, None]
1676 return [None, None]
1677
1677
1678 @landing_rev.setter
1678 @landing_rev.setter
1679 def landing_rev(self, val):
1679 def landing_rev(self, val):
1680 if ':' not in val:
1680 if ':' not in val:
1681 raise ValueError('value must be delimited with `:` and consist '
1681 raise ValueError('value must be delimited with `:` and consist '
1682 'of <rev_type>:<rev>, got %s instead' % val)
1682 'of <rev_type>:<rev>, got %s instead' % val)
1683 self._landing_revision = val
1683 self._landing_revision = val
1684
1684
1685 @hybrid_property
1685 @hybrid_property
1686 def locked(self):
1686 def locked(self):
1687 if self._locked:
1687 if self._locked:
1688 user_id, timelocked, reason = self._locked.split(':')
1688 user_id, timelocked, reason = self._locked.split(':')
1689 lock_values = int(user_id), timelocked, reason
1689 lock_values = int(user_id), timelocked, reason
1690 else:
1690 else:
1691 lock_values = [None, None, None]
1691 lock_values = [None, None, None]
1692 return lock_values
1692 return lock_values
1693
1693
1694 @locked.setter
1694 @locked.setter
1695 def locked(self, val):
1695 def locked(self, val):
1696 if val and isinstance(val, (list, tuple)):
1696 if val and isinstance(val, (list, tuple)):
1697 self._locked = ':'.join(map(str, val))
1697 self._locked = ':'.join(map(str, val))
1698 else:
1698 else:
1699 self._locked = None
1699 self._locked = None
1700
1700
1701 @hybrid_property
1701 @hybrid_property
1702 def changeset_cache(self):
1702 def changeset_cache(self):
1703 from rhodecode.lib.vcs.backends.base import EmptyCommit
1703 from rhodecode.lib.vcs.backends.base import EmptyCommit
1704 dummy = EmptyCommit().__json__()
1704 dummy = EmptyCommit().__json__()
1705 if not self._changeset_cache:
1705 if not self._changeset_cache:
1706 return dummy
1706 return dummy
1707 try:
1707 try:
1708 return json.loads(self._changeset_cache)
1708 return json.loads(self._changeset_cache)
1709 except TypeError:
1709 except TypeError:
1710 return dummy
1710 return dummy
1711 except Exception:
1711 except Exception:
1712 log.error(traceback.format_exc())
1712 log.error(traceback.format_exc())
1713 return dummy
1713 return dummy
1714
1714
1715 @changeset_cache.setter
1715 @changeset_cache.setter
1716 def changeset_cache(self, val):
1716 def changeset_cache(self, val):
1717 try:
1717 try:
1718 self._changeset_cache = json.dumps(val)
1718 self._changeset_cache = json.dumps(val)
1719 except Exception:
1719 except Exception:
1720 log.error(traceback.format_exc())
1720 log.error(traceback.format_exc())
1721
1721
1722 @hybrid_property
1722 @hybrid_property
1723 def repo_name(self):
1723 def repo_name(self):
1724 return self._repo_name
1724 return self._repo_name
1725
1725
1726 @repo_name.setter
1726 @repo_name.setter
1727 def repo_name(self, value):
1727 def repo_name(self, value):
1728 self._repo_name = value
1728 self._repo_name = value
1729 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1729 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1730
1730
1731 @classmethod
1731 @classmethod
1732 def normalize_repo_name(cls, repo_name):
1732 def normalize_repo_name(cls, repo_name):
1733 """
1733 """
1734 Normalizes os specific repo_name to the format internally stored inside
1734 Normalizes os specific repo_name to the format internally stored inside
1735 database using URL_SEP
1735 database using URL_SEP
1736
1736
1737 :param cls:
1737 :param cls:
1738 :param repo_name:
1738 :param repo_name:
1739 """
1739 """
1740 return cls.NAME_SEP.join(repo_name.split(os.sep))
1740 return cls.NAME_SEP.join(repo_name.split(os.sep))
1741
1741
1742 @classmethod
1742 @classmethod
1743 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1743 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1744 session = Session()
1744 session = Session()
1745 q = session.query(cls).filter(cls.repo_name == repo_name)
1745 q = session.query(cls).filter(cls.repo_name == repo_name)
1746
1746
1747 if cache:
1747 if cache:
1748 if identity_cache:
1748 if identity_cache:
1749 val = cls.identity_cache(session, 'repo_name', repo_name)
1749 val = cls.identity_cache(session, 'repo_name', repo_name)
1750 if val:
1750 if val:
1751 return val
1751 return val
1752 else:
1752 else:
1753 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1753 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1754 q = q.options(
1754 q = q.options(
1755 FromCache("sql_cache_short", cache_key))
1755 FromCache("sql_cache_short", cache_key))
1756
1756
1757 return q.scalar()
1757 return q.scalar()
1758
1758
1759 @classmethod
1759 @classmethod
1760 def get_by_id_or_repo_name(cls, repoid):
1760 def get_by_id_or_repo_name(cls, repoid):
1761 if isinstance(repoid, (int, long)):
1761 if isinstance(repoid, (int, long)):
1762 try:
1762 try:
1763 repo = cls.get(repoid)
1763 repo = cls.get(repoid)
1764 except ValueError:
1764 except ValueError:
1765 repo = None
1765 repo = None
1766 else:
1766 else:
1767 repo = cls.get_by_repo_name(repoid)
1767 repo = cls.get_by_repo_name(repoid)
1768 return repo
1768 return repo
1769
1769
1770 @classmethod
1770 @classmethod
1771 def get_by_full_path(cls, repo_full_path):
1771 def get_by_full_path(cls, repo_full_path):
1772 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1772 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1773 repo_name = cls.normalize_repo_name(repo_name)
1773 repo_name = cls.normalize_repo_name(repo_name)
1774 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1774 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1775
1775
1776 @classmethod
1776 @classmethod
1777 def get_repo_forks(cls, repo_id):
1777 def get_repo_forks(cls, repo_id):
1778 return cls.query().filter(Repository.fork_id == repo_id)
1778 return cls.query().filter(Repository.fork_id == repo_id)
1779
1779
1780 @classmethod
1780 @classmethod
1781 def base_path(cls):
1781 def base_path(cls):
1782 """
1782 """
1783 Returns base path when all repos are stored
1783 Returns base path when all repos are stored
1784
1784
1785 :param cls:
1785 :param cls:
1786 """
1786 """
1787 q = Session().query(RhodeCodeUi)\
1787 q = Session().query(RhodeCodeUi)\
1788 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1788 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1789 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1789 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1790 return q.one().ui_value
1790 return q.one().ui_value
1791
1791
1792 @classmethod
1792 @classmethod
1793 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1793 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1794 case_insensitive=True, archived=False):
1794 case_insensitive=True, archived=False):
1795 q = Repository.query()
1795 q = Repository.query()
1796
1796
1797 if not archived:
1797 if not archived:
1798 q = q.filter(Repository.archived.isnot(true()))
1798 q = q.filter(Repository.archived.isnot(true()))
1799
1799
1800 if not isinstance(user_id, Optional):
1800 if not isinstance(user_id, Optional):
1801 q = q.filter(Repository.user_id == user_id)
1801 q = q.filter(Repository.user_id == user_id)
1802
1802
1803 if not isinstance(group_id, Optional):
1803 if not isinstance(group_id, Optional):
1804 q = q.filter(Repository.group_id == group_id)
1804 q = q.filter(Repository.group_id == group_id)
1805
1805
1806 if case_insensitive:
1806 if case_insensitive:
1807 q = q.order_by(func.lower(Repository.repo_name))
1807 q = q.order_by(func.lower(Repository.repo_name))
1808 else:
1808 else:
1809 q = q.order_by(Repository.repo_name)
1809 q = q.order_by(Repository.repo_name)
1810
1810
1811 return q.all()
1811 return q.all()
1812
1812
1813 @property
1813 @property
1814 def forks(self):
1814 def forks(self):
1815 """
1815 """
1816 Return forks of this repo
1816 Return forks of this repo
1817 """
1817 """
1818 return Repository.get_repo_forks(self.repo_id)
1818 return Repository.get_repo_forks(self.repo_id)
1819
1819
1820 @property
1820 @property
1821 def parent(self):
1821 def parent(self):
1822 """
1822 """
1823 Returns fork parent
1823 Returns fork parent
1824 """
1824 """
1825 return self.fork
1825 return self.fork
1826
1826
1827 @property
1827 @property
1828 def just_name(self):
1828 def just_name(self):
1829 return self.repo_name.split(self.NAME_SEP)[-1]
1829 return self.repo_name.split(self.NAME_SEP)[-1]
1830
1830
1831 @property
1831 @property
1832 def groups_with_parents(self):
1832 def groups_with_parents(self):
1833 groups = []
1833 groups = []
1834 if self.group is None:
1834 if self.group is None:
1835 return groups
1835 return groups
1836
1836
1837 cur_gr = self.group
1837 cur_gr = self.group
1838 groups.insert(0, cur_gr)
1838 groups.insert(0, cur_gr)
1839 while 1:
1839 while 1:
1840 gr = getattr(cur_gr, 'parent_group', None)
1840 gr = getattr(cur_gr, 'parent_group', None)
1841 cur_gr = cur_gr.parent_group
1841 cur_gr = cur_gr.parent_group
1842 if gr is None:
1842 if gr is None:
1843 break
1843 break
1844 groups.insert(0, gr)
1844 groups.insert(0, gr)
1845
1845
1846 return groups
1846 return groups
1847
1847
1848 @property
1848 @property
1849 def groups_and_repo(self):
1849 def groups_and_repo(self):
1850 return self.groups_with_parents, self
1850 return self.groups_with_parents, self
1851
1851
1852 @LazyProperty
1852 @LazyProperty
1853 def repo_path(self):
1853 def repo_path(self):
1854 """
1854 """
1855 Returns base full path for that repository means where it actually
1855 Returns base full path for that repository means where it actually
1856 exists on a filesystem
1856 exists on a filesystem
1857 """
1857 """
1858 q = Session().query(RhodeCodeUi).filter(
1858 q = Session().query(RhodeCodeUi).filter(
1859 RhodeCodeUi.ui_key == self.NAME_SEP)
1859 RhodeCodeUi.ui_key == self.NAME_SEP)
1860 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1860 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1861 return q.one().ui_value
1861 return q.one().ui_value
1862
1862
1863 @property
1863 @property
1864 def repo_full_path(self):
1864 def repo_full_path(self):
1865 p = [self.repo_path]
1865 p = [self.repo_path]
1866 # we need to split the name by / since this is how we store the
1866 # we need to split the name by / since this is how we store the
1867 # names in the database, but that eventually needs to be converted
1867 # names in the database, but that eventually needs to be converted
1868 # into a valid system path
1868 # into a valid system path
1869 p += self.repo_name.split(self.NAME_SEP)
1869 p += self.repo_name.split(self.NAME_SEP)
1870 return os.path.join(*map(safe_unicode, p))
1870 return os.path.join(*map(safe_unicode, p))
1871
1871
1872 @property
1872 @property
1873 def cache_keys(self):
1873 def cache_keys(self):
1874 """
1874 """
1875 Returns associated cache keys for that repo
1875 Returns associated cache keys for that repo
1876 """
1876 """
1877 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1877 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1878 repo_id=self.repo_id)
1878 repo_id=self.repo_id)
1879 return CacheKey.query()\
1879 return CacheKey.query()\
1880 .filter(CacheKey.cache_args == invalidation_namespace)\
1880 .filter(CacheKey.cache_args == invalidation_namespace)\
1881 .order_by(CacheKey.cache_key)\
1881 .order_by(CacheKey.cache_key)\
1882 .all()
1882 .all()
1883
1883
1884 @property
1884 @property
1885 def cached_diffs_relative_dir(self):
1885 def cached_diffs_relative_dir(self):
1886 """
1886 """
1887 Return a relative to the repository store path of cached diffs
1887 Return a relative to the repository store path of cached diffs
1888 used for safe display for users, who shouldn't know the absolute store
1888 used for safe display for users, who shouldn't know the absolute store
1889 path
1889 path
1890 """
1890 """
1891 return os.path.join(
1891 return os.path.join(
1892 os.path.dirname(self.repo_name),
1892 os.path.dirname(self.repo_name),
1893 self.cached_diffs_dir.split(os.path.sep)[-1])
1893 self.cached_diffs_dir.split(os.path.sep)[-1])
1894
1894
1895 @property
1895 @property
1896 def cached_diffs_dir(self):
1896 def cached_diffs_dir(self):
1897 path = self.repo_full_path
1897 path = self.repo_full_path
1898 return os.path.join(
1898 return os.path.join(
1899 os.path.dirname(path),
1899 os.path.dirname(path),
1900 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1900 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1901
1901
1902 def cached_diffs(self):
1902 def cached_diffs(self):
1903 diff_cache_dir = self.cached_diffs_dir
1903 diff_cache_dir = self.cached_diffs_dir
1904 if os.path.isdir(diff_cache_dir):
1904 if os.path.isdir(diff_cache_dir):
1905 return os.listdir(diff_cache_dir)
1905 return os.listdir(diff_cache_dir)
1906 return []
1906 return []
1907
1907
1908 def shadow_repos(self):
1908 def shadow_repos(self):
1909 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1909 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1910 return [
1910 return [
1911 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1911 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1912 if x.startswith(shadow_repos_pattern)]
1912 if x.startswith(shadow_repos_pattern)]
1913
1913
1914 def get_new_name(self, repo_name):
1914 def get_new_name(self, repo_name):
1915 """
1915 """
1916 returns new full repository name based on assigned group and new new
1916 returns new full repository name based on assigned group and new new
1917
1917
1918 :param group_name:
1918 :param group_name:
1919 """
1919 """
1920 path_prefix = self.group.full_path_splitted if self.group else []
1920 path_prefix = self.group.full_path_splitted if self.group else []
1921 return self.NAME_SEP.join(path_prefix + [repo_name])
1921 return self.NAME_SEP.join(path_prefix + [repo_name])
1922
1922
1923 @property
1923 @property
1924 def _config(self):
1924 def _config(self):
1925 """
1925 """
1926 Returns db based config object.
1926 Returns db based config object.
1927 """
1927 """
1928 from rhodecode.lib.utils import make_db_config
1928 from rhodecode.lib.utils import make_db_config
1929 return make_db_config(clear_session=False, repo=self)
1929 return make_db_config(clear_session=False, repo=self)
1930
1930
1931 def permissions(self, with_admins=True, with_owner=True):
1931 def permissions(self, with_admins=True, with_owner=True):
1932 """
1932 """
1933 Permissions for repositories
1933 Permissions for repositories
1934 """
1934 """
1935 _admin_perm = 'repository.admin'
1935 _admin_perm = 'repository.admin'
1936
1936
1937 owner_row = []
1937 owner_row = []
1938 if with_owner:
1938 if with_owner:
1939 usr = AttributeDict(self.user.get_dict())
1939 usr = AttributeDict(self.user.get_dict())
1940 usr.owner_row = True
1940 usr.owner_row = True
1941 usr.permission = _admin_perm
1941 usr.permission = _admin_perm
1942 usr.permission_id = None
1942 usr.permission_id = None
1943 owner_row.append(usr)
1943 owner_row.append(usr)
1944
1944
1945 super_admin_ids = []
1945 super_admin_ids = []
1946 super_admin_rows = []
1946 super_admin_rows = []
1947 if with_admins:
1947 if with_admins:
1948 for usr in User.get_all_super_admins():
1948 for usr in User.get_all_super_admins():
1949 super_admin_ids.append(usr.user_id)
1949 super_admin_ids.append(usr.user_id)
1950 # if this admin is also owner, don't double the record
1950 # if this admin is also owner, don't double the record
1951 if usr.user_id == owner_row[0].user_id:
1951 if usr.user_id == owner_row[0].user_id:
1952 owner_row[0].admin_row = True
1952 owner_row[0].admin_row = True
1953 else:
1953 else:
1954 usr = AttributeDict(usr.get_dict())
1954 usr = AttributeDict(usr.get_dict())
1955 usr.admin_row = True
1955 usr.admin_row = True
1956 usr.permission = _admin_perm
1956 usr.permission = _admin_perm
1957 usr.permission_id = None
1957 usr.permission_id = None
1958 super_admin_rows.append(usr)
1958 super_admin_rows.append(usr)
1959
1959
1960 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1960 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1961 q = q.options(joinedload(UserRepoToPerm.repository),
1961 q = q.options(joinedload(UserRepoToPerm.repository),
1962 joinedload(UserRepoToPerm.user),
1962 joinedload(UserRepoToPerm.user),
1963 joinedload(UserRepoToPerm.permission),)
1963 joinedload(UserRepoToPerm.permission),)
1964
1964
1965 # get owners and admins and permissions. We do a trick of re-writing
1965 # get owners and admins and permissions. We do a trick of re-writing
1966 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1966 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1967 # has a global reference and changing one object propagates to all
1967 # has a global reference and changing one object propagates to all
1968 # others. This means if admin is also an owner admin_row that change
1968 # others. This means if admin is also an owner admin_row that change
1969 # would propagate to both objects
1969 # would propagate to both objects
1970 perm_rows = []
1970 perm_rows = []
1971 for _usr in q.all():
1971 for _usr in q.all():
1972 usr = AttributeDict(_usr.user.get_dict())
1972 usr = AttributeDict(_usr.user.get_dict())
1973 # if this user is also owner/admin, mark as duplicate record
1973 # if this user is also owner/admin, mark as duplicate record
1974 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1974 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1975 usr.duplicate_perm = True
1975 usr.duplicate_perm = True
1976 # also check if this permission is maybe used by branch_permissions
1976 # also check if this permission is maybe used by branch_permissions
1977 if _usr.branch_perm_entry:
1977 if _usr.branch_perm_entry:
1978 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1978 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1979
1979
1980 usr.permission = _usr.permission.permission_name
1980 usr.permission = _usr.permission.permission_name
1981 usr.permission_id = _usr.repo_to_perm_id
1981 usr.permission_id = _usr.repo_to_perm_id
1982 perm_rows.append(usr)
1982 perm_rows.append(usr)
1983
1983
1984 # filter the perm rows by 'default' first and then sort them by
1984 # filter the perm rows by 'default' first and then sort them by
1985 # admin,write,read,none permissions sorted again alphabetically in
1985 # admin,write,read,none permissions sorted again alphabetically in
1986 # each group
1986 # each group
1987 perm_rows = sorted(perm_rows, key=display_user_sort)
1987 perm_rows = sorted(perm_rows, key=display_user_sort)
1988
1988
1989 return super_admin_rows + owner_row + perm_rows
1989 return super_admin_rows + owner_row + perm_rows
1990
1990
1991 def permission_user_groups(self):
1991 def permission_user_groups(self):
1992 q = UserGroupRepoToPerm.query().filter(
1992 q = UserGroupRepoToPerm.query().filter(
1993 UserGroupRepoToPerm.repository == self)
1993 UserGroupRepoToPerm.repository == self)
1994 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1994 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1995 joinedload(UserGroupRepoToPerm.users_group),
1995 joinedload(UserGroupRepoToPerm.users_group),
1996 joinedload(UserGroupRepoToPerm.permission),)
1996 joinedload(UserGroupRepoToPerm.permission),)
1997
1997
1998 perm_rows = []
1998 perm_rows = []
1999 for _user_group in q.all():
1999 for _user_group in q.all():
2000 usr = AttributeDict(_user_group.users_group.get_dict())
2000 usr = AttributeDict(_user_group.users_group.get_dict())
2001 usr.permission = _user_group.permission.permission_name
2001 usr.permission = _user_group.permission.permission_name
2002 perm_rows.append(usr)
2002 perm_rows.append(usr)
2003
2003
2004 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2004 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2005 return perm_rows
2005 return perm_rows
2006
2006
2007 def get_api_data(self, include_secrets=False):
2007 def get_api_data(self, include_secrets=False):
2008 """
2008 """
2009 Common function for generating repo api data
2009 Common function for generating repo api data
2010
2010
2011 :param include_secrets: See :meth:`User.get_api_data`.
2011 :param include_secrets: See :meth:`User.get_api_data`.
2012
2012
2013 """
2013 """
2014 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2014 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2015 # move this methods on models level.
2015 # move this methods on models level.
2016 from rhodecode.model.settings import SettingsModel
2016 from rhodecode.model.settings import SettingsModel
2017 from rhodecode.model.repo import RepoModel
2017 from rhodecode.model.repo import RepoModel
2018
2018
2019 repo = self
2019 repo = self
2020 _user_id, _time, _reason = self.locked
2020 _user_id, _time, _reason = self.locked
2021
2021
2022 data = {
2022 data = {
2023 'repo_id': repo.repo_id,
2023 'repo_id': repo.repo_id,
2024 'repo_name': repo.repo_name,
2024 'repo_name': repo.repo_name,
2025 'repo_type': repo.repo_type,
2025 'repo_type': repo.repo_type,
2026 'clone_uri': repo.clone_uri or '',
2026 'clone_uri': repo.clone_uri or '',
2027 'push_uri': repo.push_uri or '',
2027 'push_uri': repo.push_uri or '',
2028 'url': RepoModel().get_url(self),
2028 'url': RepoModel().get_url(self),
2029 'private': repo.private,
2029 'private': repo.private,
2030 'created_on': repo.created_on,
2030 'created_on': repo.created_on,
2031 'description': repo.description_safe,
2031 'description': repo.description_safe,
2032 'landing_rev': repo.landing_rev,
2032 'landing_rev': repo.landing_rev,
2033 'owner': repo.user.username,
2033 'owner': repo.user.username,
2034 'fork_of': repo.fork.repo_name if repo.fork else None,
2034 'fork_of': repo.fork.repo_name if repo.fork else None,
2035 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2035 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2036 'enable_statistics': repo.enable_statistics,
2036 'enable_statistics': repo.enable_statistics,
2037 'enable_locking': repo.enable_locking,
2037 'enable_locking': repo.enable_locking,
2038 'enable_downloads': repo.enable_downloads,
2038 'enable_downloads': repo.enable_downloads,
2039 'last_changeset': repo.changeset_cache,
2039 'last_changeset': repo.changeset_cache,
2040 'locked_by': User.get(_user_id).get_api_data(
2040 'locked_by': User.get(_user_id).get_api_data(
2041 include_secrets=include_secrets) if _user_id else None,
2041 include_secrets=include_secrets) if _user_id else None,
2042 'locked_date': time_to_datetime(_time) if _time else None,
2042 'locked_date': time_to_datetime(_time) if _time else None,
2043 'lock_reason': _reason if _reason else None,
2043 'lock_reason': _reason if _reason else None,
2044 }
2044 }
2045
2045
2046 # TODO: mikhail: should be per-repo settings here
2046 # TODO: mikhail: should be per-repo settings here
2047 rc_config = SettingsModel().get_all_settings()
2047 rc_config = SettingsModel().get_all_settings()
2048 repository_fields = str2bool(
2048 repository_fields = str2bool(
2049 rc_config.get('rhodecode_repository_fields'))
2049 rc_config.get('rhodecode_repository_fields'))
2050 if repository_fields:
2050 if repository_fields:
2051 for f in self.extra_fields:
2051 for f in self.extra_fields:
2052 data[f.field_key_prefixed] = f.field_value
2052 data[f.field_key_prefixed] = f.field_value
2053
2053
2054 return data
2054 return data
2055
2055
2056 @classmethod
2056 @classmethod
2057 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2057 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2058 if not lock_time:
2058 if not lock_time:
2059 lock_time = time.time()
2059 lock_time = time.time()
2060 if not lock_reason:
2060 if not lock_reason:
2061 lock_reason = cls.LOCK_AUTOMATIC
2061 lock_reason = cls.LOCK_AUTOMATIC
2062 repo.locked = [user_id, lock_time, lock_reason]
2062 repo.locked = [user_id, lock_time, lock_reason]
2063 Session().add(repo)
2063 Session().add(repo)
2064 Session().commit()
2064 Session().commit()
2065
2065
2066 @classmethod
2066 @classmethod
2067 def unlock(cls, repo):
2067 def unlock(cls, repo):
2068 repo.locked = None
2068 repo.locked = None
2069 Session().add(repo)
2069 Session().add(repo)
2070 Session().commit()
2070 Session().commit()
2071
2071
2072 @classmethod
2072 @classmethod
2073 def getlock(cls, repo):
2073 def getlock(cls, repo):
2074 return repo.locked
2074 return repo.locked
2075
2075
2076 def is_user_lock(self, user_id):
2076 def is_user_lock(self, user_id):
2077 if self.lock[0]:
2077 if self.lock[0]:
2078 lock_user_id = safe_int(self.lock[0])
2078 lock_user_id = safe_int(self.lock[0])
2079 user_id = safe_int(user_id)
2079 user_id = safe_int(user_id)
2080 # both are ints, and they are equal
2080 # both are ints, and they are equal
2081 return all([lock_user_id, user_id]) and lock_user_id == user_id
2081 return all([lock_user_id, user_id]) and lock_user_id == user_id
2082
2082
2083 return False
2083 return False
2084
2084
2085 def get_locking_state(self, action, user_id, only_when_enabled=True):
2085 def get_locking_state(self, action, user_id, only_when_enabled=True):
2086 """
2086 """
2087 Checks locking on this repository, if locking is enabled and lock is
2087 Checks locking on this repository, if locking is enabled and lock is
2088 present returns a tuple of make_lock, locked, locked_by.
2088 present returns a tuple of make_lock, locked, locked_by.
2089 make_lock can have 3 states None (do nothing) True, make lock
2089 make_lock can have 3 states None (do nothing) True, make lock
2090 False release lock, This value is later propagated to hooks, which
2090 False release lock, This value is later propagated to hooks, which
2091 do the locking. Think about this as signals passed to hooks what to do.
2091 do the locking. Think about this as signals passed to hooks what to do.
2092
2092
2093 """
2093 """
2094 # TODO: johbo: This is part of the business logic and should be moved
2094 # TODO: johbo: This is part of the business logic and should be moved
2095 # into the RepositoryModel.
2095 # into the RepositoryModel.
2096
2096
2097 if action not in ('push', 'pull'):
2097 if action not in ('push', 'pull'):
2098 raise ValueError("Invalid action value: %s" % repr(action))
2098 raise ValueError("Invalid action value: %s" % repr(action))
2099
2099
2100 # defines if locked error should be thrown to user
2100 # defines if locked error should be thrown to user
2101 currently_locked = False
2101 currently_locked = False
2102 # defines if new lock should be made, tri-state
2102 # defines if new lock should be made, tri-state
2103 make_lock = None
2103 make_lock = None
2104 repo = self
2104 repo = self
2105 user = User.get(user_id)
2105 user = User.get(user_id)
2106
2106
2107 lock_info = repo.locked
2107 lock_info = repo.locked
2108
2108
2109 if repo and (repo.enable_locking or not only_when_enabled):
2109 if repo and (repo.enable_locking or not only_when_enabled):
2110 if action == 'push':
2110 if action == 'push':
2111 # check if it's already locked !, if it is compare users
2111 # check if it's already locked !, if it is compare users
2112 locked_by_user_id = lock_info[0]
2112 locked_by_user_id = lock_info[0]
2113 if user.user_id == locked_by_user_id:
2113 if user.user_id == locked_by_user_id:
2114 log.debug(
2114 log.debug(
2115 'Got `push` action from user %s, now unlocking', user)
2115 'Got `push` action from user %s, now unlocking', user)
2116 # unlock if we have push from user who locked
2116 # unlock if we have push from user who locked
2117 make_lock = False
2117 make_lock = False
2118 else:
2118 else:
2119 # we're not the same user who locked, ban with
2119 # we're not the same user who locked, ban with
2120 # code defined in settings (default is 423 HTTP Locked) !
2120 # code defined in settings (default is 423 HTTP Locked) !
2121 log.debug('Repo %s is currently locked by %s', repo, user)
2121 log.debug('Repo %s is currently locked by %s', repo, user)
2122 currently_locked = True
2122 currently_locked = True
2123 elif action == 'pull':
2123 elif action == 'pull':
2124 # [0] user [1] date
2124 # [0] user [1] date
2125 if lock_info[0] and lock_info[1]:
2125 if lock_info[0] and lock_info[1]:
2126 log.debug('Repo %s is currently locked by %s', repo, user)
2126 log.debug('Repo %s is currently locked by %s', repo, user)
2127 currently_locked = True
2127 currently_locked = True
2128 else:
2128 else:
2129 log.debug('Setting lock on repo %s by %s', repo, user)
2129 log.debug('Setting lock on repo %s by %s', repo, user)
2130 make_lock = True
2130 make_lock = True
2131
2131
2132 else:
2132 else:
2133 log.debug('Repository %s do not have locking enabled', repo)
2133 log.debug('Repository %s do not have locking enabled', repo)
2134
2134
2135 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2135 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2136 make_lock, currently_locked, lock_info)
2136 make_lock, currently_locked, lock_info)
2137
2137
2138 from rhodecode.lib.auth import HasRepoPermissionAny
2138 from rhodecode.lib.auth import HasRepoPermissionAny
2139 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2139 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2140 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2140 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2141 # if we don't have at least write permission we cannot make a lock
2141 # if we don't have at least write permission we cannot make a lock
2142 log.debug('lock state reset back to FALSE due to lack '
2142 log.debug('lock state reset back to FALSE due to lack '
2143 'of at least read permission')
2143 'of at least read permission')
2144 make_lock = False
2144 make_lock = False
2145
2145
2146 return make_lock, currently_locked, lock_info
2146 return make_lock, currently_locked, lock_info
2147
2147
2148 @property
2148 @property
2149 def last_db_change(self):
2149 def last_db_change(self):
2150 return self.updated_on
2150 return self.updated_on
2151
2151
2152 @property
2152 @property
2153 def clone_uri_hidden(self):
2153 def clone_uri_hidden(self):
2154 clone_uri = self.clone_uri
2154 clone_uri = self.clone_uri
2155 if clone_uri:
2155 if clone_uri:
2156 import urlobject
2156 import urlobject
2157 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2157 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2158 if url_obj.password:
2158 if url_obj.password:
2159 clone_uri = url_obj.with_password('*****')
2159 clone_uri = url_obj.with_password('*****')
2160 return clone_uri
2160 return clone_uri
2161
2161
2162 @property
2162 @property
2163 def push_uri_hidden(self):
2163 def push_uri_hidden(self):
2164 push_uri = self.push_uri
2164 push_uri = self.push_uri
2165 if push_uri:
2165 if push_uri:
2166 import urlobject
2166 import urlobject
2167 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2167 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2168 if url_obj.password:
2168 if url_obj.password:
2169 push_uri = url_obj.with_password('*****')
2169 push_uri = url_obj.with_password('*****')
2170 return push_uri
2170 return push_uri
2171
2171
2172 def clone_url(self, **override):
2172 def clone_url(self, **override):
2173 from rhodecode.model.settings import SettingsModel
2173 from rhodecode.model.settings import SettingsModel
2174
2174
2175 uri_tmpl = None
2175 uri_tmpl = None
2176 if 'with_id' in override:
2176 if 'with_id' in override:
2177 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2177 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2178 del override['with_id']
2178 del override['with_id']
2179
2179
2180 if 'uri_tmpl' in override:
2180 if 'uri_tmpl' in override:
2181 uri_tmpl = override['uri_tmpl']
2181 uri_tmpl = override['uri_tmpl']
2182 del override['uri_tmpl']
2182 del override['uri_tmpl']
2183
2183
2184 ssh = False
2184 ssh = False
2185 if 'ssh' in override:
2185 if 'ssh' in override:
2186 ssh = True
2186 ssh = True
2187 del override['ssh']
2187 del override['ssh']
2188
2188
2189 # we didn't override our tmpl from **overrides
2189 # we didn't override our tmpl from **overrides
2190 if not uri_tmpl:
2190 if not uri_tmpl:
2191 rc_config = SettingsModel().get_all_settings(cache=True)
2191 rc_config = SettingsModel().get_all_settings(cache=True)
2192 if ssh:
2192 if ssh:
2193 uri_tmpl = rc_config.get(
2193 uri_tmpl = rc_config.get(
2194 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2194 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2195 else:
2195 else:
2196 uri_tmpl = rc_config.get(
2196 uri_tmpl = rc_config.get(
2197 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2197 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2198
2198
2199 request = get_current_request()
2199 request = get_current_request()
2200 return get_clone_url(request=request,
2200 return get_clone_url(request=request,
2201 uri_tmpl=uri_tmpl,
2201 uri_tmpl=uri_tmpl,
2202 repo_name=self.repo_name,
2202 repo_name=self.repo_name,
2203 repo_id=self.repo_id, **override)
2203 repo_id=self.repo_id, **override)
2204
2204
2205 def set_state(self, state):
2205 def set_state(self, state):
2206 self.repo_state = state
2206 self.repo_state = state
2207 Session().add(self)
2207 Session().add(self)
2208 #==========================================================================
2208 #==========================================================================
2209 # SCM PROPERTIES
2209 # SCM PROPERTIES
2210 #==========================================================================
2210 #==========================================================================
2211
2211
2212 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2212 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2213 return get_commit_safe(
2213 return get_commit_safe(
2214 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2214 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2215
2215
2216 def get_changeset(self, rev=None, pre_load=None):
2216 def get_changeset(self, rev=None, pre_load=None):
2217 warnings.warn("Use get_commit", DeprecationWarning)
2217 warnings.warn("Use get_commit", DeprecationWarning)
2218 commit_id = None
2218 commit_id = None
2219 commit_idx = None
2219 commit_idx = None
2220 if isinstance(rev, compat.string_types):
2220 if isinstance(rev, compat.string_types):
2221 commit_id = rev
2221 commit_id = rev
2222 else:
2222 else:
2223 commit_idx = rev
2223 commit_idx = rev
2224 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2224 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2225 pre_load=pre_load)
2225 pre_load=pre_load)
2226
2226
2227 def get_landing_commit(self):
2227 def get_landing_commit(self):
2228 """
2228 """
2229 Returns landing commit, or if that doesn't exist returns the tip
2229 Returns landing commit, or if that doesn't exist returns the tip
2230 """
2230 """
2231 _rev_type, _rev = self.landing_rev
2231 _rev_type, _rev = self.landing_rev
2232 commit = self.get_commit(_rev)
2232 commit = self.get_commit(_rev)
2233 if isinstance(commit, EmptyCommit):
2233 if isinstance(commit, EmptyCommit):
2234 return self.get_commit()
2234 return self.get_commit()
2235 return commit
2235 return commit
2236
2236
2237 def update_commit_cache(self, cs_cache=None, config=None):
2237 def update_commit_cache(self, cs_cache=None, config=None):
2238 """
2238 """
2239 Update cache of last changeset for repository, keys should be::
2239 Update cache of last changeset for repository, keys should be::
2240
2240
2241 short_id
2241 short_id
2242 raw_id
2242 raw_id
2243 revision
2243 revision
2244 parents
2244 parents
2245 message
2245 message
2246 date
2246 date
2247 author
2247 author
2248
2248
2249 :param cs_cache:
2249 :param cs_cache:
2250 """
2250 """
2251 from rhodecode.lib.vcs.backends.base import BaseChangeset
2251 from rhodecode.lib.vcs.backends.base import BaseChangeset
2252 if cs_cache is None:
2252 if cs_cache is None:
2253 # use no-cache version here
2253 # use no-cache version here
2254 scm_repo = self.scm_instance(cache=False, config=config)
2254 scm_repo = self.scm_instance(cache=False, config=config)
2255
2255
2256 empty = scm_repo.is_empty()
2256 empty = scm_repo.is_empty()
2257 if not empty:
2257 if not empty:
2258 cs_cache = scm_repo.get_commit(
2258 cs_cache = scm_repo.get_commit(
2259 pre_load=["author", "date", "message", "parents"])
2259 pre_load=["author", "date", "message", "parents"])
2260 else:
2260 else:
2261 cs_cache = EmptyCommit()
2261 cs_cache = EmptyCommit()
2262
2262
2263 if isinstance(cs_cache, BaseChangeset):
2263 if isinstance(cs_cache, BaseChangeset):
2264 cs_cache = cs_cache.__json__()
2264 cs_cache = cs_cache.__json__()
2265
2265
2266 def is_outdated(new_cs_cache):
2266 def is_outdated(new_cs_cache):
2267 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2267 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2268 new_cs_cache['revision'] != self.changeset_cache['revision']):
2268 new_cs_cache['revision'] != self.changeset_cache['revision']):
2269 return True
2269 return True
2270 return False
2270 return False
2271
2271
2272 # check if we have maybe already latest cached revision
2272 # check if we have maybe already latest cached revision
2273 if is_outdated(cs_cache) or not self.changeset_cache:
2273 if is_outdated(cs_cache) or not self.changeset_cache:
2274 _default = datetime.datetime.utcnow()
2274 _default = datetime.datetime.utcnow()
2275 last_change = cs_cache.get('date') or _default
2275 last_change = cs_cache.get('date') or _default
2276 if self.updated_on and self.updated_on > last_change:
2276 if self.updated_on and self.updated_on > last_change:
2277 # we check if last update is newer than the new value
2277 # we check if last update is newer than the new value
2278 # if yes, we use the current timestamp instead. Imagine you get
2278 # if yes, we use the current timestamp instead. Imagine you get
2279 # old commit pushed 1y ago, we'd set last update 1y to ago.
2279 # old commit pushed 1y ago, we'd set last update 1y to ago.
2280 last_change = _default
2280 last_change = _default
2281 log.debug('updated repo %s with new commit cache %s',
2281 log.debug('updated repo %s with new commit cache %s',
2282 self.repo_name, cs_cache)
2282 self.repo_name, cs_cache)
2283 self.updated_on = last_change
2283 self.updated_on = last_change
2284 self.changeset_cache = cs_cache
2284 self.changeset_cache = cs_cache
2285 Session().add(self)
2285 Session().add(self)
2286 Session().commit()
2286 Session().commit()
2287 else:
2287 else:
2288 log.debug('Skipping update_commit_cache for repo:`%s` '
2288 log.debug('Skipping update_commit_cache for repo:`%s` '
2289 'commit already with latest changes', self.repo_name)
2289 'commit already with latest changes', self.repo_name)
2290
2290
2291 @property
2291 @property
2292 def tip(self):
2292 def tip(self):
2293 return self.get_commit('tip')
2293 return self.get_commit('tip')
2294
2294
2295 @property
2295 @property
2296 def author(self):
2296 def author(self):
2297 return self.tip.author
2297 return self.tip.author
2298
2298
2299 @property
2299 @property
2300 def last_change(self):
2300 def last_change(self):
2301 return self.scm_instance().last_change
2301 return self.scm_instance().last_change
2302
2302
2303 def get_comments(self, revisions=None):
2303 def get_comments(self, revisions=None):
2304 """
2304 """
2305 Returns comments for this repository grouped by revisions
2305 Returns comments for this repository grouped by revisions
2306
2306
2307 :param revisions: filter query by revisions only
2307 :param revisions: filter query by revisions only
2308 """
2308 """
2309 cmts = ChangesetComment.query()\
2309 cmts = ChangesetComment.query()\
2310 .filter(ChangesetComment.repo == self)
2310 .filter(ChangesetComment.repo == self)
2311 if revisions:
2311 if revisions:
2312 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2312 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2313 grouped = collections.defaultdict(list)
2313 grouped = collections.defaultdict(list)
2314 for cmt in cmts.all():
2314 for cmt in cmts.all():
2315 grouped[cmt.revision].append(cmt)
2315 grouped[cmt.revision].append(cmt)
2316 return grouped
2316 return grouped
2317
2317
2318 def statuses(self, revisions=None):
2318 def statuses(self, revisions=None):
2319 """
2319 """
2320 Returns statuses for this repository
2320 Returns statuses for this repository
2321
2321
2322 :param revisions: list of revisions to get statuses for
2322 :param revisions: list of revisions to get statuses for
2323 """
2323 """
2324 statuses = ChangesetStatus.query()\
2324 statuses = ChangesetStatus.query()\
2325 .filter(ChangesetStatus.repo == self)\
2325 .filter(ChangesetStatus.repo == self)\
2326 .filter(ChangesetStatus.version == 0)
2326 .filter(ChangesetStatus.version == 0)
2327
2327
2328 if revisions:
2328 if revisions:
2329 # Try doing the filtering in chunks to avoid hitting limits
2329 # Try doing the filtering in chunks to avoid hitting limits
2330 size = 500
2330 size = 500
2331 status_results = []
2331 status_results = []
2332 for chunk in xrange(0, len(revisions), size):
2332 for chunk in xrange(0, len(revisions), size):
2333 status_results += statuses.filter(
2333 status_results += statuses.filter(
2334 ChangesetStatus.revision.in_(
2334 ChangesetStatus.revision.in_(
2335 revisions[chunk: chunk+size])
2335 revisions[chunk: chunk+size])
2336 ).all()
2336 ).all()
2337 else:
2337 else:
2338 status_results = statuses.all()
2338 status_results = statuses.all()
2339
2339
2340 grouped = {}
2340 grouped = {}
2341
2341
2342 # maybe we have open new pullrequest without a status?
2342 # maybe we have open new pullrequest without a status?
2343 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2343 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2344 status_lbl = ChangesetStatus.get_status_lbl(stat)
2344 status_lbl = ChangesetStatus.get_status_lbl(stat)
2345 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2345 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2346 for rev in pr.revisions:
2346 for rev in pr.revisions:
2347 pr_id = pr.pull_request_id
2347 pr_id = pr.pull_request_id
2348 pr_repo = pr.target_repo.repo_name
2348 pr_repo = pr.target_repo.repo_name
2349 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2349 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2350
2350
2351 for stat in status_results:
2351 for stat in status_results:
2352 pr_id = pr_repo = None
2352 pr_id = pr_repo = None
2353 if stat.pull_request:
2353 if stat.pull_request:
2354 pr_id = stat.pull_request.pull_request_id
2354 pr_id = stat.pull_request.pull_request_id
2355 pr_repo = stat.pull_request.target_repo.repo_name
2355 pr_repo = stat.pull_request.target_repo.repo_name
2356 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2356 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2357 pr_id, pr_repo]
2357 pr_id, pr_repo]
2358 return grouped
2358 return grouped
2359
2359
2360 # ==========================================================================
2360 # ==========================================================================
2361 # SCM CACHE INSTANCE
2361 # SCM CACHE INSTANCE
2362 # ==========================================================================
2362 # ==========================================================================
2363
2363
2364 def scm_instance(self, **kwargs):
2364 def scm_instance(self, **kwargs):
2365 import rhodecode
2365 import rhodecode
2366
2366
2367 # Passing a config will not hit the cache currently only used
2367 # Passing a config will not hit the cache currently only used
2368 # for repo2dbmapper
2368 # for repo2dbmapper
2369 config = kwargs.pop('config', None)
2369 config = kwargs.pop('config', None)
2370 cache = kwargs.pop('cache', None)
2370 cache = kwargs.pop('cache', None)
2371 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2371 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2372 # if cache is NOT defined use default global, else we have a full
2372 # if cache is NOT defined use default global, else we have a full
2373 # control over cache behaviour
2373 # control over cache behaviour
2374 if cache is None and full_cache and not config:
2374 if cache is None and full_cache and not config:
2375 return self._get_instance_cached()
2375 return self._get_instance_cached()
2376 return self._get_instance(cache=bool(cache), config=config)
2376 return self._get_instance(cache=bool(cache), config=config)
2377
2377
2378 def _get_instance_cached(self):
2378 def _get_instance_cached(self):
2379 from rhodecode.lib import rc_cache
2379 from rhodecode.lib import rc_cache
2380
2380
2381 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2381 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2382 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2382 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2383 repo_id=self.repo_id)
2383 repo_id=self.repo_id)
2384 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2384 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2385
2385
2386 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2386 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2387 def get_instance_cached(repo_id, context_id):
2387 def get_instance_cached(repo_id, context_id):
2388 return self._get_instance()
2388 return self._get_instance()
2389
2389
2390 # we must use thread scoped cache here,
2390 # we must use thread scoped cache here,
2391 # because each thread of gevent needs it's own not shared connection and cache
2391 # because each thread of gevent needs it's own not shared connection and cache
2392 # we also alter `args` so the cache key is individual for every green thread.
2392 # we also alter `args` so the cache key is individual for every green thread.
2393 inv_context_manager = rc_cache.InvalidationContext(
2393 inv_context_manager = rc_cache.InvalidationContext(
2394 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2394 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2395 thread_scoped=True)
2395 thread_scoped=True)
2396 with inv_context_manager as invalidation_context:
2396 with inv_context_manager as invalidation_context:
2397 args = (self.repo_id, inv_context_manager.cache_key)
2397 args = (self.repo_id, inv_context_manager.cache_key)
2398 # re-compute and store cache if we get invalidate signal
2398 # re-compute and store cache if we get invalidate signal
2399 if invalidation_context.should_invalidate():
2399 if invalidation_context.should_invalidate():
2400 instance = get_instance_cached.refresh(*args)
2400 instance = get_instance_cached.refresh(*args)
2401 else:
2401 else:
2402 instance = get_instance_cached(*args)
2402 instance = get_instance_cached(*args)
2403
2403
2404 log.debug(
2404 log.debug(
2405 'Repo instance fetched in %.3fs', inv_context_manager.compute_time)
2405 'Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2406 return instance
2406 return instance
2407
2407
2408 def _get_instance(self, cache=True, config=None):
2408 def _get_instance(self, cache=True, config=None):
2409 config = config or self._config
2409 config = config or self._config
2410 custom_wire = {
2410 custom_wire = {
2411 'cache': cache # controls the vcs.remote cache
2411 'cache': cache # controls the vcs.remote cache
2412 }
2412 }
2413 repo = get_vcs_instance(
2413 repo = get_vcs_instance(
2414 repo_path=safe_str(self.repo_full_path),
2414 repo_path=safe_str(self.repo_full_path),
2415 config=config,
2415 config=config,
2416 with_wire=custom_wire,
2416 with_wire=custom_wire,
2417 create=False,
2417 create=False,
2418 _vcs_alias=self.repo_type)
2418 _vcs_alias=self.repo_type)
2419
2419
2420 return repo
2420 return repo
2421
2421
2422 def __json__(self):
2422 def __json__(self):
2423 return {'landing_rev': self.landing_rev}
2423 return {'landing_rev': self.landing_rev}
2424
2424
2425 def get_dict(self):
2425 def get_dict(self):
2426
2426
2427 # Since we transformed `repo_name` to a hybrid property, we need to
2427 # Since we transformed `repo_name` to a hybrid property, we need to
2428 # keep compatibility with the code which uses `repo_name` field.
2428 # keep compatibility with the code which uses `repo_name` field.
2429
2429
2430 result = super(Repository, self).get_dict()
2430 result = super(Repository, self).get_dict()
2431 result['repo_name'] = result.pop('_repo_name', None)
2431 result['repo_name'] = result.pop('_repo_name', None)
2432 return result
2432 return result
2433
2433
2434
2434
2435 class RepoGroup(Base, BaseModel):
2435 class RepoGroup(Base, BaseModel):
2436 __tablename__ = 'groups'
2436 __tablename__ = 'groups'
2437 __table_args__ = (
2437 __table_args__ = (
2438 UniqueConstraint('group_name', 'group_parent_id'),
2438 UniqueConstraint('group_name', 'group_parent_id'),
2439 base_table_args,
2439 base_table_args,
2440 )
2440 )
2441 __mapper_args__ = {'order_by': 'group_name'}
2441 __mapper_args__ = {'order_by': 'group_name'}
2442
2442
2443 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2443 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2444
2444
2445 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2445 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2446 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2446 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2447 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2447 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2448 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2448 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2449 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2449 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2450 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2450 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2451 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2451 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2452 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2452 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2453 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2453 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2454
2454
2455 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2455 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2456 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2456 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2457 parent_group = relationship('RepoGroup', remote_side=group_id)
2457 parent_group = relationship('RepoGroup', remote_side=group_id)
2458 user = relationship('User')
2458 user = relationship('User')
2459 integrations = relationship('Integration',
2459 integrations = relationship('Integration',
2460 cascade="all, delete, delete-orphan")
2460 cascade="all, delete, delete-orphan")
2461
2461
2462 def __init__(self, group_name='', parent_group=None):
2462 def __init__(self, group_name='', parent_group=None):
2463 self.group_name = group_name
2463 self.group_name = group_name
2464 self.parent_group = parent_group
2464 self.parent_group = parent_group
2465
2465
2466 def __unicode__(self):
2466 def __unicode__(self):
2467 return u"<%s('id:%s:%s')>" % (
2467 return u"<%s('id:%s:%s')>" % (
2468 self.__class__.__name__, self.group_id, self.group_name)
2468 self.__class__.__name__, self.group_id, self.group_name)
2469
2469
2470 @hybrid_property
2470 @hybrid_property
2471 def description_safe(self):
2471 def description_safe(self):
2472 from rhodecode.lib import helpers as h
2472 from rhodecode.lib import helpers as h
2473 return h.escape(self.group_description)
2473 return h.escape(self.group_description)
2474
2474
2475 @classmethod
2475 @classmethod
2476 def _generate_choice(cls, repo_group):
2476 def _generate_choice(cls, repo_group):
2477 from webhelpers.html import literal as _literal
2477 from webhelpers.html import literal as _literal
2478 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2478 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2479 return repo_group.group_id, _name(repo_group.full_path_splitted)
2479 return repo_group.group_id, _name(repo_group.full_path_splitted)
2480
2480
2481 @classmethod
2481 @classmethod
2482 def groups_choices(cls, groups=None, show_empty_group=True):
2482 def groups_choices(cls, groups=None, show_empty_group=True):
2483 if not groups:
2483 if not groups:
2484 groups = cls.query().all()
2484 groups = cls.query().all()
2485
2485
2486 repo_groups = []
2486 repo_groups = []
2487 if show_empty_group:
2487 if show_empty_group:
2488 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2488 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2489
2489
2490 repo_groups.extend([cls._generate_choice(x) for x in groups])
2490 repo_groups.extend([cls._generate_choice(x) for x in groups])
2491
2491
2492 repo_groups = sorted(
2492 repo_groups = sorted(
2493 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2493 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2494 return repo_groups
2494 return repo_groups
2495
2495
2496 @classmethod
2496 @classmethod
2497 def url_sep(cls):
2497 def url_sep(cls):
2498 return URL_SEP
2498 return URL_SEP
2499
2499
2500 @classmethod
2500 @classmethod
2501 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2501 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2502 if case_insensitive:
2502 if case_insensitive:
2503 gr = cls.query().filter(func.lower(cls.group_name)
2503 gr = cls.query().filter(func.lower(cls.group_name)
2504 == func.lower(group_name))
2504 == func.lower(group_name))
2505 else:
2505 else:
2506 gr = cls.query().filter(cls.group_name == group_name)
2506 gr = cls.query().filter(cls.group_name == group_name)
2507 if cache:
2507 if cache:
2508 name_key = _hash_key(group_name)
2508 name_key = _hash_key(group_name)
2509 gr = gr.options(
2509 gr = gr.options(
2510 FromCache("sql_cache_short", "get_group_%s" % name_key))
2510 FromCache("sql_cache_short", "get_group_%s" % name_key))
2511 return gr.scalar()
2511 return gr.scalar()
2512
2512
2513 @classmethod
2513 @classmethod
2514 def get_user_personal_repo_group(cls, user_id):
2514 def get_user_personal_repo_group(cls, user_id):
2515 user = User.get(user_id)
2515 user = User.get(user_id)
2516 if user.username == User.DEFAULT_USER:
2516 if user.username == User.DEFAULT_USER:
2517 return None
2517 return None
2518
2518
2519 return cls.query()\
2519 return cls.query()\
2520 .filter(cls.personal == true()) \
2520 .filter(cls.personal == true()) \
2521 .filter(cls.user == user) \
2521 .filter(cls.user == user) \
2522 .order_by(cls.group_id.asc()) \
2522 .order_by(cls.group_id.asc()) \
2523 .first()
2523 .first()
2524
2524
2525 @classmethod
2525 @classmethod
2526 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2526 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2527 case_insensitive=True):
2527 case_insensitive=True):
2528 q = RepoGroup.query()
2528 q = RepoGroup.query()
2529
2529
2530 if not isinstance(user_id, Optional):
2530 if not isinstance(user_id, Optional):
2531 q = q.filter(RepoGroup.user_id == user_id)
2531 q = q.filter(RepoGroup.user_id == user_id)
2532
2532
2533 if not isinstance(group_id, Optional):
2533 if not isinstance(group_id, Optional):
2534 q = q.filter(RepoGroup.group_parent_id == group_id)
2534 q = q.filter(RepoGroup.group_parent_id == group_id)
2535
2535
2536 if case_insensitive:
2536 if case_insensitive:
2537 q = q.order_by(func.lower(RepoGroup.group_name))
2537 q = q.order_by(func.lower(RepoGroup.group_name))
2538 else:
2538 else:
2539 q = q.order_by(RepoGroup.group_name)
2539 q = q.order_by(RepoGroup.group_name)
2540 return q.all()
2540 return q.all()
2541
2541
2542 @property
2542 @property
2543 def parents(self):
2543 def parents(self):
2544 parents_recursion_limit = 10
2544 parents_recursion_limit = 10
2545 groups = []
2545 groups = []
2546 if self.parent_group is None:
2546 if self.parent_group is None:
2547 return groups
2547 return groups
2548 cur_gr = self.parent_group
2548 cur_gr = self.parent_group
2549 groups.insert(0, cur_gr)
2549 groups.insert(0, cur_gr)
2550 cnt = 0
2550 cnt = 0
2551 while 1:
2551 while 1:
2552 cnt += 1
2552 cnt += 1
2553 gr = getattr(cur_gr, 'parent_group', None)
2553 gr = getattr(cur_gr, 'parent_group', None)
2554 cur_gr = cur_gr.parent_group
2554 cur_gr = cur_gr.parent_group
2555 if gr is None:
2555 if gr is None:
2556 break
2556 break
2557 if cnt == parents_recursion_limit:
2557 if cnt == parents_recursion_limit:
2558 # this will prevent accidental infinit loops
2558 # this will prevent accidental infinit loops
2559 log.error('more than %s parents found for group %s, stopping '
2559 log.error('more than %s parents found for group %s, stopping '
2560 'recursive parent fetching', parents_recursion_limit, self)
2560 'recursive parent fetching', parents_recursion_limit, self)
2561 break
2561 break
2562
2562
2563 groups.insert(0, gr)
2563 groups.insert(0, gr)
2564 return groups
2564 return groups
2565
2565
2566 @property
2566 @property
2567 def last_db_change(self):
2567 def last_db_change(self):
2568 return self.updated_on
2568 return self.updated_on
2569
2569
2570 @property
2570 @property
2571 def children(self):
2571 def children(self):
2572 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2572 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2573
2573
2574 @property
2574 @property
2575 def name(self):
2575 def name(self):
2576 return self.group_name.split(RepoGroup.url_sep())[-1]
2576 return self.group_name.split(RepoGroup.url_sep())[-1]
2577
2577
2578 @property
2578 @property
2579 def full_path(self):
2579 def full_path(self):
2580 return self.group_name
2580 return self.group_name
2581
2581
2582 @property
2582 @property
2583 def full_path_splitted(self):
2583 def full_path_splitted(self):
2584 return self.group_name.split(RepoGroup.url_sep())
2584 return self.group_name.split(RepoGroup.url_sep())
2585
2585
2586 @property
2586 @property
2587 def repositories(self):
2587 def repositories(self):
2588 return Repository.query()\
2588 return Repository.query()\
2589 .filter(Repository.group == self)\
2589 .filter(Repository.group == self)\
2590 .order_by(Repository.repo_name)
2590 .order_by(Repository.repo_name)
2591
2591
2592 @property
2592 @property
2593 def repositories_recursive_count(self):
2593 def repositories_recursive_count(self):
2594 cnt = self.repositories.count()
2594 cnt = self.repositories.count()
2595
2595
2596 def children_count(group):
2596 def children_count(group):
2597 cnt = 0
2597 cnt = 0
2598 for child in group.children:
2598 for child in group.children:
2599 cnt += child.repositories.count()
2599 cnt += child.repositories.count()
2600 cnt += children_count(child)
2600 cnt += children_count(child)
2601 return cnt
2601 return cnt
2602
2602
2603 return cnt + children_count(self)
2603 return cnt + children_count(self)
2604
2604
2605 def _recursive_objects(self, include_repos=True):
2605 def _recursive_objects(self, include_repos=True):
2606 all_ = []
2606 all_ = []
2607
2607
2608 def _get_members(root_gr):
2608 def _get_members(root_gr):
2609 if include_repos:
2609 if include_repos:
2610 for r in root_gr.repositories:
2610 for r in root_gr.repositories:
2611 all_.append(r)
2611 all_.append(r)
2612 childs = root_gr.children.all()
2612 childs = root_gr.children.all()
2613 if childs:
2613 if childs:
2614 for gr in childs:
2614 for gr in childs:
2615 all_.append(gr)
2615 all_.append(gr)
2616 _get_members(gr)
2616 _get_members(gr)
2617
2617
2618 _get_members(self)
2618 _get_members(self)
2619 return [self] + all_
2619 return [self] + all_
2620
2620
2621 def recursive_groups_and_repos(self):
2621 def recursive_groups_and_repos(self):
2622 """
2622 """
2623 Recursive return all groups, with repositories in those groups
2623 Recursive return all groups, with repositories in those groups
2624 """
2624 """
2625 return self._recursive_objects()
2625 return self._recursive_objects()
2626
2626
2627 def recursive_groups(self):
2627 def recursive_groups(self):
2628 """
2628 """
2629 Returns all children groups for this group including children of children
2629 Returns all children groups for this group including children of children
2630 """
2630 """
2631 return self._recursive_objects(include_repos=False)
2631 return self._recursive_objects(include_repos=False)
2632
2632
2633 def get_new_name(self, group_name):
2633 def get_new_name(self, group_name):
2634 """
2634 """
2635 returns new full group name based on parent and new name
2635 returns new full group name based on parent and new name
2636
2636
2637 :param group_name:
2637 :param group_name:
2638 """
2638 """
2639 path_prefix = (self.parent_group.full_path_splitted if
2639 path_prefix = (self.parent_group.full_path_splitted if
2640 self.parent_group else [])
2640 self.parent_group else [])
2641 return RepoGroup.url_sep().join(path_prefix + [group_name])
2641 return RepoGroup.url_sep().join(path_prefix + [group_name])
2642
2642
2643 def permissions(self, with_admins=True, with_owner=True):
2643 def permissions(self, with_admins=True, with_owner=True):
2644 """
2644 """
2645 Permissions for repository groups
2645 Permissions for repository groups
2646 """
2646 """
2647 _admin_perm = 'group.admin'
2647 _admin_perm = 'group.admin'
2648
2648
2649 owner_row = []
2649 owner_row = []
2650 if with_owner:
2650 if with_owner:
2651 usr = AttributeDict(self.user.get_dict())
2651 usr = AttributeDict(self.user.get_dict())
2652 usr.owner_row = True
2652 usr.owner_row = True
2653 usr.permission = _admin_perm
2653 usr.permission = _admin_perm
2654 owner_row.append(usr)
2654 owner_row.append(usr)
2655
2655
2656 super_admin_ids = []
2656 super_admin_ids = []
2657 super_admin_rows = []
2657 super_admin_rows = []
2658 if with_admins:
2658 if with_admins:
2659 for usr in User.get_all_super_admins():
2659 for usr in User.get_all_super_admins():
2660 super_admin_ids.append(usr.user_id)
2660 super_admin_ids.append(usr.user_id)
2661 # if this admin is also owner, don't double the record
2661 # if this admin is also owner, don't double the record
2662 if usr.user_id == owner_row[0].user_id:
2662 if usr.user_id == owner_row[0].user_id:
2663 owner_row[0].admin_row = True
2663 owner_row[0].admin_row = True
2664 else:
2664 else:
2665 usr = AttributeDict(usr.get_dict())
2665 usr = AttributeDict(usr.get_dict())
2666 usr.admin_row = True
2666 usr.admin_row = True
2667 usr.permission = _admin_perm
2667 usr.permission = _admin_perm
2668 super_admin_rows.append(usr)
2668 super_admin_rows.append(usr)
2669
2669
2670 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2670 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2671 q = q.options(joinedload(UserRepoGroupToPerm.group),
2671 q = q.options(joinedload(UserRepoGroupToPerm.group),
2672 joinedload(UserRepoGroupToPerm.user),
2672 joinedload(UserRepoGroupToPerm.user),
2673 joinedload(UserRepoGroupToPerm.permission),)
2673 joinedload(UserRepoGroupToPerm.permission),)
2674
2674
2675 # get owners and admins and permissions. We do a trick of re-writing
2675 # get owners and admins and permissions. We do a trick of re-writing
2676 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2676 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2677 # has a global reference and changing one object propagates to all
2677 # has a global reference and changing one object propagates to all
2678 # others. This means if admin is also an owner admin_row that change
2678 # others. This means if admin is also an owner admin_row that change
2679 # would propagate to both objects
2679 # would propagate to both objects
2680 perm_rows = []
2680 perm_rows = []
2681 for _usr in q.all():
2681 for _usr in q.all():
2682 usr = AttributeDict(_usr.user.get_dict())
2682 usr = AttributeDict(_usr.user.get_dict())
2683 # if this user is also owner/admin, mark as duplicate record
2683 # if this user is also owner/admin, mark as duplicate record
2684 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2684 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2685 usr.duplicate_perm = True
2685 usr.duplicate_perm = True
2686 usr.permission = _usr.permission.permission_name
2686 usr.permission = _usr.permission.permission_name
2687 perm_rows.append(usr)
2687 perm_rows.append(usr)
2688
2688
2689 # filter the perm rows by 'default' first and then sort them by
2689 # filter the perm rows by 'default' first and then sort them by
2690 # admin,write,read,none permissions sorted again alphabetically in
2690 # admin,write,read,none permissions sorted again alphabetically in
2691 # each group
2691 # each group
2692 perm_rows = sorted(perm_rows, key=display_user_sort)
2692 perm_rows = sorted(perm_rows, key=display_user_sort)
2693
2693
2694 return super_admin_rows + owner_row + perm_rows
2694 return super_admin_rows + owner_row + perm_rows
2695
2695
2696 def permission_user_groups(self):
2696 def permission_user_groups(self):
2697 q = UserGroupRepoGroupToPerm.query().filter(
2697 q = UserGroupRepoGroupToPerm.query().filter(
2698 UserGroupRepoGroupToPerm.group == self)
2698 UserGroupRepoGroupToPerm.group == self)
2699 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2699 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2700 joinedload(UserGroupRepoGroupToPerm.users_group),
2700 joinedload(UserGroupRepoGroupToPerm.users_group),
2701 joinedload(UserGroupRepoGroupToPerm.permission),)
2701 joinedload(UserGroupRepoGroupToPerm.permission),)
2702
2702
2703 perm_rows = []
2703 perm_rows = []
2704 for _user_group in q.all():
2704 for _user_group in q.all():
2705 usr = AttributeDict(_user_group.users_group.get_dict())
2705 usr = AttributeDict(_user_group.users_group.get_dict())
2706 usr.permission = _user_group.permission.permission_name
2706 usr.permission = _user_group.permission.permission_name
2707 perm_rows.append(usr)
2707 perm_rows.append(usr)
2708
2708
2709 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2709 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2710 return perm_rows
2710 return perm_rows
2711
2711
2712 def get_api_data(self):
2712 def get_api_data(self):
2713 """
2713 """
2714 Common function for generating api data
2714 Common function for generating api data
2715
2715
2716 """
2716 """
2717 group = self
2717 group = self
2718 data = {
2718 data = {
2719 'group_id': group.group_id,
2719 'group_id': group.group_id,
2720 'group_name': group.group_name,
2720 'group_name': group.group_name,
2721 'group_description': group.description_safe,
2721 'group_description': group.description_safe,
2722 'parent_group': group.parent_group.group_name if group.parent_group else None,
2722 'parent_group': group.parent_group.group_name if group.parent_group else None,
2723 'repositories': [x.repo_name for x in group.repositories],
2723 'repositories': [x.repo_name for x in group.repositories],
2724 'owner': group.user.username,
2724 'owner': group.user.username,
2725 }
2725 }
2726 return data
2726 return data
2727
2727
2728
2728
2729 class Permission(Base, BaseModel):
2729 class Permission(Base, BaseModel):
2730 __tablename__ = 'permissions'
2730 __tablename__ = 'permissions'
2731 __table_args__ = (
2731 __table_args__ = (
2732 Index('p_perm_name_idx', 'permission_name'),
2732 Index('p_perm_name_idx', 'permission_name'),
2733 base_table_args,
2733 base_table_args,
2734 )
2734 )
2735
2735
2736 PERMS = [
2736 PERMS = [
2737 ('hg.admin', _('RhodeCode Super Administrator')),
2737 ('hg.admin', _('RhodeCode Super Administrator')),
2738
2738
2739 ('repository.none', _('Repository no access')),
2739 ('repository.none', _('Repository no access')),
2740 ('repository.read', _('Repository read access')),
2740 ('repository.read', _('Repository read access')),
2741 ('repository.write', _('Repository write access')),
2741 ('repository.write', _('Repository write access')),
2742 ('repository.admin', _('Repository admin access')),
2742 ('repository.admin', _('Repository admin access')),
2743
2743
2744 ('group.none', _('Repository group no access')),
2744 ('group.none', _('Repository group no access')),
2745 ('group.read', _('Repository group read access')),
2745 ('group.read', _('Repository group read access')),
2746 ('group.write', _('Repository group write access')),
2746 ('group.write', _('Repository group write access')),
2747 ('group.admin', _('Repository group admin access')),
2747 ('group.admin', _('Repository group admin access')),
2748
2748
2749 ('usergroup.none', _('User group no access')),
2749 ('usergroup.none', _('User group no access')),
2750 ('usergroup.read', _('User group read access')),
2750 ('usergroup.read', _('User group read access')),
2751 ('usergroup.write', _('User group write access')),
2751 ('usergroup.write', _('User group write access')),
2752 ('usergroup.admin', _('User group admin access')),
2752 ('usergroup.admin', _('User group admin access')),
2753
2753
2754 ('branch.none', _('Branch no permissions')),
2754 ('branch.none', _('Branch no permissions')),
2755 ('branch.merge', _('Branch access by web merge')),
2755 ('branch.merge', _('Branch access by web merge')),
2756 ('branch.push', _('Branch access by push')),
2756 ('branch.push', _('Branch access by push')),
2757 ('branch.push_force', _('Branch access by push with force')),
2757 ('branch.push_force', _('Branch access by push with force')),
2758
2758
2759 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2759 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2760 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2760 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2761
2761
2762 ('hg.usergroup.create.false', _('User Group creation disabled')),
2762 ('hg.usergroup.create.false', _('User Group creation disabled')),
2763 ('hg.usergroup.create.true', _('User Group creation enabled')),
2763 ('hg.usergroup.create.true', _('User Group creation enabled')),
2764
2764
2765 ('hg.create.none', _('Repository creation disabled')),
2765 ('hg.create.none', _('Repository creation disabled')),
2766 ('hg.create.repository', _('Repository creation enabled')),
2766 ('hg.create.repository', _('Repository creation enabled')),
2767 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2767 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2768 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2768 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2769
2769
2770 ('hg.fork.none', _('Repository forking disabled')),
2770 ('hg.fork.none', _('Repository forking disabled')),
2771 ('hg.fork.repository', _('Repository forking enabled')),
2771 ('hg.fork.repository', _('Repository forking enabled')),
2772
2772
2773 ('hg.register.none', _('Registration disabled')),
2773 ('hg.register.none', _('Registration disabled')),
2774 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2774 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2775 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2775 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2776
2776
2777 ('hg.password_reset.enabled', _('Password reset enabled')),
2777 ('hg.password_reset.enabled', _('Password reset enabled')),
2778 ('hg.password_reset.hidden', _('Password reset hidden')),
2778 ('hg.password_reset.hidden', _('Password reset hidden')),
2779 ('hg.password_reset.disabled', _('Password reset disabled')),
2779 ('hg.password_reset.disabled', _('Password reset disabled')),
2780
2780
2781 ('hg.extern_activate.manual', _('Manual activation of external account')),
2781 ('hg.extern_activate.manual', _('Manual activation of external account')),
2782 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2782 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2783
2783
2784 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2784 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2785 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2785 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2786 ]
2786 ]
2787
2787
2788 # definition of system default permissions for DEFAULT user, created on
2788 # definition of system default permissions for DEFAULT user, created on
2789 # system setup
2789 # system setup
2790 DEFAULT_USER_PERMISSIONS = [
2790 DEFAULT_USER_PERMISSIONS = [
2791 # object perms
2791 # object perms
2792 'repository.read',
2792 'repository.read',
2793 'group.read',
2793 'group.read',
2794 'usergroup.read',
2794 'usergroup.read',
2795 # branch, for backward compat we need same value as before so forced pushed
2795 # branch, for backward compat we need same value as before so forced pushed
2796 'branch.push_force',
2796 'branch.push_force',
2797 # global
2797 # global
2798 'hg.create.repository',
2798 'hg.create.repository',
2799 'hg.repogroup.create.false',
2799 'hg.repogroup.create.false',
2800 'hg.usergroup.create.false',
2800 'hg.usergroup.create.false',
2801 'hg.create.write_on_repogroup.true',
2801 'hg.create.write_on_repogroup.true',
2802 'hg.fork.repository',
2802 'hg.fork.repository',
2803 'hg.register.manual_activate',
2803 'hg.register.manual_activate',
2804 'hg.password_reset.enabled',
2804 'hg.password_reset.enabled',
2805 'hg.extern_activate.auto',
2805 'hg.extern_activate.auto',
2806 'hg.inherit_default_perms.true',
2806 'hg.inherit_default_perms.true',
2807 ]
2807 ]
2808
2808
2809 # defines which permissions are more important higher the more important
2809 # defines which permissions are more important higher the more important
2810 # Weight defines which permissions are more important.
2810 # Weight defines which permissions are more important.
2811 # The higher number the more important.
2811 # The higher number the more important.
2812 PERM_WEIGHTS = {
2812 PERM_WEIGHTS = {
2813 'repository.none': 0,
2813 'repository.none': 0,
2814 'repository.read': 1,
2814 'repository.read': 1,
2815 'repository.write': 3,
2815 'repository.write': 3,
2816 'repository.admin': 4,
2816 'repository.admin': 4,
2817
2817
2818 'group.none': 0,
2818 'group.none': 0,
2819 'group.read': 1,
2819 'group.read': 1,
2820 'group.write': 3,
2820 'group.write': 3,
2821 'group.admin': 4,
2821 'group.admin': 4,
2822
2822
2823 'usergroup.none': 0,
2823 'usergroup.none': 0,
2824 'usergroup.read': 1,
2824 'usergroup.read': 1,
2825 'usergroup.write': 3,
2825 'usergroup.write': 3,
2826 'usergroup.admin': 4,
2826 'usergroup.admin': 4,
2827
2827
2828 'branch.none': 0,
2828 'branch.none': 0,
2829 'branch.merge': 1,
2829 'branch.merge': 1,
2830 'branch.push': 3,
2830 'branch.push': 3,
2831 'branch.push_force': 4,
2831 'branch.push_force': 4,
2832
2832
2833 'hg.repogroup.create.false': 0,
2833 'hg.repogroup.create.false': 0,
2834 'hg.repogroup.create.true': 1,
2834 'hg.repogroup.create.true': 1,
2835
2835
2836 'hg.usergroup.create.false': 0,
2836 'hg.usergroup.create.false': 0,
2837 'hg.usergroup.create.true': 1,
2837 'hg.usergroup.create.true': 1,
2838
2838
2839 'hg.fork.none': 0,
2839 'hg.fork.none': 0,
2840 'hg.fork.repository': 1,
2840 'hg.fork.repository': 1,
2841 'hg.create.none': 0,
2841 'hg.create.none': 0,
2842 'hg.create.repository': 1
2842 'hg.create.repository': 1
2843 }
2843 }
2844
2844
2845 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2845 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2846 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2846 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2847 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2847 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2848
2848
2849 def __unicode__(self):
2849 def __unicode__(self):
2850 return u"<%s('%s:%s')>" % (
2850 return u"<%s('%s:%s')>" % (
2851 self.__class__.__name__, self.permission_id, self.permission_name
2851 self.__class__.__name__, self.permission_id, self.permission_name
2852 )
2852 )
2853
2853
2854 @classmethod
2854 @classmethod
2855 def get_by_key(cls, key):
2855 def get_by_key(cls, key):
2856 return cls.query().filter(cls.permission_name == key).scalar()
2856 return cls.query().filter(cls.permission_name == key).scalar()
2857
2857
2858 @classmethod
2858 @classmethod
2859 def get_default_repo_perms(cls, user_id, repo_id=None):
2859 def get_default_repo_perms(cls, user_id, repo_id=None):
2860 q = Session().query(UserRepoToPerm, Repository, Permission)\
2860 q = Session().query(UserRepoToPerm, Repository, Permission)\
2861 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2861 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2862 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2862 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2863 .filter(UserRepoToPerm.user_id == user_id)
2863 .filter(UserRepoToPerm.user_id == user_id)
2864 if repo_id:
2864 if repo_id:
2865 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2865 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2866 return q.all()
2866 return q.all()
2867
2867
2868 @classmethod
2868 @classmethod
2869 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2869 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2870 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2870 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2871 .join(
2871 .join(
2872 Permission,
2872 Permission,
2873 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2873 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2874 .join(
2874 .join(
2875 UserRepoToPerm,
2875 UserRepoToPerm,
2876 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2876 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2877 .filter(UserRepoToPerm.user_id == user_id)
2877 .filter(UserRepoToPerm.user_id == user_id)
2878
2878
2879 if repo_id:
2879 if repo_id:
2880 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2880 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2881 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2881 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2882
2882
2883 @classmethod
2883 @classmethod
2884 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2884 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2885 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2885 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2886 .join(
2886 .join(
2887 Permission,
2887 Permission,
2888 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2888 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2889 .join(
2889 .join(
2890 Repository,
2890 Repository,
2891 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2891 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2892 .join(
2892 .join(
2893 UserGroup,
2893 UserGroup,
2894 UserGroupRepoToPerm.users_group_id ==
2894 UserGroupRepoToPerm.users_group_id ==
2895 UserGroup.users_group_id)\
2895 UserGroup.users_group_id)\
2896 .join(
2896 .join(
2897 UserGroupMember,
2897 UserGroupMember,
2898 UserGroupRepoToPerm.users_group_id ==
2898 UserGroupRepoToPerm.users_group_id ==
2899 UserGroupMember.users_group_id)\
2899 UserGroupMember.users_group_id)\
2900 .filter(
2900 .filter(
2901 UserGroupMember.user_id == user_id,
2901 UserGroupMember.user_id == user_id,
2902 UserGroup.users_group_active == true())
2902 UserGroup.users_group_active == true())
2903 if repo_id:
2903 if repo_id:
2904 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2904 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2905 return q.all()
2905 return q.all()
2906
2906
2907 @classmethod
2907 @classmethod
2908 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2908 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2909 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2909 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2910 .join(
2910 .join(
2911 Permission,
2911 Permission,
2912 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2912 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2913 .join(
2913 .join(
2914 UserGroupRepoToPerm,
2914 UserGroupRepoToPerm,
2915 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2915 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2916 .join(
2916 .join(
2917 UserGroup,
2917 UserGroup,
2918 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2918 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2919 .join(
2919 .join(
2920 UserGroupMember,
2920 UserGroupMember,
2921 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2921 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2922 .filter(
2922 .filter(
2923 UserGroupMember.user_id == user_id,
2923 UserGroupMember.user_id == user_id,
2924 UserGroup.users_group_active == true())
2924 UserGroup.users_group_active == true())
2925
2925
2926 if repo_id:
2926 if repo_id:
2927 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2927 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2928 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2928 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2929
2929
2930 @classmethod
2930 @classmethod
2931 def get_default_group_perms(cls, user_id, repo_group_id=None):
2931 def get_default_group_perms(cls, user_id, repo_group_id=None):
2932 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2932 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2933 .join(
2933 .join(
2934 Permission,
2934 Permission,
2935 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2935 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2936 .join(
2936 .join(
2937 RepoGroup,
2937 RepoGroup,
2938 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2938 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2939 .filter(UserRepoGroupToPerm.user_id == user_id)
2939 .filter(UserRepoGroupToPerm.user_id == user_id)
2940 if repo_group_id:
2940 if repo_group_id:
2941 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2941 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2942 return q.all()
2942 return q.all()
2943
2943
2944 @classmethod
2944 @classmethod
2945 def get_default_group_perms_from_user_group(
2945 def get_default_group_perms_from_user_group(
2946 cls, user_id, repo_group_id=None):
2946 cls, user_id, repo_group_id=None):
2947 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2947 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2948 .join(
2948 .join(
2949 Permission,
2949 Permission,
2950 UserGroupRepoGroupToPerm.permission_id ==
2950 UserGroupRepoGroupToPerm.permission_id ==
2951 Permission.permission_id)\
2951 Permission.permission_id)\
2952 .join(
2952 .join(
2953 RepoGroup,
2953 RepoGroup,
2954 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2954 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2955 .join(
2955 .join(
2956 UserGroup,
2956 UserGroup,
2957 UserGroupRepoGroupToPerm.users_group_id ==
2957 UserGroupRepoGroupToPerm.users_group_id ==
2958 UserGroup.users_group_id)\
2958 UserGroup.users_group_id)\
2959 .join(
2959 .join(
2960 UserGroupMember,
2960 UserGroupMember,
2961 UserGroupRepoGroupToPerm.users_group_id ==
2961 UserGroupRepoGroupToPerm.users_group_id ==
2962 UserGroupMember.users_group_id)\
2962 UserGroupMember.users_group_id)\
2963 .filter(
2963 .filter(
2964 UserGroupMember.user_id == user_id,
2964 UserGroupMember.user_id == user_id,
2965 UserGroup.users_group_active == true())
2965 UserGroup.users_group_active == true())
2966 if repo_group_id:
2966 if repo_group_id:
2967 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2967 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2968 return q.all()
2968 return q.all()
2969
2969
2970 @classmethod
2970 @classmethod
2971 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2971 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2972 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2972 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2973 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2973 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2974 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2974 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2975 .filter(UserUserGroupToPerm.user_id == user_id)
2975 .filter(UserUserGroupToPerm.user_id == user_id)
2976 if user_group_id:
2976 if user_group_id:
2977 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2977 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2978 return q.all()
2978 return q.all()
2979
2979
2980 @classmethod
2980 @classmethod
2981 def get_default_user_group_perms_from_user_group(
2981 def get_default_user_group_perms_from_user_group(
2982 cls, user_id, user_group_id=None):
2982 cls, user_id, user_group_id=None):
2983 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2983 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2984 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2984 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2985 .join(
2985 .join(
2986 Permission,
2986 Permission,
2987 UserGroupUserGroupToPerm.permission_id ==
2987 UserGroupUserGroupToPerm.permission_id ==
2988 Permission.permission_id)\
2988 Permission.permission_id)\
2989 .join(
2989 .join(
2990 TargetUserGroup,
2990 TargetUserGroup,
2991 UserGroupUserGroupToPerm.target_user_group_id ==
2991 UserGroupUserGroupToPerm.target_user_group_id ==
2992 TargetUserGroup.users_group_id)\
2992 TargetUserGroup.users_group_id)\
2993 .join(
2993 .join(
2994 UserGroup,
2994 UserGroup,
2995 UserGroupUserGroupToPerm.user_group_id ==
2995 UserGroupUserGroupToPerm.user_group_id ==
2996 UserGroup.users_group_id)\
2996 UserGroup.users_group_id)\
2997 .join(
2997 .join(
2998 UserGroupMember,
2998 UserGroupMember,
2999 UserGroupUserGroupToPerm.user_group_id ==
2999 UserGroupUserGroupToPerm.user_group_id ==
3000 UserGroupMember.users_group_id)\
3000 UserGroupMember.users_group_id)\
3001 .filter(
3001 .filter(
3002 UserGroupMember.user_id == user_id,
3002 UserGroupMember.user_id == user_id,
3003 UserGroup.users_group_active == true())
3003 UserGroup.users_group_active == true())
3004 if user_group_id:
3004 if user_group_id:
3005 q = q.filter(
3005 q = q.filter(
3006 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3006 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3007
3007
3008 return q.all()
3008 return q.all()
3009
3009
3010
3010
3011 class UserRepoToPerm(Base, BaseModel):
3011 class UserRepoToPerm(Base, BaseModel):
3012 __tablename__ = 'repo_to_perm'
3012 __tablename__ = 'repo_to_perm'
3013 __table_args__ = (
3013 __table_args__ = (
3014 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3014 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3015 base_table_args
3015 base_table_args
3016 )
3016 )
3017
3017
3018 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3018 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3019 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3019 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3020 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3020 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3021 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3021 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3022
3022
3023 user = relationship('User')
3023 user = relationship('User')
3024 repository = relationship('Repository')
3024 repository = relationship('Repository')
3025 permission = relationship('Permission')
3025 permission = relationship('Permission')
3026
3026
3027 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3027 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3028
3028
3029 @classmethod
3029 @classmethod
3030 def create(cls, user, repository, permission):
3030 def create(cls, user, repository, permission):
3031 n = cls()
3031 n = cls()
3032 n.user = user
3032 n.user = user
3033 n.repository = repository
3033 n.repository = repository
3034 n.permission = permission
3034 n.permission = permission
3035 Session().add(n)
3035 Session().add(n)
3036 return n
3036 return n
3037
3037
3038 def __unicode__(self):
3038 def __unicode__(self):
3039 return u'<%s => %s >' % (self.user, self.repository)
3039 return u'<%s => %s >' % (self.user, self.repository)
3040
3040
3041
3041
3042 class UserUserGroupToPerm(Base, BaseModel):
3042 class UserUserGroupToPerm(Base, BaseModel):
3043 __tablename__ = 'user_user_group_to_perm'
3043 __tablename__ = 'user_user_group_to_perm'
3044 __table_args__ = (
3044 __table_args__ = (
3045 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3045 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3046 base_table_args
3046 base_table_args
3047 )
3047 )
3048
3048
3049 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3049 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3050 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3050 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3051 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3051 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3052 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3052 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3053
3053
3054 user = relationship('User')
3054 user = relationship('User')
3055 user_group = relationship('UserGroup')
3055 user_group = relationship('UserGroup')
3056 permission = relationship('Permission')
3056 permission = relationship('Permission')
3057
3057
3058 @classmethod
3058 @classmethod
3059 def create(cls, user, user_group, permission):
3059 def create(cls, user, user_group, permission):
3060 n = cls()
3060 n = cls()
3061 n.user = user
3061 n.user = user
3062 n.user_group = user_group
3062 n.user_group = user_group
3063 n.permission = permission
3063 n.permission = permission
3064 Session().add(n)
3064 Session().add(n)
3065 return n
3065 return n
3066
3066
3067 def __unicode__(self):
3067 def __unicode__(self):
3068 return u'<%s => %s >' % (self.user, self.user_group)
3068 return u'<%s => %s >' % (self.user, self.user_group)
3069
3069
3070
3070
3071 class UserToPerm(Base, BaseModel):
3071 class UserToPerm(Base, BaseModel):
3072 __tablename__ = 'user_to_perm'
3072 __tablename__ = 'user_to_perm'
3073 __table_args__ = (
3073 __table_args__ = (
3074 UniqueConstraint('user_id', 'permission_id'),
3074 UniqueConstraint('user_id', 'permission_id'),
3075 base_table_args
3075 base_table_args
3076 )
3076 )
3077
3077
3078 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3078 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3079 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3079 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3080 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3080 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3081
3081
3082 user = relationship('User')
3082 user = relationship('User')
3083 permission = relationship('Permission', lazy='joined')
3083 permission = relationship('Permission', lazy='joined')
3084
3084
3085 def __unicode__(self):
3085 def __unicode__(self):
3086 return u'<%s => %s >' % (self.user, self.permission)
3086 return u'<%s => %s >' % (self.user, self.permission)
3087
3087
3088
3088
3089 class UserGroupRepoToPerm(Base, BaseModel):
3089 class UserGroupRepoToPerm(Base, BaseModel):
3090 __tablename__ = 'users_group_repo_to_perm'
3090 __tablename__ = 'users_group_repo_to_perm'
3091 __table_args__ = (
3091 __table_args__ = (
3092 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3092 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3093 base_table_args
3093 base_table_args
3094 )
3094 )
3095
3095
3096 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3096 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3097 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3097 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3098 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3098 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3099 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3099 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3100
3100
3101 users_group = relationship('UserGroup')
3101 users_group = relationship('UserGroup')
3102 permission = relationship('Permission')
3102 permission = relationship('Permission')
3103 repository = relationship('Repository')
3103 repository = relationship('Repository')
3104 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3104 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3105
3105
3106 @classmethod
3106 @classmethod
3107 def create(cls, users_group, repository, permission):
3107 def create(cls, users_group, repository, permission):
3108 n = cls()
3108 n = cls()
3109 n.users_group = users_group
3109 n.users_group = users_group
3110 n.repository = repository
3110 n.repository = repository
3111 n.permission = permission
3111 n.permission = permission
3112 Session().add(n)
3112 Session().add(n)
3113 return n
3113 return n
3114
3114
3115 def __unicode__(self):
3115 def __unicode__(self):
3116 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3116 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3117
3117
3118
3118
3119 class UserGroupUserGroupToPerm(Base, BaseModel):
3119 class UserGroupUserGroupToPerm(Base, BaseModel):
3120 __tablename__ = 'user_group_user_group_to_perm'
3120 __tablename__ = 'user_group_user_group_to_perm'
3121 __table_args__ = (
3121 __table_args__ = (
3122 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3122 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3123 CheckConstraint('target_user_group_id != user_group_id'),
3123 CheckConstraint('target_user_group_id != user_group_id'),
3124 base_table_args
3124 base_table_args
3125 )
3125 )
3126
3126
3127 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)
3127 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)
3128 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3128 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3129 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3129 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3130 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3130 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3131
3131
3132 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3132 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3133 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3133 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3134 permission = relationship('Permission')
3134 permission = relationship('Permission')
3135
3135
3136 @classmethod
3136 @classmethod
3137 def create(cls, target_user_group, user_group, permission):
3137 def create(cls, target_user_group, user_group, permission):
3138 n = cls()
3138 n = cls()
3139 n.target_user_group = target_user_group
3139 n.target_user_group = target_user_group
3140 n.user_group = user_group
3140 n.user_group = user_group
3141 n.permission = permission
3141 n.permission = permission
3142 Session().add(n)
3142 Session().add(n)
3143 return n
3143 return n
3144
3144
3145 def __unicode__(self):
3145 def __unicode__(self):
3146 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3146 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3147
3147
3148
3148
3149 class UserGroupToPerm(Base, BaseModel):
3149 class UserGroupToPerm(Base, BaseModel):
3150 __tablename__ = 'users_group_to_perm'
3150 __tablename__ = 'users_group_to_perm'
3151 __table_args__ = (
3151 __table_args__ = (
3152 UniqueConstraint('users_group_id', 'permission_id',),
3152 UniqueConstraint('users_group_id', 'permission_id',),
3153 base_table_args
3153 base_table_args
3154 )
3154 )
3155
3155
3156 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3156 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3157 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3157 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3158 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3158 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3159
3159
3160 users_group = relationship('UserGroup')
3160 users_group = relationship('UserGroup')
3161 permission = relationship('Permission')
3161 permission = relationship('Permission')
3162
3162
3163
3163
3164 class UserRepoGroupToPerm(Base, BaseModel):
3164 class UserRepoGroupToPerm(Base, BaseModel):
3165 __tablename__ = 'user_repo_group_to_perm'
3165 __tablename__ = 'user_repo_group_to_perm'
3166 __table_args__ = (
3166 __table_args__ = (
3167 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3167 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3168 base_table_args
3168 base_table_args
3169 )
3169 )
3170
3170
3171 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3171 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3172 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3172 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3173 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3173 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3174 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3174 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3175
3175
3176 user = relationship('User')
3176 user = relationship('User')
3177 group = relationship('RepoGroup')
3177 group = relationship('RepoGroup')
3178 permission = relationship('Permission')
3178 permission = relationship('Permission')
3179
3179
3180 @classmethod
3180 @classmethod
3181 def create(cls, user, repository_group, permission):
3181 def create(cls, user, repository_group, permission):
3182 n = cls()
3182 n = cls()
3183 n.user = user
3183 n.user = user
3184 n.group = repository_group
3184 n.group = repository_group
3185 n.permission = permission
3185 n.permission = permission
3186 Session().add(n)
3186 Session().add(n)
3187 return n
3187 return n
3188
3188
3189
3189
3190 class UserGroupRepoGroupToPerm(Base, BaseModel):
3190 class UserGroupRepoGroupToPerm(Base, BaseModel):
3191 __tablename__ = 'users_group_repo_group_to_perm'
3191 __tablename__ = 'users_group_repo_group_to_perm'
3192 __table_args__ = (
3192 __table_args__ = (
3193 UniqueConstraint('users_group_id', 'group_id'),
3193 UniqueConstraint('users_group_id', 'group_id'),
3194 base_table_args
3194 base_table_args
3195 )
3195 )
3196
3196
3197 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)
3197 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)
3198 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3198 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3199 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3199 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3200 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3200 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3201
3201
3202 users_group = relationship('UserGroup')
3202 users_group = relationship('UserGroup')
3203 permission = relationship('Permission')
3203 permission = relationship('Permission')
3204 group = relationship('RepoGroup')
3204 group = relationship('RepoGroup')
3205
3205
3206 @classmethod
3206 @classmethod
3207 def create(cls, user_group, repository_group, permission):
3207 def create(cls, user_group, repository_group, permission):
3208 n = cls()
3208 n = cls()
3209 n.users_group = user_group
3209 n.users_group = user_group
3210 n.group = repository_group
3210 n.group = repository_group
3211 n.permission = permission
3211 n.permission = permission
3212 Session().add(n)
3212 Session().add(n)
3213 return n
3213 return n
3214
3214
3215 def __unicode__(self):
3215 def __unicode__(self):
3216 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3216 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3217
3217
3218
3218
3219 class Statistics(Base, BaseModel):
3219 class Statistics(Base, BaseModel):
3220 __tablename__ = 'statistics'
3220 __tablename__ = 'statistics'
3221 __table_args__ = (
3221 __table_args__ = (
3222 base_table_args
3222 base_table_args
3223 )
3223 )
3224
3224
3225 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3225 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3226 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3226 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3227 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3227 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3228 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3228 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3229 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3229 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3230 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3230 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3231
3231
3232 repository = relationship('Repository', single_parent=True)
3232 repository = relationship('Repository', single_parent=True)
3233
3233
3234
3234
3235 class UserFollowing(Base, BaseModel):
3235 class UserFollowing(Base, BaseModel):
3236 __tablename__ = 'user_followings'
3236 __tablename__ = 'user_followings'
3237 __table_args__ = (
3237 __table_args__ = (
3238 UniqueConstraint('user_id', 'follows_repository_id'),
3238 UniqueConstraint('user_id', 'follows_repository_id'),
3239 UniqueConstraint('user_id', 'follows_user_id'),
3239 UniqueConstraint('user_id', 'follows_user_id'),
3240 base_table_args
3240 base_table_args
3241 )
3241 )
3242
3242
3243 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3243 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3244 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3244 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3245 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3245 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3246 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3246 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3247 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3247 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3248
3248
3249 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3249 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3250
3250
3251 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3251 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3252 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3252 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3253
3253
3254 @classmethod
3254 @classmethod
3255 def get_repo_followers(cls, repo_id):
3255 def get_repo_followers(cls, repo_id):
3256 return cls.query().filter(cls.follows_repo_id == repo_id)
3256 return cls.query().filter(cls.follows_repo_id == repo_id)
3257
3257
3258
3258
3259 class CacheKey(Base, BaseModel):
3259 class CacheKey(Base, BaseModel):
3260 __tablename__ = 'cache_invalidation'
3260 __tablename__ = 'cache_invalidation'
3261 __table_args__ = (
3261 __table_args__ = (
3262 UniqueConstraint('cache_key'),
3262 UniqueConstraint('cache_key'),
3263 Index('key_idx', 'cache_key'),
3263 Index('key_idx', 'cache_key'),
3264 base_table_args,
3264 base_table_args,
3265 )
3265 )
3266
3266
3267 CACHE_TYPE_FEED = 'FEED'
3267 CACHE_TYPE_FEED = 'FEED'
3268 CACHE_TYPE_README = 'README'
3268 CACHE_TYPE_README = 'README'
3269 # namespaces used to register process/thread aware caches
3269 # namespaces used to register process/thread aware caches
3270 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3270 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3271 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3271 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3272
3272
3273 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3273 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3274 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3274 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3275 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3275 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3276 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3276 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3277
3277
3278 def __init__(self, cache_key, cache_args=''):
3278 def __init__(self, cache_key, cache_args=''):
3279 self.cache_key = cache_key
3279 self.cache_key = cache_key
3280 self.cache_args = cache_args
3280 self.cache_args = cache_args
3281 self.cache_active = False
3281 self.cache_active = False
3282
3282
3283 def __unicode__(self):
3283 def __unicode__(self):
3284 return u"<%s('%s:%s[%s]')>" % (
3284 return u"<%s('%s:%s[%s]')>" % (
3285 self.__class__.__name__,
3285 self.__class__.__name__,
3286 self.cache_id, self.cache_key, self.cache_active)
3286 self.cache_id, self.cache_key, self.cache_active)
3287
3287
3288 def _cache_key_partition(self):
3288 def _cache_key_partition(self):
3289 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3289 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3290 return prefix, repo_name, suffix
3290 return prefix, repo_name, suffix
3291
3291
3292 def get_prefix(self):
3292 def get_prefix(self):
3293 """
3293 """
3294 Try to extract prefix from existing cache key. The key could consist
3294 Try to extract prefix from existing cache key. The key could consist
3295 of prefix, repo_name, suffix
3295 of prefix, repo_name, suffix
3296 """
3296 """
3297 # this returns prefix, repo_name, suffix
3297 # this returns prefix, repo_name, suffix
3298 return self._cache_key_partition()[0]
3298 return self._cache_key_partition()[0]
3299
3299
3300 def get_suffix(self):
3300 def get_suffix(self):
3301 """
3301 """
3302 get suffix that might have been used in _get_cache_key to
3302 get suffix that might have been used in _get_cache_key to
3303 generate self.cache_key. Only used for informational purposes
3303 generate self.cache_key. Only used for informational purposes
3304 in repo_edit.mako.
3304 in repo_edit.mako.
3305 """
3305 """
3306 # prefix, repo_name, suffix
3306 # prefix, repo_name, suffix
3307 return self._cache_key_partition()[2]
3307 return self._cache_key_partition()[2]
3308
3308
3309 @classmethod
3309 @classmethod
3310 def delete_all_cache(cls):
3310 def delete_all_cache(cls):
3311 """
3311 """
3312 Delete all cache keys from database.
3312 Delete all cache keys from database.
3313 Should only be run when all instances are down and all entries
3313 Should only be run when all instances are down and all entries
3314 thus stale.
3314 thus stale.
3315 """
3315 """
3316 cls.query().delete()
3316 cls.query().delete()
3317 Session().commit()
3317 Session().commit()
3318
3318
3319 @classmethod
3319 @classmethod
3320 def set_invalidate(cls, cache_uid, delete=False):
3320 def set_invalidate(cls, cache_uid, delete=False):
3321 """
3321 """
3322 Mark all caches of a repo as invalid in the database.
3322 Mark all caches of a repo as invalid in the database.
3323 """
3323 """
3324
3324
3325 try:
3325 try:
3326 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3326 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3327 if delete:
3327 if delete:
3328 qry.delete()
3328 qry.delete()
3329 log.debug('cache objects deleted for cache args %s',
3329 log.debug('cache objects deleted for cache args %s',
3330 safe_str(cache_uid))
3330 safe_str(cache_uid))
3331 else:
3331 else:
3332 qry.update({"cache_active": False})
3332 qry.update({"cache_active": False})
3333 log.debug('cache objects marked as invalid for cache args %s',
3333 log.debug('cache objects marked as invalid for cache args %s',
3334 safe_str(cache_uid))
3334 safe_str(cache_uid))
3335
3335
3336 Session().commit()
3336 Session().commit()
3337 except Exception:
3337 except Exception:
3338 log.exception(
3338 log.exception(
3339 'Cache key invalidation failed for cache args %s',
3339 'Cache key invalidation failed for cache args %s',
3340 safe_str(cache_uid))
3340 safe_str(cache_uid))
3341 Session().rollback()
3341 Session().rollback()
3342
3342
3343 @classmethod
3343 @classmethod
3344 def get_active_cache(cls, cache_key):
3344 def get_active_cache(cls, cache_key):
3345 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3345 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3346 if inv_obj:
3346 if inv_obj:
3347 return inv_obj
3347 return inv_obj
3348 return None
3348 return None
3349
3349
3350
3350
3351 class ChangesetComment(Base, BaseModel):
3351 class ChangesetComment(Base, BaseModel):
3352 __tablename__ = 'changeset_comments'
3352 __tablename__ = 'changeset_comments'
3353 __table_args__ = (
3353 __table_args__ = (
3354 Index('cc_revision_idx', 'revision'),
3354 Index('cc_revision_idx', 'revision'),
3355 base_table_args,
3355 base_table_args,
3356 )
3356 )
3357
3357
3358 COMMENT_OUTDATED = u'comment_outdated'
3358 COMMENT_OUTDATED = u'comment_outdated'
3359 COMMENT_TYPE_NOTE = u'note'
3359 COMMENT_TYPE_NOTE = u'note'
3360 COMMENT_TYPE_TODO = u'todo'
3360 COMMENT_TYPE_TODO = u'todo'
3361 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3361 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3362
3362
3363 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3363 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3364 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3364 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3365 revision = Column('revision', String(40), nullable=True)
3365 revision = Column('revision', String(40), nullable=True)
3366 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3366 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3367 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3367 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3368 line_no = Column('line_no', Unicode(10), nullable=True)
3368 line_no = Column('line_no', Unicode(10), nullable=True)
3369 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3369 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3370 f_path = Column('f_path', Unicode(1000), nullable=True)
3370 f_path = Column('f_path', Unicode(1000), nullable=True)
3371 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3371 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3372 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3372 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3373 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3373 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3374 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3374 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3375 renderer = Column('renderer', Unicode(64), nullable=True)
3375 renderer = Column('renderer', Unicode(64), nullable=True)
3376 display_state = Column('display_state', Unicode(128), nullable=True)
3376 display_state = Column('display_state', Unicode(128), nullable=True)
3377
3377
3378 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3378 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3379 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3379 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3380
3380
3381 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3381 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3382 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3382 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3383
3383
3384 author = relationship('User', lazy='joined')
3384 author = relationship('User', lazy='joined')
3385 repo = relationship('Repository')
3385 repo = relationship('Repository')
3386 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3386 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3387 pull_request = relationship('PullRequest', lazy='joined')
3387 pull_request = relationship('PullRequest', lazy='joined')
3388 pull_request_version = relationship('PullRequestVersion')
3388 pull_request_version = relationship('PullRequestVersion')
3389
3389
3390 @classmethod
3390 @classmethod
3391 def get_users(cls, revision=None, pull_request_id=None):
3391 def get_users(cls, revision=None, pull_request_id=None):
3392 """
3392 """
3393 Returns user associated with this ChangesetComment. ie those
3393 Returns user associated with this ChangesetComment. ie those
3394 who actually commented
3394 who actually commented
3395
3395
3396 :param cls:
3396 :param cls:
3397 :param revision:
3397 :param revision:
3398 """
3398 """
3399 q = Session().query(User)\
3399 q = Session().query(User)\
3400 .join(ChangesetComment.author)
3400 .join(ChangesetComment.author)
3401 if revision:
3401 if revision:
3402 q = q.filter(cls.revision == revision)
3402 q = q.filter(cls.revision == revision)
3403 elif pull_request_id:
3403 elif pull_request_id:
3404 q = q.filter(cls.pull_request_id == pull_request_id)
3404 q = q.filter(cls.pull_request_id == pull_request_id)
3405 return q.all()
3405 return q.all()
3406
3406
3407 @classmethod
3407 @classmethod
3408 def get_index_from_version(cls, pr_version, versions):
3408 def get_index_from_version(cls, pr_version, versions):
3409 num_versions = [x.pull_request_version_id for x in versions]
3409 num_versions = [x.pull_request_version_id for x in versions]
3410 try:
3410 try:
3411 return num_versions.index(pr_version) +1
3411 return num_versions.index(pr_version) +1
3412 except (IndexError, ValueError):
3412 except (IndexError, ValueError):
3413 return
3413 return
3414
3414
3415 @property
3415 @property
3416 def outdated(self):
3416 def outdated(self):
3417 return self.display_state == self.COMMENT_OUTDATED
3417 return self.display_state == self.COMMENT_OUTDATED
3418
3418
3419 def outdated_at_version(self, version):
3419 def outdated_at_version(self, version):
3420 """
3420 """
3421 Checks if comment is outdated for given pull request version
3421 Checks if comment is outdated for given pull request version
3422 """
3422 """
3423 return self.outdated and self.pull_request_version_id != version
3423 return self.outdated and self.pull_request_version_id != version
3424
3424
3425 def older_than_version(self, version):
3425 def older_than_version(self, version):
3426 """
3426 """
3427 Checks if comment is made from previous version than given
3427 Checks if comment is made from previous version than given
3428 """
3428 """
3429 if version is None:
3429 if version is None:
3430 return self.pull_request_version_id is not None
3430 return self.pull_request_version_id is not None
3431
3431
3432 return self.pull_request_version_id < version
3432 return self.pull_request_version_id < version
3433
3433
3434 @property
3434 @property
3435 def resolved(self):
3435 def resolved(self):
3436 return self.resolved_by[0] if self.resolved_by else None
3436 return self.resolved_by[0] if self.resolved_by else None
3437
3437
3438 @property
3438 @property
3439 def is_todo(self):
3439 def is_todo(self):
3440 return self.comment_type == self.COMMENT_TYPE_TODO
3440 return self.comment_type == self.COMMENT_TYPE_TODO
3441
3441
3442 @property
3442 @property
3443 def is_inline(self):
3443 def is_inline(self):
3444 return self.line_no and self.f_path
3444 return self.line_no and self.f_path
3445
3445
3446 def get_index_version(self, versions):
3446 def get_index_version(self, versions):
3447 return self.get_index_from_version(
3447 return self.get_index_from_version(
3448 self.pull_request_version_id, versions)
3448 self.pull_request_version_id, versions)
3449
3449
3450 def __repr__(self):
3450 def __repr__(self):
3451 if self.comment_id:
3451 if self.comment_id:
3452 return '<DB:Comment #%s>' % self.comment_id
3452 return '<DB:Comment #%s>' % self.comment_id
3453 else:
3453 else:
3454 return '<DB:Comment at %#x>' % id(self)
3454 return '<DB:Comment at %#x>' % id(self)
3455
3455
3456 def get_api_data(self):
3456 def get_api_data(self):
3457 comment = self
3457 comment = self
3458 data = {
3458 data = {
3459 'comment_id': comment.comment_id,
3459 'comment_id': comment.comment_id,
3460 'comment_type': comment.comment_type,
3460 'comment_type': comment.comment_type,
3461 'comment_text': comment.text,
3461 'comment_text': comment.text,
3462 'comment_status': comment.status_change,
3462 'comment_status': comment.status_change,
3463 'comment_f_path': comment.f_path,
3463 'comment_f_path': comment.f_path,
3464 'comment_lineno': comment.line_no,
3464 'comment_lineno': comment.line_no,
3465 'comment_author': comment.author,
3465 'comment_author': comment.author,
3466 'comment_created_on': comment.created_on
3466 'comment_created_on': comment.created_on
3467 }
3467 }
3468 return data
3468 return data
3469
3469
3470 def __json__(self):
3470 def __json__(self):
3471 data = dict()
3471 data = dict()
3472 data.update(self.get_api_data())
3472 data.update(self.get_api_data())
3473 return data
3473 return data
3474
3474
3475
3475
3476 class ChangesetStatus(Base, BaseModel):
3476 class ChangesetStatus(Base, BaseModel):
3477 __tablename__ = 'changeset_statuses'
3477 __tablename__ = 'changeset_statuses'
3478 __table_args__ = (
3478 __table_args__ = (
3479 Index('cs_revision_idx', 'revision'),
3479 Index('cs_revision_idx', 'revision'),
3480 Index('cs_version_idx', 'version'),
3480 Index('cs_version_idx', 'version'),
3481 UniqueConstraint('repo_id', 'revision', 'version'),
3481 UniqueConstraint('repo_id', 'revision', 'version'),
3482 base_table_args
3482 base_table_args
3483 )
3483 )
3484
3484
3485 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3485 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3486 STATUS_APPROVED = 'approved'
3486 STATUS_APPROVED = 'approved'
3487 STATUS_REJECTED = 'rejected'
3487 STATUS_REJECTED = 'rejected'
3488 STATUS_UNDER_REVIEW = 'under_review'
3488 STATUS_UNDER_REVIEW = 'under_review'
3489
3489
3490 STATUSES = [
3490 STATUSES = [
3491 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3491 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3492 (STATUS_APPROVED, _("Approved")),
3492 (STATUS_APPROVED, _("Approved")),
3493 (STATUS_REJECTED, _("Rejected")),
3493 (STATUS_REJECTED, _("Rejected")),
3494 (STATUS_UNDER_REVIEW, _("Under Review")),
3494 (STATUS_UNDER_REVIEW, _("Under Review")),
3495 ]
3495 ]
3496
3496
3497 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3497 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3498 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3498 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3499 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3499 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3500 revision = Column('revision', String(40), nullable=False)
3500 revision = Column('revision', String(40), nullable=False)
3501 status = Column('status', String(128), nullable=False, default=DEFAULT)
3501 status = Column('status', String(128), nullable=False, default=DEFAULT)
3502 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3502 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3503 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3503 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3504 version = Column('version', Integer(), nullable=False, default=0)
3504 version = Column('version', Integer(), nullable=False, default=0)
3505 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3505 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3506
3506
3507 author = relationship('User', lazy='joined')
3507 author = relationship('User', lazy='joined')
3508 repo = relationship('Repository')
3508 repo = relationship('Repository')
3509 comment = relationship('ChangesetComment', lazy='joined')
3509 comment = relationship('ChangesetComment', lazy='joined')
3510 pull_request = relationship('PullRequest', lazy='joined')
3510 pull_request = relationship('PullRequest', lazy='joined')
3511
3511
3512 def __unicode__(self):
3512 def __unicode__(self):
3513 return u"<%s('%s[v%s]:%s')>" % (
3513 return u"<%s('%s[v%s]:%s')>" % (
3514 self.__class__.__name__,
3514 self.__class__.__name__,
3515 self.status, self.version, self.author
3515 self.status, self.version, self.author
3516 )
3516 )
3517
3517
3518 @classmethod
3518 @classmethod
3519 def get_status_lbl(cls, value):
3519 def get_status_lbl(cls, value):
3520 return dict(cls.STATUSES).get(value)
3520 return dict(cls.STATUSES).get(value)
3521
3521
3522 @property
3522 @property
3523 def status_lbl(self):
3523 def status_lbl(self):
3524 return ChangesetStatus.get_status_lbl(self.status)
3524 return ChangesetStatus.get_status_lbl(self.status)
3525
3525
3526 def get_api_data(self):
3526 def get_api_data(self):
3527 status = self
3527 status = self
3528 data = {
3528 data = {
3529 'status_id': status.changeset_status_id,
3529 'status_id': status.changeset_status_id,
3530 'status': status.status,
3530 'status': status.status,
3531 }
3531 }
3532 return data
3532 return data
3533
3533
3534 def __json__(self):
3534 def __json__(self):
3535 data = dict()
3535 data = dict()
3536 data.update(self.get_api_data())
3536 data.update(self.get_api_data())
3537 return data
3537 return data
3538
3538
3539
3539
3540 class _PullRequestBase(BaseModel):
3540 class _PullRequestBase(BaseModel):
3541 """
3541 """
3542 Common attributes of pull request and version entries.
3542 Common attributes of pull request and version entries.
3543 """
3543 """
3544
3544
3545 # .status values
3545 # .status values
3546 STATUS_NEW = u'new'
3546 STATUS_NEW = u'new'
3547 STATUS_OPEN = u'open'
3547 STATUS_OPEN = u'open'
3548 STATUS_CLOSED = u'closed'
3548 STATUS_CLOSED = u'closed'
3549
3549
3550 # available states
3550 # available states
3551 STATE_CREATING = u'creating'
3551 STATE_CREATING = u'creating'
3552 STATE_UPDATING = u'updating'
3552 STATE_UPDATING = u'updating'
3553 STATE_MERGING = u'merging'
3553 STATE_MERGING = u'merging'
3554 STATE_CREATED = u'created'
3554 STATE_CREATED = u'created'
3555
3555
3556 title = Column('title', Unicode(255), nullable=True)
3556 title = Column('title', Unicode(255), nullable=True)
3557 description = Column(
3557 description = Column(
3558 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3558 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3559 nullable=True)
3559 nullable=True)
3560 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3560 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3561
3561
3562 # new/open/closed status of pull request (not approve/reject/etc)
3562 # new/open/closed status of pull request (not approve/reject/etc)
3563 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3563 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3564 created_on = Column(
3564 created_on = Column(
3565 'created_on', DateTime(timezone=False), nullable=False,
3565 'created_on', DateTime(timezone=False), nullable=False,
3566 default=datetime.datetime.now)
3566 default=datetime.datetime.now)
3567 updated_on = Column(
3567 updated_on = Column(
3568 'updated_on', DateTime(timezone=False), nullable=False,
3568 'updated_on', DateTime(timezone=False), nullable=False,
3569 default=datetime.datetime.now)
3569 default=datetime.datetime.now)
3570
3570
3571 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3571 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3572
3572
3573 @declared_attr
3573 @declared_attr
3574 def user_id(cls):
3574 def user_id(cls):
3575 return Column(
3575 return Column(
3576 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3576 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3577 unique=None)
3577 unique=None)
3578
3578
3579 # 500 revisions max
3579 # 500 revisions max
3580 _revisions = Column(
3580 _revisions = Column(
3581 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3581 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3582
3582
3583 @declared_attr
3583 @declared_attr
3584 def source_repo_id(cls):
3584 def source_repo_id(cls):
3585 # TODO: dan: rename column to source_repo_id
3585 # TODO: dan: rename column to source_repo_id
3586 return Column(
3586 return Column(
3587 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3587 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3588 nullable=False)
3588 nullable=False)
3589
3589
3590 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3590 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3591
3591
3592 @hybrid_property
3592 @hybrid_property
3593 def source_ref(self):
3593 def source_ref(self):
3594 return self._source_ref
3594 return self._source_ref
3595
3595
3596 @source_ref.setter
3596 @source_ref.setter
3597 def source_ref(self, val):
3597 def source_ref(self, val):
3598 parts = (val or '').split(':')
3598 parts = (val or '').split(':')
3599 if len(parts) != 3:
3599 if len(parts) != 3:
3600 raise ValueError(
3600 raise ValueError(
3601 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3601 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3602 self._source_ref = safe_unicode(val)
3602 self._source_ref = safe_unicode(val)
3603
3603
3604 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3604 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3605
3605
3606 @hybrid_property
3606 @hybrid_property
3607 def target_ref(self):
3607 def target_ref(self):
3608 return self._target_ref
3608 return self._target_ref
3609
3609
3610 @target_ref.setter
3610 @target_ref.setter
3611 def target_ref(self, val):
3611 def target_ref(self, val):
3612 parts = (val or '').split(':')
3612 parts = (val or '').split(':')
3613 if len(parts) != 3:
3613 if len(parts) != 3:
3614 raise ValueError(
3614 raise ValueError(
3615 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3615 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3616 self._target_ref = safe_unicode(val)
3616 self._target_ref = safe_unicode(val)
3617
3617
3618 @declared_attr
3618 @declared_attr
3619 def target_repo_id(cls):
3619 def target_repo_id(cls):
3620 # TODO: dan: rename column to target_repo_id
3620 # TODO: dan: rename column to target_repo_id
3621 return Column(
3621 return Column(
3622 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3622 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3623 nullable=False)
3623 nullable=False)
3624
3624
3625 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3625 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3626
3626
3627 # TODO: dan: rename column to last_merge_source_rev
3627 # TODO: dan: rename column to last_merge_source_rev
3628 _last_merge_source_rev = Column(
3628 _last_merge_source_rev = Column(
3629 'last_merge_org_rev', String(40), nullable=True)
3629 'last_merge_org_rev', String(40), nullable=True)
3630 # TODO: dan: rename column to last_merge_target_rev
3630 # TODO: dan: rename column to last_merge_target_rev
3631 _last_merge_target_rev = Column(
3631 _last_merge_target_rev = Column(
3632 'last_merge_other_rev', String(40), nullable=True)
3632 'last_merge_other_rev', String(40), nullable=True)
3633 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3633 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3634 merge_rev = Column('merge_rev', String(40), nullable=True)
3634 merge_rev = Column('merge_rev', String(40), nullable=True)
3635
3635
3636 reviewer_data = Column(
3636 reviewer_data = Column(
3637 'reviewer_data_json', MutationObj.as_mutable(
3637 'reviewer_data_json', MutationObj.as_mutable(
3638 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3638 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3639
3639
3640 @property
3640 @property
3641 def reviewer_data_json(self):
3641 def reviewer_data_json(self):
3642 return json.dumps(self.reviewer_data)
3642 return json.dumps(self.reviewer_data)
3643
3643
3644 @hybrid_property
3644 @hybrid_property
3645 def description_safe(self):
3645 def description_safe(self):
3646 from rhodecode.lib import helpers as h
3646 from rhodecode.lib import helpers as h
3647 return h.escape(self.description)
3647 return h.escape(self.description)
3648
3648
3649 @hybrid_property
3649 @hybrid_property
3650 def revisions(self):
3650 def revisions(self):
3651 return self._revisions.split(':') if self._revisions else []
3651 return self._revisions.split(':') if self._revisions else []
3652
3652
3653 @revisions.setter
3653 @revisions.setter
3654 def revisions(self, val):
3654 def revisions(self, val):
3655 self._revisions = ':'.join(val)
3655 self._revisions = ':'.join(val)
3656
3656
3657 @hybrid_property
3657 @hybrid_property
3658 def last_merge_status(self):
3658 def last_merge_status(self):
3659 return safe_int(self._last_merge_status)
3659 return safe_int(self._last_merge_status)
3660
3660
3661 @last_merge_status.setter
3661 @last_merge_status.setter
3662 def last_merge_status(self, val):
3662 def last_merge_status(self, val):
3663 self._last_merge_status = val
3663 self._last_merge_status = val
3664
3664
3665 @declared_attr
3665 @declared_attr
3666 def author(cls):
3666 def author(cls):
3667 return relationship('User', lazy='joined')
3667 return relationship('User', lazy='joined')
3668
3668
3669 @declared_attr
3669 @declared_attr
3670 def source_repo(cls):
3670 def source_repo(cls):
3671 return relationship(
3671 return relationship(
3672 'Repository',
3672 'Repository',
3673 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3673 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3674
3674
3675 @property
3675 @property
3676 def source_ref_parts(self):
3676 def source_ref_parts(self):
3677 return self.unicode_to_reference(self.source_ref)
3677 return self.unicode_to_reference(self.source_ref)
3678
3678
3679 @declared_attr
3679 @declared_attr
3680 def target_repo(cls):
3680 def target_repo(cls):
3681 return relationship(
3681 return relationship(
3682 'Repository',
3682 'Repository',
3683 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3683 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3684
3684
3685 @property
3685 @property
3686 def target_ref_parts(self):
3686 def target_ref_parts(self):
3687 return self.unicode_to_reference(self.target_ref)
3687 return self.unicode_to_reference(self.target_ref)
3688
3688
3689 @property
3689 @property
3690 def shadow_merge_ref(self):
3690 def shadow_merge_ref(self):
3691 return self.unicode_to_reference(self._shadow_merge_ref)
3691 return self.unicode_to_reference(self._shadow_merge_ref)
3692
3692
3693 @shadow_merge_ref.setter
3693 @shadow_merge_ref.setter
3694 def shadow_merge_ref(self, ref):
3694 def shadow_merge_ref(self, ref):
3695 self._shadow_merge_ref = self.reference_to_unicode(ref)
3695 self._shadow_merge_ref = self.reference_to_unicode(ref)
3696
3696
3697 @staticmethod
3697 @staticmethod
3698 def unicode_to_reference(raw):
3698 def unicode_to_reference(raw):
3699 """
3699 """
3700 Convert a unicode (or string) to a reference object.
3700 Convert a unicode (or string) to a reference object.
3701 If unicode evaluates to False it returns None.
3701 If unicode evaluates to False it returns None.
3702 """
3702 """
3703 if raw:
3703 if raw:
3704 refs = raw.split(':')
3704 refs = raw.split(':')
3705 return Reference(*refs)
3705 return Reference(*refs)
3706 else:
3706 else:
3707 return None
3707 return None
3708
3708
3709 @staticmethod
3709 @staticmethod
3710 def reference_to_unicode(ref):
3710 def reference_to_unicode(ref):
3711 """
3711 """
3712 Convert a reference object to unicode.
3712 Convert a reference object to unicode.
3713 If reference is None it returns None.
3713 If reference is None it returns None.
3714 """
3714 """
3715 if ref:
3715 if ref:
3716 return u':'.join(ref)
3716 return u':'.join(ref)
3717 else:
3717 else:
3718 return None
3718 return None
3719
3719
3720 def get_api_data(self, with_merge_state=True):
3720 def get_api_data(self, with_merge_state=True):
3721 from rhodecode.model.pull_request import PullRequestModel
3721 from rhodecode.model.pull_request import PullRequestModel
3722
3722
3723 pull_request = self
3723 pull_request = self
3724 if with_merge_state:
3724 if with_merge_state:
3725 merge_status = PullRequestModel().merge_status(pull_request)
3725 merge_status = PullRequestModel().merge_status(pull_request)
3726 merge_state = {
3726 merge_state = {
3727 'status': merge_status[0],
3727 'status': merge_status[0],
3728 'message': safe_unicode(merge_status[1]),
3728 'message': safe_unicode(merge_status[1]),
3729 }
3729 }
3730 else:
3730 else:
3731 merge_state = {'status': 'not_available',
3731 merge_state = {'status': 'not_available',
3732 'message': 'not_available'}
3732 'message': 'not_available'}
3733
3733
3734 merge_data = {
3734 merge_data = {
3735 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3735 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3736 'reference': (
3736 'reference': (
3737 pull_request.shadow_merge_ref._asdict()
3737 pull_request.shadow_merge_ref._asdict()
3738 if pull_request.shadow_merge_ref else None),
3738 if pull_request.shadow_merge_ref else None),
3739 }
3739 }
3740
3740
3741 data = {
3741 data = {
3742 'pull_request_id': pull_request.pull_request_id,
3742 'pull_request_id': pull_request.pull_request_id,
3743 'url': PullRequestModel().get_url(pull_request),
3743 'url': PullRequestModel().get_url(pull_request),
3744 'title': pull_request.title,
3744 'title': pull_request.title,
3745 'description': pull_request.description,
3745 'description': pull_request.description,
3746 'status': pull_request.status,
3746 'status': pull_request.status,
3747 'created_on': pull_request.created_on,
3747 'created_on': pull_request.created_on,
3748 'updated_on': pull_request.updated_on,
3748 'updated_on': pull_request.updated_on,
3749 'commit_ids': pull_request.revisions,
3749 'commit_ids': pull_request.revisions,
3750 'review_status': pull_request.calculated_review_status(),
3750 'review_status': pull_request.calculated_review_status(),
3751 'mergeable': merge_state,
3751 'mergeable': merge_state,
3752 'source': {
3752 'source': {
3753 'clone_url': pull_request.source_repo.clone_url(),
3753 'clone_url': pull_request.source_repo.clone_url(),
3754 'repository': pull_request.source_repo.repo_name,
3754 'repository': pull_request.source_repo.repo_name,
3755 'reference': {
3755 'reference': {
3756 'name': pull_request.source_ref_parts.name,
3756 'name': pull_request.source_ref_parts.name,
3757 'type': pull_request.source_ref_parts.type,
3757 'type': pull_request.source_ref_parts.type,
3758 'commit_id': pull_request.source_ref_parts.commit_id,
3758 'commit_id': pull_request.source_ref_parts.commit_id,
3759 },
3759 },
3760 },
3760 },
3761 'target': {
3761 'target': {
3762 'clone_url': pull_request.target_repo.clone_url(),
3762 'clone_url': pull_request.target_repo.clone_url(),
3763 'repository': pull_request.target_repo.repo_name,
3763 'repository': pull_request.target_repo.repo_name,
3764 'reference': {
3764 'reference': {
3765 'name': pull_request.target_ref_parts.name,
3765 'name': pull_request.target_ref_parts.name,
3766 'type': pull_request.target_ref_parts.type,
3766 'type': pull_request.target_ref_parts.type,
3767 'commit_id': pull_request.target_ref_parts.commit_id,
3767 'commit_id': pull_request.target_ref_parts.commit_id,
3768 },
3768 },
3769 },
3769 },
3770 'merge': merge_data,
3770 'merge': merge_data,
3771 'author': pull_request.author.get_api_data(include_secrets=False,
3771 'author': pull_request.author.get_api_data(include_secrets=False,
3772 details='basic'),
3772 details='basic'),
3773 'reviewers': [
3773 'reviewers': [
3774 {
3774 {
3775 'user': reviewer.get_api_data(include_secrets=False,
3775 'user': reviewer.get_api_data(include_secrets=False,
3776 details='basic'),
3776 details='basic'),
3777 'reasons': reasons,
3777 'reasons': reasons,
3778 'review_status': st[0][1].status if st else 'not_reviewed',
3778 'review_status': st[0][1].status if st else 'not_reviewed',
3779 }
3779 }
3780 for obj, reviewer, reasons, mandatory, st in
3780 for obj, reviewer, reasons, mandatory, st in
3781 pull_request.reviewers_statuses()
3781 pull_request.reviewers_statuses()
3782 ]
3782 ]
3783 }
3783 }
3784
3784
3785 return data
3785 return data
3786
3786
3787
3787
3788 class PullRequest(Base, _PullRequestBase):
3788 class PullRequest(Base, _PullRequestBase):
3789 __tablename__ = 'pull_requests'
3789 __tablename__ = 'pull_requests'
3790 __table_args__ = (
3790 __table_args__ = (
3791 base_table_args,
3791 base_table_args,
3792 )
3792 )
3793
3793
3794 pull_request_id = Column(
3794 pull_request_id = Column(
3795 'pull_request_id', Integer(), nullable=False, primary_key=True)
3795 'pull_request_id', Integer(), nullable=False, primary_key=True)
3796
3796
3797 def __repr__(self):
3797 def __repr__(self):
3798 if self.pull_request_id:
3798 if self.pull_request_id:
3799 return '<DB:PullRequest #%s>' % self.pull_request_id
3799 return '<DB:PullRequest #%s>' % self.pull_request_id
3800 else:
3800 else:
3801 return '<DB:PullRequest at %#x>' % id(self)
3801 return '<DB:PullRequest at %#x>' % id(self)
3802
3802
3803 reviewers = relationship('PullRequestReviewers',
3803 reviewers = relationship('PullRequestReviewers',
3804 cascade="all, delete, delete-orphan")
3804 cascade="all, delete, delete-orphan")
3805 statuses = relationship('ChangesetStatus',
3805 statuses = relationship('ChangesetStatus',
3806 cascade="all, delete, delete-orphan")
3806 cascade="all, delete, delete-orphan")
3807 comments = relationship('ChangesetComment',
3807 comments = relationship('ChangesetComment',
3808 cascade="all, delete, delete-orphan")
3808 cascade="all, delete, delete-orphan")
3809 versions = relationship('PullRequestVersion',
3809 versions = relationship('PullRequestVersion',
3810 cascade="all, delete, delete-orphan",
3810 cascade="all, delete, delete-orphan",
3811 lazy='dynamic')
3811 lazy='dynamic')
3812
3812
3813 @classmethod
3813 @classmethod
3814 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3814 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3815 internal_methods=None):
3815 internal_methods=None):
3816
3816
3817 class PullRequestDisplay(object):
3817 class PullRequestDisplay(object):
3818 """
3818 """
3819 Special object wrapper for showing PullRequest data via Versions
3819 Special object wrapper for showing PullRequest data via Versions
3820 It mimics PR object as close as possible. This is read only object
3820 It mimics PR object as close as possible. This is read only object
3821 just for display
3821 just for display
3822 """
3822 """
3823
3823
3824 def __init__(self, attrs, internal=None):
3824 def __init__(self, attrs, internal=None):
3825 self.attrs = attrs
3825 self.attrs = attrs
3826 # internal have priority over the given ones via attrs
3826 # internal have priority over the given ones via attrs
3827 self.internal = internal or ['versions']
3827 self.internal = internal or ['versions']
3828
3828
3829 def __getattr__(self, item):
3829 def __getattr__(self, item):
3830 if item in self.internal:
3830 if item in self.internal:
3831 return getattr(self, item)
3831 return getattr(self, item)
3832 try:
3832 try:
3833 return self.attrs[item]
3833 return self.attrs[item]
3834 except KeyError:
3834 except KeyError:
3835 raise AttributeError(
3835 raise AttributeError(
3836 '%s object has no attribute %s' % (self, item))
3836 '%s object has no attribute %s' % (self, item))
3837
3837
3838 def __repr__(self):
3838 def __repr__(self):
3839 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3839 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3840
3840
3841 def versions(self):
3841 def versions(self):
3842 return pull_request_obj.versions.order_by(
3842 return pull_request_obj.versions.order_by(
3843 PullRequestVersion.pull_request_version_id).all()
3843 PullRequestVersion.pull_request_version_id).all()
3844
3844
3845 def is_closed(self):
3845 def is_closed(self):
3846 return pull_request_obj.is_closed()
3846 return pull_request_obj.is_closed()
3847
3847
3848 @property
3848 @property
3849 def pull_request_version_id(self):
3849 def pull_request_version_id(self):
3850 return getattr(pull_request_obj, 'pull_request_version_id', None)
3850 return getattr(pull_request_obj, 'pull_request_version_id', None)
3851
3851
3852 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3852 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3853
3853
3854 attrs.author = StrictAttributeDict(
3854 attrs.author = StrictAttributeDict(
3855 pull_request_obj.author.get_api_data())
3855 pull_request_obj.author.get_api_data())
3856 if pull_request_obj.target_repo:
3856 if pull_request_obj.target_repo:
3857 attrs.target_repo = StrictAttributeDict(
3857 attrs.target_repo = StrictAttributeDict(
3858 pull_request_obj.target_repo.get_api_data())
3858 pull_request_obj.target_repo.get_api_data())
3859 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3859 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3860
3860
3861 if pull_request_obj.source_repo:
3861 if pull_request_obj.source_repo:
3862 attrs.source_repo = StrictAttributeDict(
3862 attrs.source_repo = StrictAttributeDict(
3863 pull_request_obj.source_repo.get_api_data())
3863 pull_request_obj.source_repo.get_api_data())
3864 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3864 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3865
3865
3866 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3866 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3867 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3867 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3868 attrs.revisions = pull_request_obj.revisions
3868 attrs.revisions = pull_request_obj.revisions
3869
3869
3870 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3870 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3871 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3871 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3872 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3872 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3873
3873
3874 return PullRequestDisplay(attrs, internal=internal_methods)
3874 return PullRequestDisplay(attrs, internal=internal_methods)
3875
3875
3876 def is_closed(self):
3876 def is_closed(self):
3877 return self.status == self.STATUS_CLOSED
3877 return self.status == self.STATUS_CLOSED
3878
3878
3879 def __json__(self):
3879 def __json__(self):
3880 return {
3880 return {
3881 'revisions': self.revisions,
3881 'revisions': self.revisions,
3882 }
3882 }
3883
3883
3884 def calculated_review_status(self):
3884 def calculated_review_status(self):
3885 from rhodecode.model.changeset_status import ChangesetStatusModel
3885 from rhodecode.model.changeset_status import ChangesetStatusModel
3886 return ChangesetStatusModel().calculated_review_status(self)
3886 return ChangesetStatusModel().calculated_review_status(self)
3887
3887
3888 def reviewers_statuses(self):
3888 def reviewers_statuses(self):
3889 from rhodecode.model.changeset_status import ChangesetStatusModel
3889 from rhodecode.model.changeset_status import ChangesetStatusModel
3890 return ChangesetStatusModel().reviewers_statuses(self)
3890 return ChangesetStatusModel().reviewers_statuses(self)
3891
3891
3892 @property
3892 @property
3893 def workspace_id(self):
3893 def workspace_id(self):
3894 from rhodecode.model.pull_request import PullRequestModel
3894 from rhodecode.model.pull_request import PullRequestModel
3895 return PullRequestModel()._workspace_id(self)
3895 return PullRequestModel()._workspace_id(self)
3896
3896
3897 def get_shadow_repo(self):
3897 def get_shadow_repo(self):
3898 workspace_id = self.workspace_id
3898 workspace_id = self.workspace_id
3899 vcs_obj = self.target_repo.scm_instance()
3899 vcs_obj = self.target_repo.scm_instance()
3900 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3900 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3901 self.target_repo.repo_id, workspace_id)
3901 self.target_repo.repo_id, workspace_id)
3902 if os.path.isdir(shadow_repository_path):
3902 if os.path.isdir(shadow_repository_path):
3903 return vcs_obj.get_shadow_instance(shadow_repository_path)
3903 return vcs_obj.get_shadow_instance(shadow_repository_path)
3904
3904
3905
3905
3906 class PullRequestVersion(Base, _PullRequestBase):
3906 class PullRequestVersion(Base, _PullRequestBase):
3907 __tablename__ = 'pull_request_versions'
3907 __tablename__ = 'pull_request_versions'
3908 __table_args__ = (
3908 __table_args__ = (
3909 base_table_args,
3909 base_table_args,
3910 )
3910 )
3911
3911
3912 pull_request_version_id = Column(
3912 pull_request_version_id = Column(
3913 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3913 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3914 pull_request_id = Column(
3914 pull_request_id = Column(
3915 'pull_request_id', Integer(),
3915 'pull_request_id', Integer(),
3916 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3916 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3917 pull_request = relationship('PullRequest')
3917 pull_request = relationship('PullRequest')
3918
3918
3919 def __repr__(self):
3919 def __repr__(self):
3920 if self.pull_request_version_id:
3920 if self.pull_request_version_id:
3921 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3921 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3922 else:
3922 else:
3923 return '<DB:PullRequestVersion at %#x>' % id(self)
3923 return '<DB:PullRequestVersion at %#x>' % id(self)
3924
3924
3925 @property
3925 @property
3926 def reviewers(self):
3926 def reviewers(self):
3927 return self.pull_request.reviewers
3927 return self.pull_request.reviewers
3928
3928
3929 @property
3929 @property
3930 def versions(self):
3930 def versions(self):
3931 return self.pull_request.versions
3931 return self.pull_request.versions
3932
3932
3933 def is_closed(self):
3933 def is_closed(self):
3934 # calculate from original
3934 # calculate from original
3935 return self.pull_request.status == self.STATUS_CLOSED
3935 return self.pull_request.status == self.STATUS_CLOSED
3936
3936
3937 def calculated_review_status(self):
3937 def calculated_review_status(self):
3938 return self.pull_request.calculated_review_status()
3938 return self.pull_request.calculated_review_status()
3939
3939
3940 def reviewers_statuses(self):
3940 def reviewers_statuses(self):
3941 return self.pull_request.reviewers_statuses()
3941 return self.pull_request.reviewers_statuses()
3942
3942
3943
3943
3944 class PullRequestReviewers(Base, BaseModel):
3944 class PullRequestReviewers(Base, BaseModel):
3945 __tablename__ = 'pull_request_reviewers'
3945 __tablename__ = 'pull_request_reviewers'
3946 __table_args__ = (
3946 __table_args__ = (
3947 base_table_args,
3947 base_table_args,
3948 )
3948 )
3949
3949
3950 @hybrid_property
3950 @hybrid_property
3951 def reasons(self):
3951 def reasons(self):
3952 if not self._reasons:
3952 if not self._reasons:
3953 return []
3953 return []
3954 return self._reasons
3954 return self._reasons
3955
3955
3956 @reasons.setter
3956 @reasons.setter
3957 def reasons(self, val):
3957 def reasons(self, val):
3958 val = val or []
3958 val = val or []
3959 if any(not isinstance(x, compat.string_types) for x in val):
3959 if any(not isinstance(x, compat.string_types) for x in val):
3960 raise Exception('invalid reasons type, must be list of strings')
3960 raise Exception('invalid reasons type, must be list of strings')
3961 self._reasons = val
3961 self._reasons = val
3962
3962
3963 pull_requests_reviewers_id = Column(
3963 pull_requests_reviewers_id = Column(
3964 'pull_requests_reviewers_id', Integer(), nullable=False,
3964 'pull_requests_reviewers_id', Integer(), nullable=False,
3965 primary_key=True)
3965 primary_key=True)
3966 pull_request_id = Column(
3966 pull_request_id = Column(
3967 "pull_request_id", Integer(),
3967 "pull_request_id", Integer(),
3968 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3968 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3969 user_id = Column(
3969 user_id = Column(
3970 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3970 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3971 _reasons = Column(
3971 _reasons = Column(
3972 'reason', MutationList.as_mutable(
3972 'reason', MutationList.as_mutable(
3973 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3973 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3974
3974
3975 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3975 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3976 user = relationship('User')
3976 user = relationship('User')
3977 pull_request = relationship('PullRequest')
3977 pull_request = relationship('PullRequest')
3978
3978
3979 rule_data = Column(
3979 rule_data = Column(
3980 'rule_data_json',
3980 'rule_data_json',
3981 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
3981 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
3982
3982
3983 def rule_user_group_data(self):
3983 def rule_user_group_data(self):
3984 """
3984 """
3985 Returns the voting user group rule data for this reviewer
3985 Returns the voting user group rule data for this reviewer
3986 """
3986 """
3987
3987
3988 if self.rule_data and 'vote_rule' in self.rule_data:
3988 if self.rule_data and 'vote_rule' in self.rule_data:
3989 user_group_data = {}
3989 user_group_data = {}
3990 if 'rule_user_group_entry_id' in self.rule_data:
3990 if 'rule_user_group_entry_id' in self.rule_data:
3991 # means a group with voting rules !
3991 # means a group with voting rules !
3992 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
3992 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
3993 user_group_data['name'] = self.rule_data['rule_name']
3993 user_group_data['name'] = self.rule_data['rule_name']
3994 user_group_data['vote_rule'] = self.rule_data['vote_rule']
3994 user_group_data['vote_rule'] = self.rule_data['vote_rule']
3995
3995
3996 return user_group_data
3996 return user_group_data
3997
3997
3998 def __unicode__(self):
3998 def __unicode__(self):
3999 return u"<%s('id:%s')>" % (self.__class__.__name__,
3999 return u"<%s('id:%s')>" % (self.__class__.__name__,
4000 self.pull_requests_reviewers_id)
4000 self.pull_requests_reviewers_id)
4001
4001
4002
4002
4003 class Notification(Base, BaseModel):
4003 class Notification(Base, BaseModel):
4004 __tablename__ = 'notifications'
4004 __tablename__ = 'notifications'
4005 __table_args__ = (
4005 __table_args__ = (
4006 Index('notification_type_idx', 'type'),
4006 Index('notification_type_idx', 'type'),
4007 base_table_args,
4007 base_table_args,
4008 )
4008 )
4009
4009
4010 TYPE_CHANGESET_COMMENT = u'cs_comment'
4010 TYPE_CHANGESET_COMMENT = u'cs_comment'
4011 TYPE_MESSAGE = u'message'
4011 TYPE_MESSAGE = u'message'
4012 TYPE_MENTION = u'mention'
4012 TYPE_MENTION = u'mention'
4013 TYPE_REGISTRATION = u'registration'
4013 TYPE_REGISTRATION = u'registration'
4014 TYPE_PULL_REQUEST = u'pull_request'
4014 TYPE_PULL_REQUEST = u'pull_request'
4015 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4015 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4016
4016
4017 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4017 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4018 subject = Column('subject', Unicode(512), nullable=True)
4018 subject = Column('subject', Unicode(512), nullable=True)
4019 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4019 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4020 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4020 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4021 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4021 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4022 type_ = Column('type', Unicode(255))
4022 type_ = Column('type', Unicode(255))
4023
4023
4024 created_by_user = relationship('User')
4024 created_by_user = relationship('User')
4025 notifications_to_users = relationship('UserNotification', lazy='joined',
4025 notifications_to_users = relationship('UserNotification', lazy='joined',
4026 cascade="all, delete, delete-orphan")
4026 cascade="all, delete, delete-orphan")
4027
4027
4028 @property
4028 @property
4029 def recipients(self):
4029 def recipients(self):
4030 return [x.user for x in UserNotification.query()\
4030 return [x.user for x in UserNotification.query()\
4031 .filter(UserNotification.notification == self)\
4031 .filter(UserNotification.notification == self)\
4032 .order_by(UserNotification.user_id.asc()).all()]
4032 .order_by(UserNotification.user_id.asc()).all()]
4033
4033
4034 @classmethod
4034 @classmethod
4035 def create(cls, created_by, subject, body, recipients, type_=None):
4035 def create(cls, created_by, subject, body, recipients, type_=None):
4036 if type_ is None:
4036 if type_ is None:
4037 type_ = Notification.TYPE_MESSAGE
4037 type_ = Notification.TYPE_MESSAGE
4038
4038
4039 notification = cls()
4039 notification = cls()
4040 notification.created_by_user = created_by
4040 notification.created_by_user = created_by
4041 notification.subject = subject
4041 notification.subject = subject
4042 notification.body = body
4042 notification.body = body
4043 notification.type_ = type_
4043 notification.type_ = type_
4044 notification.created_on = datetime.datetime.now()
4044 notification.created_on = datetime.datetime.now()
4045
4045
4046 # For each recipient link the created notification to his account
4046 # For each recipient link the created notification to his account
4047 for u in recipients:
4047 for u in recipients:
4048 assoc = UserNotification()
4048 assoc = UserNotification()
4049 assoc.user_id = u.user_id
4049 assoc.user_id = u.user_id
4050 assoc.notification = notification
4050 assoc.notification = notification
4051
4051
4052 # if created_by is inside recipients mark his notification
4052 # if created_by is inside recipients mark his notification
4053 # as read
4053 # as read
4054 if u.user_id == created_by.user_id:
4054 if u.user_id == created_by.user_id:
4055 assoc.read = True
4055 assoc.read = True
4056 Session().add(assoc)
4056 Session().add(assoc)
4057
4057
4058 Session().add(notification)
4058 Session().add(notification)
4059
4059
4060 return notification
4060 return notification
4061
4061
4062
4062
4063 class UserNotification(Base, BaseModel):
4063 class UserNotification(Base, BaseModel):
4064 __tablename__ = 'user_to_notification'
4064 __tablename__ = 'user_to_notification'
4065 __table_args__ = (
4065 __table_args__ = (
4066 UniqueConstraint('user_id', 'notification_id'),
4066 UniqueConstraint('user_id', 'notification_id'),
4067 base_table_args
4067 base_table_args
4068 )
4068 )
4069
4069
4070 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4070 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4071 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4071 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4072 read = Column('read', Boolean, default=False)
4072 read = Column('read', Boolean, default=False)
4073 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4073 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4074
4074
4075 user = relationship('User', lazy="joined")
4075 user = relationship('User', lazy="joined")
4076 notification = relationship('Notification', lazy="joined",
4076 notification = relationship('Notification', lazy="joined",
4077 order_by=lambda: Notification.created_on.desc(),)
4077 order_by=lambda: Notification.created_on.desc(),)
4078
4078
4079 def mark_as_read(self):
4079 def mark_as_read(self):
4080 self.read = True
4080 self.read = True
4081 Session().add(self)
4081 Session().add(self)
4082
4082
4083
4083
4084 class Gist(Base, BaseModel):
4084 class Gist(Base, BaseModel):
4085 __tablename__ = 'gists'
4085 __tablename__ = 'gists'
4086 __table_args__ = (
4086 __table_args__ = (
4087 Index('g_gist_access_id_idx', 'gist_access_id'),
4087 Index('g_gist_access_id_idx', 'gist_access_id'),
4088 Index('g_created_on_idx', 'created_on'),
4088 Index('g_created_on_idx', 'created_on'),
4089 base_table_args
4089 base_table_args
4090 )
4090 )
4091
4091
4092 GIST_PUBLIC = u'public'
4092 GIST_PUBLIC = u'public'
4093 GIST_PRIVATE = u'private'
4093 GIST_PRIVATE = u'private'
4094 DEFAULT_FILENAME = u'gistfile1.txt'
4094 DEFAULT_FILENAME = u'gistfile1.txt'
4095
4095
4096 ACL_LEVEL_PUBLIC = u'acl_public'
4096 ACL_LEVEL_PUBLIC = u'acl_public'
4097 ACL_LEVEL_PRIVATE = u'acl_private'
4097 ACL_LEVEL_PRIVATE = u'acl_private'
4098
4098
4099 gist_id = Column('gist_id', Integer(), primary_key=True)
4099 gist_id = Column('gist_id', Integer(), primary_key=True)
4100 gist_access_id = Column('gist_access_id', Unicode(250))
4100 gist_access_id = Column('gist_access_id', Unicode(250))
4101 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4101 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4102 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4102 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4103 gist_expires = Column('gist_expires', Float(53), nullable=False)
4103 gist_expires = Column('gist_expires', Float(53), nullable=False)
4104 gist_type = Column('gist_type', Unicode(128), nullable=False)
4104 gist_type = Column('gist_type', Unicode(128), nullable=False)
4105 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4105 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4106 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4106 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4107 acl_level = Column('acl_level', Unicode(128), nullable=True)
4107 acl_level = Column('acl_level', Unicode(128), nullable=True)
4108
4108
4109 owner = relationship('User')
4109 owner = relationship('User')
4110
4110
4111 def __repr__(self):
4111 def __repr__(self):
4112 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4112 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4113
4113
4114 @hybrid_property
4114 @hybrid_property
4115 def description_safe(self):
4115 def description_safe(self):
4116 from rhodecode.lib import helpers as h
4116 from rhodecode.lib import helpers as h
4117 return h.escape(self.gist_description)
4117 return h.escape(self.gist_description)
4118
4118
4119 @classmethod
4119 @classmethod
4120 def get_or_404(cls, id_):
4120 def get_or_404(cls, id_):
4121 from pyramid.httpexceptions import HTTPNotFound
4121 from pyramid.httpexceptions import HTTPNotFound
4122
4122
4123 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4123 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4124 if not res:
4124 if not res:
4125 raise HTTPNotFound()
4125 raise HTTPNotFound()
4126 return res
4126 return res
4127
4127
4128 @classmethod
4128 @classmethod
4129 def get_by_access_id(cls, gist_access_id):
4129 def get_by_access_id(cls, gist_access_id):
4130 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4130 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4131
4131
4132 def gist_url(self):
4132 def gist_url(self):
4133 from rhodecode.model.gist import GistModel
4133 from rhodecode.model.gist import GistModel
4134 return GistModel().get_url(self)
4134 return GistModel().get_url(self)
4135
4135
4136 @classmethod
4136 @classmethod
4137 def base_path(cls):
4137 def base_path(cls):
4138 """
4138 """
4139 Returns base path when all gists are stored
4139 Returns base path when all gists are stored
4140
4140
4141 :param cls:
4141 :param cls:
4142 """
4142 """
4143 from rhodecode.model.gist import GIST_STORE_LOC
4143 from rhodecode.model.gist import GIST_STORE_LOC
4144 q = Session().query(RhodeCodeUi)\
4144 q = Session().query(RhodeCodeUi)\
4145 .filter(RhodeCodeUi.ui_key == URL_SEP)
4145 .filter(RhodeCodeUi.ui_key == URL_SEP)
4146 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4146 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4147 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4147 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4148
4148
4149 def get_api_data(self):
4149 def get_api_data(self):
4150 """
4150 """
4151 Common function for generating gist related data for API
4151 Common function for generating gist related data for API
4152 """
4152 """
4153 gist = self
4153 gist = self
4154 data = {
4154 data = {
4155 'gist_id': gist.gist_id,
4155 'gist_id': gist.gist_id,
4156 'type': gist.gist_type,
4156 'type': gist.gist_type,
4157 'access_id': gist.gist_access_id,
4157 'access_id': gist.gist_access_id,
4158 'description': gist.gist_description,
4158 'description': gist.gist_description,
4159 'url': gist.gist_url(),
4159 'url': gist.gist_url(),
4160 'expires': gist.gist_expires,
4160 'expires': gist.gist_expires,
4161 'created_on': gist.created_on,
4161 'created_on': gist.created_on,
4162 'modified_at': gist.modified_at,
4162 'modified_at': gist.modified_at,
4163 'content': None,
4163 'content': None,
4164 'acl_level': gist.acl_level,
4164 'acl_level': gist.acl_level,
4165 }
4165 }
4166 return data
4166 return data
4167
4167
4168 def __json__(self):
4168 def __json__(self):
4169 data = dict(
4169 data = dict(
4170 )
4170 )
4171 data.update(self.get_api_data())
4171 data.update(self.get_api_data())
4172 return data
4172 return data
4173 # SCM functions
4173 # SCM functions
4174
4174
4175 def scm_instance(self, **kwargs):
4175 def scm_instance(self, **kwargs):
4176 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4176 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4177 return get_vcs_instance(
4177 return get_vcs_instance(
4178 repo_path=safe_str(full_repo_path), create=False)
4178 repo_path=safe_str(full_repo_path), create=False)
4179
4179
4180
4180
4181 class ExternalIdentity(Base, BaseModel):
4181 class ExternalIdentity(Base, BaseModel):
4182 __tablename__ = 'external_identities'
4182 __tablename__ = 'external_identities'
4183 __table_args__ = (
4183 __table_args__ = (
4184 Index('local_user_id_idx', 'local_user_id'),
4184 Index('local_user_id_idx', 'local_user_id'),
4185 Index('external_id_idx', 'external_id'),
4185 Index('external_id_idx', 'external_id'),
4186 base_table_args
4186 base_table_args
4187 )
4187 )
4188
4188
4189 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4189 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4190 external_username = Column('external_username', Unicode(1024), default=u'')
4190 external_username = Column('external_username', Unicode(1024), default=u'')
4191 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4191 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4192 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4192 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4193 access_token = Column('access_token', String(1024), default=u'')
4193 access_token = Column('access_token', String(1024), default=u'')
4194 alt_token = Column('alt_token', String(1024), default=u'')
4194 alt_token = Column('alt_token', String(1024), default=u'')
4195 token_secret = Column('token_secret', String(1024), default=u'')
4195 token_secret = Column('token_secret', String(1024), default=u'')
4196
4196
4197 @classmethod
4197 @classmethod
4198 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4198 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4199 """
4199 """
4200 Returns ExternalIdentity instance based on search params
4200 Returns ExternalIdentity instance based on search params
4201
4201
4202 :param external_id:
4202 :param external_id:
4203 :param provider_name:
4203 :param provider_name:
4204 :return: ExternalIdentity
4204 :return: ExternalIdentity
4205 """
4205 """
4206 query = cls.query()
4206 query = cls.query()
4207 query = query.filter(cls.external_id == external_id)
4207 query = query.filter(cls.external_id == external_id)
4208 query = query.filter(cls.provider_name == provider_name)
4208 query = query.filter(cls.provider_name == provider_name)
4209 if local_user_id:
4209 if local_user_id:
4210 query = query.filter(cls.local_user_id == local_user_id)
4210 query = query.filter(cls.local_user_id == local_user_id)
4211 return query.first()
4211 return query.first()
4212
4212
4213 @classmethod
4213 @classmethod
4214 def user_by_external_id_and_provider(cls, external_id, provider_name):
4214 def user_by_external_id_and_provider(cls, external_id, provider_name):
4215 """
4215 """
4216 Returns User instance based on search params
4216 Returns User instance based on search params
4217
4217
4218 :param external_id:
4218 :param external_id:
4219 :param provider_name:
4219 :param provider_name:
4220 :return: User
4220 :return: User
4221 """
4221 """
4222 query = User.query()
4222 query = User.query()
4223 query = query.filter(cls.external_id == external_id)
4223 query = query.filter(cls.external_id == external_id)
4224 query = query.filter(cls.provider_name == provider_name)
4224 query = query.filter(cls.provider_name == provider_name)
4225 query = query.filter(User.user_id == cls.local_user_id)
4225 query = query.filter(User.user_id == cls.local_user_id)
4226 return query.first()
4226 return query.first()
4227
4227
4228 @classmethod
4228 @classmethod
4229 def by_local_user_id(cls, local_user_id):
4229 def by_local_user_id(cls, local_user_id):
4230 """
4230 """
4231 Returns all tokens for user
4231 Returns all tokens for user
4232
4232
4233 :param local_user_id:
4233 :param local_user_id:
4234 :return: ExternalIdentity
4234 :return: ExternalIdentity
4235 """
4235 """
4236 query = cls.query()
4236 query = cls.query()
4237 query = query.filter(cls.local_user_id == local_user_id)
4237 query = query.filter(cls.local_user_id == local_user_id)
4238 return query
4238 return query
4239
4239
4240 @classmethod
4240 @classmethod
4241 def load_provider_plugin(cls, plugin_id):
4241 def load_provider_plugin(cls, plugin_id):
4242 from rhodecode.authentication.base import loadplugin
4242 from rhodecode.authentication.base import loadplugin
4243 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4243 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4244 auth_plugin = loadplugin(_plugin_id)
4244 auth_plugin = loadplugin(_plugin_id)
4245 return auth_plugin
4245 return auth_plugin
4246
4246
4247
4247
4248 class Integration(Base, BaseModel):
4248 class Integration(Base, BaseModel):
4249 __tablename__ = 'integrations'
4249 __tablename__ = 'integrations'
4250 __table_args__ = (
4250 __table_args__ = (
4251 base_table_args
4251 base_table_args
4252 )
4252 )
4253
4253
4254 integration_id = Column('integration_id', Integer(), primary_key=True)
4254 integration_id = Column('integration_id', Integer(), primary_key=True)
4255 integration_type = Column('integration_type', String(255))
4255 integration_type = Column('integration_type', String(255))
4256 enabled = Column('enabled', Boolean(), nullable=False)
4256 enabled = Column('enabled', Boolean(), nullable=False)
4257 name = Column('name', String(255), nullable=False)
4257 name = Column('name', String(255), nullable=False)
4258 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4258 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4259 default=False)
4259 default=False)
4260
4260
4261 settings = Column(
4261 settings = Column(
4262 'settings_json', MutationObj.as_mutable(
4262 'settings_json', MutationObj.as_mutable(
4263 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4263 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4264 repo_id = Column(
4264 repo_id = Column(
4265 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4265 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4266 nullable=True, unique=None, default=None)
4266 nullable=True, unique=None, default=None)
4267 repo = relationship('Repository', lazy='joined')
4267 repo = relationship('Repository', lazy='joined')
4268
4268
4269 repo_group_id = Column(
4269 repo_group_id = Column(
4270 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4270 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4271 nullable=True, unique=None, default=None)
4271 nullable=True, unique=None, default=None)
4272 repo_group = relationship('RepoGroup', lazy='joined')
4272 repo_group = relationship('RepoGroup', lazy='joined')
4273
4273
4274 @property
4274 @property
4275 def scope(self):
4275 def scope(self):
4276 if self.repo:
4276 if self.repo:
4277 return repr(self.repo)
4277 return repr(self.repo)
4278 if self.repo_group:
4278 if self.repo_group:
4279 if self.child_repos_only:
4279 if self.child_repos_only:
4280 return repr(self.repo_group) + ' (child repos only)'
4280 return repr(self.repo_group) + ' (child repos only)'
4281 else:
4281 else:
4282 return repr(self.repo_group) + ' (recursive)'
4282 return repr(self.repo_group) + ' (recursive)'
4283 if self.child_repos_only:
4283 if self.child_repos_only:
4284 return 'root_repos'
4284 return 'root_repos'
4285 return 'global'
4285 return 'global'
4286
4286
4287 def __repr__(self):
4287 def __repr__(self):
4288 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4288 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4289
4289
4290
4290
4291 class RepoReviewRuleUser(Base, BaseModel):
4291 class RepoReviewRuleUser(Base, BaseModel):
4292 __tablename__ = 'repo_review_rules_users'
4292 __tablename__ = 'repo_review_rules_users'
4293 __table_args__ = (
4293 __table_args__ = (
4294 base_table_args
4294 base_table_args
4295 )
4295 )
4296
4296
4297 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4297 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4298 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4298 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4299 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4299 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4300 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4300 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4301 user = relationship('User')
4301 user = relationship('User')
4302
4302
4303 def rule_data(self):
4303 def rule_data(self):
4304 return {
4304 return {
4305 'mandatory': self.mandatory
4305 'mandatory': self.mandatory
4306 }
4306 }
4307
4307
4308
4308
4309 class RepoReviewRuleUserGroup(Base, BaseModel):
4309 class RepoReviewRuleUserGroup(Base, BaseModel):
4310 __tablename__ = 'repo_review_rules_users_groups'
4310 __tablename__ = 'repo_review_rules_users_groups'
4311 __table_args__ = (
4311 __table_args__ = (
4312 base_table_args
4312 base_table_args
4313 )
4313 )
4314
4314
4315 VOTE_RULE_ALL = -1
4315 VOTE_RULE_ALL = -1
4316
4316
4317 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4317 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4318 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4318 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4319 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4319 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4320 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4320 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4321 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4321 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4322 users_group = relationship('UserGroup')
4322 users_group = relationship('UserGroup')
4323
4323
4324 def rule_data(self):
4324 def rule_data(self):
4325 return {
4325 return {
4326 'mandatory': self.mandatory,
4326 'mandatory': self.mandatory,
4327 'vote_rule': self.vote_rule
4327 'vote_rule': self.vote_rule
4328 }
4328 }
4329
4329
4330 @property
4330 @property
4331 def vote_rule_label(self):
4331 def vote_rule_label(self):
4332 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4332 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4333 return 'all must vote'
4333 return 'all must vote'
4334 else:
4334 else:
4335 return 'min. vote {}'.format(self.vote_rule)
4335 return 'min. vote {}'.format(self.vote_rule)
4336
4336
4337
4337
4338 class RepoReviewRule(Base, BaseModel):
4338 class RepoReviewRule(Base, BaseModel):
4339 __tablename__ = 'repo_review_rules'
4339 __tablename__ = 'repo_review_rules'
4340 __table_args__ = (
4340 __table_args__ = (
4341 base_table_args
4341 base_table_args
4342 )
4342 )
4343
4343
4344 repo_review_rule_id = Column(
4344 repo_review_rule_id = Column(
4345 'repo_review_rule_id', Integer(), primary_key=True)
4345 'repo_review_rule_id', Integer(), primary_key=True)
4346 repo_id = Column(
4346 repo_id = Column(
4347 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4347 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4348 repo = relationship('Repository', backref='review_rules')
4348 repo = relationship('Repository', backref='review_rules')
4349
4349
4350 review_rule_name = Column('review_rule_name', String(255))
4350 review_rule_name = Column('review_rule_name', String(255))
4351 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4351 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4352 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4352 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4353 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4353 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4354
4354
4355 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4355 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4356 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4356 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4357 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4357 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4358 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4358 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4359
4359
4360 rule_users = relationship('RepoReviewRuleUser')
4360 rule_users = relationship('RepoReviewRuleUser')
4361 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4361 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4362
4362
4363 def _validate_pattern(self, value):
4363 def _validate_pattern(self, value):
4364 re.compile('^' + glob2re(value) + '$')
4364 re.compile('^' + glob2re(value) + '$')
4365
4365
4366 @hybrid_property
4366 @hybrid_property
4367 def source_branch_pattern(self):
4367 def source_branch_pattern(self):
4368 return self._branch_pattern or '*'
4368 return self._branch_pattern or '*'
4369
4369
4370 @source_branch_pattern.setter
4370 @source_branch_pattern.setter
4371 def source_branch_pattern(self, value):
4371 def source_branch_pattern(self, value):
4372 self._validate_pattern(value)
4372 self._validate_pattern(value)
4373 self._branch_pattern = value or '*'
4373 self._branch_pattern = value or '*'
4374
4374
4375 @hybrid_property
4375 @hybrid_property
4376 def target_branch_pattern(self):
4376 def target_branch_pattern(self):
4377 return self._target_branch_pattern or '*'
4377 return self._target_branch_pattern or '*'
4378
4378
4379 @target_branch_pattern.setter
4379 @target_branch_pattern.setter
4380 def target_branch_pattern(self, value):
4380 def target_branch_pattern(self, value):
4381 self._validate_pattern(value)
4381 self._validate_pattern(value)
4382 self._target_branch_pattern = value or '*'
4382 self._target_branch_pattern = value or '*'
4383
4383
4384 @hybrid_property
4384 @hybrid_property
4385 def file_pattern(self):
4385 def file_pattern(self):
4386 return self._file_pattern or '*'
4386 return self._file_pattern or '*'
4387
4387
4388 @file_pattern.setter
4388 @file_pattern.setter
4389 def file_pattern(self, value):
4389 def file_pattern(self, value):
4390 self._validate_pattern(value)
4390 self._validate_pattern(value)
4391 self._file_pattern = value or '*'
4391 self._file_pattern = value or '*'
4392
4392
4393 def matches(self, source_branch, target_branch, files_changed):
4393 def matches(self, source_branch, target_branch, files_changed):
4394 """
4394 """
4395 Check if this review rule matches a branch/files in a pull request
4395 Check if this review rule matches a branch/files in a pull request
4396
4396
4397 :param source_branch: source branch name for the commit
4397 :param source_branch: source branch name for the commit
4398 :param target_branch: target branch name for the commit
4398 :param target_branch: target branch name for the commit
4399 :param files_changed: list of file paths changed in the pull request
4399 :param files_changed: list of file paths changed in the pull request
4400 """
4400 """
4401
4401
4402 source_branch = source_branch or ''
4402 source_branch = source_branch or ''
4403 target_branch = target_branch or ''
4403 target_branch = target_branch or ''
4404 files_changed = files_changed or []
4404 files_changed = files_changed or []
4405
4405
4406 branch_matches = True
4406 branch_matches = True
4407 if source_branch or target_branch:
4407 if source_branch or target_branch:
4408 if self.source_branch_pattern == '*':
4408 if self.source_branch_pattern == '*':
4409 source_branch_match = True
4409 source_branch_match = True
4410 else:
4410 else:
4411 if self.source_branch_pattern.startswith('re:'):
4411 if self.source_branch_pattern.startswith('re:'):
4412 source_pattern = self.source_branch_pattern[3:]
4412 source_pattern = self.source_branch_pattern[3:]
4413 else:
4413 else:
4414 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4414 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4415 source_branch_regex = re.compile(source_pattern)
4415 source_branch_regex = re.compile(source_pattern)
4416 source_branch_match = bool(source_branch_regex.search(source_branch))
4416 source_branch_match = bool(source_branch_regex.search(source_branch))
4417 if self.target_branch_pattern == '*':
4417 if self.target_branch_pattern == '*':
4418 target_branch_match = True
4418 target_branch_match = True
4419 else:
4419 else:
4420 if self.target_branch_pattern.startswith('re:'):
4420 if self.target_branch_pattern.startswith('re:'):
4421 target_pattern = self.target_branch_pattern[3:]
4421 target_pattern = self.target_branch_pattern[3:]
4422 else:
4422 else:
4423 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4423 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4424 target_branch_regex = re.compile(target_pattern)
4424 target_branch_regex = re.compile(target_pattern)
4425 target_branch_match = bool(target_branch_regex.search(target_branch))
4425 target_branch_match = bool(target_branch_regex.search(target_branch))
4426
4426
4427 branch_matches = source_branch_match and target_branch_match
4427 branch_matches = source_branch_match and target_branch_match
4428
4428
4429 files_matches = True
4429 files_matches = True
4430 if self.file_pattern != '*':
4430 if self.file_pattern != '*':
4431 files_matches = False
4431 files_matches = False
4432 if self.file_pattern.startswith('re:'):
4432 if self.file_pattern.startswith('re:'):
4433 file_pattern = self.file_pattern[3:]
4433 file_pattern = self.file_pattern[3:]
4434 else:
4434 else:
4435 file_pattern = glob2re(self.file_pattern)
4435 file_pattern = glob2re(self.file_pattern)
4436 file_regex = re.compile(file_pattern)
4436 file_regex = re.compile(file_pattern)
4437 for filename in files_changed:
4437 for filename in files_changed:
4438 if file_regex.search(filename):
4438 if file_regex.search(filename):
4439 files_matches = True
4439 files_matches = True
4440 break
4440 break
4441
4441
4442 return branch_matches and files_matches
4442 return branch_matches and files_matches
4443
4443
4444 @property
4444 @property
4445 def review_users(self):
4445 def review_users(self):
4446 """ Returns the users which this rule applies to """
4446 """ Returns the users which this rule applies to """
4447
4447
4448 users = collections.OrderedDict()
4448 users = collections.OrderedDict()
4449
4449
4450 for rule_user in self.rule_users:
4450 for rule_user in self.rule_users:
4451 if rule_user.user.active:
4451 if rule_user.user.active:
4452 if rule_user.user not in users:
4452 if rule_user.user not in users:
4453 users[rule_user.user.username] = {
4453 users[rule_user.user.username] = {
4454 'user': rule_user.user,
4454 'user': rule_user.user,
4455 'source': 'user',
4455 'source': 'user',
4456 'source_data': {},
4456 'source_data': {},
4457 'data': rule_user.rule_data()
4457 'data': rule_user.rule_data()
4458 }
4458 }
4459
4459
4460 for rule_user_group in self.rule_user_groups:
4460 for rule_user_group in self.rule_user_groups:
4461 source_data = {
4461 source_data = {
4462 'user_group_id': rule_user_group.users_group.users_group_id,
4462 'user_group_id': rule_user_group.users_group.users_group_id,
4463 'name': rule_user_group.users_group.users_group_name,
4463 'name': rule_user_group.users_group.users_group_name,
4464 'members': len(rule_user_group.users_group.members)
4464 'members': len(rule_user_group.users_group.members)
4465 }
4465 }
4466 for member in rule_user_group.users_group.members:
4466 for member in rule_user_group.users_group.members:
4467 if member.user.active:
4467 if member.user.active:
4468 key = member.user.username
4468 key = member.user.username
4469 if key in users:
4469 if key in users:
4470 # skip this member as we have him already
4470 # skip this member as we have him already
4471 # this prevents from override the "first" matched
4471 # this prevents from override the "first" matched
4472 # users with duplicates in multiple groups
4472 # users with duplicates in multiple groups
4473 continue
4473 continue
4474
4474
4475 users[key] = {
4475 users[key] = {
4476 'user': member.user,
4476 'user': member.user,
4477 'source': 'user_group',
4477 'source': 'user_group',
4478 'source_data': source_data,
4478 'source_data': source_data,
4479 'data': rule_user_group.rule_data()
4479 'data': rule_user_group.rule_data()
4480 }
4480 }
4481
4481
4482 return users
4482 return users
4483
4483
4484 def user_group_vote_rule(self, user_id):
4484 def user_group_vote_rule(self, user_id):
4485
4485
4486 rules = []
4486 rules = []
4487 if not self.rule_user_groups:
4487 if not self.rule_user_groups:
4488 return rules
4488 return rules
4489
4489
4490 for user_group in self.rule_user_groups:
4490 for user_group in self.rule_user_groups:
4491 user_group_members = [x.user_id for x in user_group.users_group.members]
4491 user_group_members = [x.user_id for x in user_group.users_group.members]
4492 if user_id in user_group_members:
4492 if user_id in user_group_members:
4493 rules.append(user_group)
4493 rules.append(user_group)
4494 return rules
4494 return rules
4495
4495
4496 def __repr__(self):
4496 def __repr__(self):
4497 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4497 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4498 self.repo_review_rule_id, self.repo)
4498 self.repo_review_rule_id, self.repo)
4499
4499
4500
4500
4501 class ScheduleEntry(Base, BaseModel):
4501 class ScheduleEntry(Base, BaseModel):
4502 __tablename__ = 'schedule_entries'
4502 __tablename__ = 'schedule_entries'
4503 __table_args__ = (
4503 __table_args__ = (
4504 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4504 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4505 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4505 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4506 base_table_args,
4506 base_table_args,
4507 )
4507 )
4508
4508
4509 schedule_types = ['crontab', 'timedelta', 'integer']
4509 schedule_types = ['crontab', 'timedelta', 'integer']
4510 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4510 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4511
4511
4512 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4512 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4513 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4513 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4514 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4514 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4515
4515
4516 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4516 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4517 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4517 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4518
4518
4519 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4519 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4520 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4520 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4521
4521
4522 # task
4522 # task
4523 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4523 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4524 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4524 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4525 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4525 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4526 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4526 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4527
4527
4528 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4528 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4529 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4529 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4530
4530
4531 @hybrid_property
4531 @hybrid_property
4532 def schedule_type(self):
4532 def schedule_type(self):
4533 return self._schedule_type
4533 return self._schedule_type
4534
4534
4535 @schedule_type.setter
4535 @schedule_type.setter
4536 def schedule_type(self, val):
4536 def schedule_type(self, val):
4537 if val not in self.schedule_types:
4537 if val not in self.schedule_types:
4538 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4538 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4539 val, self.schedule_type))
4539 val, self.schedule_type))
4540
4540
4541 self._schedule_type = val
4541 self._schedule_type = val
4542
4542
4543 @classmethod
4543 @classmethod
4544 def get_uid(cls, obj):
4544 def get_uid(cls, obj):
4545 args = obj.task_args
4545 args = obj.task_args
4546 kwargs = obj.task_kwargs
4546 kwargs = obj.task_kwargs
4547 if isinstance(args, JsonRaw):
4547 if isinstance(args, JsonRaw):
4548 try:
4548 try:
4549 args = json.loads(args)
4549 args = json.loads(args)
4550 except ValueError:
4550 except ValueError:
4551 args = tuple()
4551 args = tuple()
4552
4552
4553 if isinstance(kwargs, JsonRaw):
4553 if isinstance(kwargs, JsonRaw):
4554 try:
4554 try:
4555 kwargs = json.loads(kwargs)
4555 kwargs = json.loads(kwargs)
4556 except ValueError:
4556 except ValueError:
4557 kwargs = dict()
4557 kwargs = dict()
4558
4558
4559 dot_notation = obj.task_dot_notation
4559 dot_notation = obj.task_dot_notation
4560 val = '.'.join(map(safe_str, [
4560 val = '.'.join(map(safe_str, [
4561 sorted(dot_notation), args, sorted(kwargs.items())]))
4561 sorted(dot_notation), args, sorted(kwargs.items())]))
4562 return hashlib.sha1(val).hexdigest()
4562 return hashlib.sha1(val).hexdigest()
4563
4563
4564 @classmethod
4564 @classmethod
4565 def get_by_schedule_name(cls, schedule_name):
4565 def get_by_schedule_name(cls, schedule_name):
4566 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4566 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4567
4567
4568 @classmethod
4568 @classmethod
4569 def get_by_schedule_id(cls, schedule_id):
4569 def get_by_schedule_id(cls, schedule_id):
4570 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4570 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4571
4571
4572 @property
4572 @property
4573 def task(self):
4573 def task(self):
4574 return self.task_dot_notation
4574 return self.task_dot_notation
4575
4575
4576 @property
4576 @property
4577 def schedule(self):
4577 def schedule(self):
4578 from rhodecode.lib.celerylib.utils import raw_2_schedule
4578 from rhodecode.lib.celerylib.utils import raw_2_schedule
4579 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4579 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4580 return schedule
4580 return schedule
4581
4581
4582 @property
4582 @property
4583 def args(self):
4583 def args(self):
4584 try:
4584 try:
4585 return list(self.task_args or [])
4585 return list(self.task_args or [])
4586 except ValueError:
4586 except ValueError:
4587 return list()
4587 return list()
4588
4588
4589 @property
4589 @property
4590 def kwargs(self):
4590 def kwargs(self):
4591 try:
4591 try:
4592 return dict(self.task_kwargs or {})
4592 return dict(self.task_kwargs or {})
4593 except ValueError:
4593 except ValueError:
4594 return dict()
4594 return dict()
4595
4595
4596 def _as_raw(self, val):
4596 def _as_raw(self, val):
4597 if hasattr(val, 'de_coerce'):
4597 if hasattr(val, 'de_coerce'):
4598 val = val.de_coerce()
4598 val = val.de_coerce()
4599 if val:
4599 if val:
4600 val = json.dumps(val)
4600 val = json.dumps(val)
4601
4601
4602 return val
4602 return val
4603
4603
4604 @property
4604 @property
4605 def schedule_definition_raw(self):
4605 def schedule_definition_raw(self):
4606 return self._as_raw(self.schedule_definition)
4606 return self._as_raw(self.schedule_definition)
4607
4607
4608 @property
4608 @property
4609 def args_raw(self):
4609 def args_raw(self):
4610 return self._as_raw(self.task_args)
4610 return self._as_raw(self.task_args)
4611
4611
4612 @property
4612 @property
4613 def kwargs_raw(self):
4613 def kwargs_raw(self):
4614 return self._as_raw(self.task_kwargs)
4614 return self._as_raw(self.task_kwargs)
4615
4615
4616 def __repr__(self):
4616 def __repr__(self):
4617 return '<DB:ScheduleEntry({}:{})>'.format(
4617 return '<DB:ScheduleEntry({}:{})>'.format(
4618 self.schedule_entry_id, self.schedule_name)
4618 self.schedule_entry_id, self.schedule_name)
4619
4619
4620
4620
4621 @event.listens_for(ScheduleEntry, 'before_update')
4621 @event.listens_for(ScheduleEntry, 'before_update')
4622 def update_task_uid(mapper, connection, target):
4622 def update_task_uid(mapper, connection, target):
4623 target.task_uid = ScheduleEntry.get_uid(target)
4623 target.task_uid = ScheduleEntry.get_uid(target)
4624
4624
4625
4625
4626 @event.listens_for(ScheduleEntry, 'before_insert')
4626 @event.listens_for(ScheduleEntry, 'before_insert')
4627 def set_task_uid(mapper, connection, target):
4627 def set_task_uid(mapper, connection, target):
4628 target.task_uid = ScheduleEntry.get_uid(target)
4628 target.task_uid = ScheduleEntry.get_uid(target)
4629
4629
4630
4630
4631 class _BaseBranchPerms(BaseModel):
4631 class _BaseBranchPerms(BaseModel):
4632 @classmethod
4632 @classmethod
4633 def compute_hash(cls, value):
4633 def compute_hash(cls, value):
4634 return sha1_safe(value)
4634 return sha1_safe(value)
4635
4635
4636 @hybrid_property
4636 @hybrid_property
4637 def branch_pattern(self):
4637 def branch_pattern(self):
4638 return self._branch_pattern or '*'
4638 return self._branch_pattern or '*'
4639
4639
4640 @hybrid_property
4640 @hybrid_property
4641 def branch_hash(self):
4641 def branch_hash(self):
4642 return self._branch_hash
4642 return self._branch_hash
4643
4643
4644 def _validate_glob(self, value):
4644 def _validate_glob(self, value):
4645 re.compile('^' + glob2re(value) + '$')
4645 re.compile('^' + glob2re(value) + '$')
4646
4646
4647 @branch_pattern.setter
4647 @branch_pattern.setter
4648 def branch_pattern(self, value):
4648 def branch_pattern(self, value):
4649 self._validate_glob(value)
4649 self._validate_glob(value)
4650 self._branch_pattern = value or '*'
4650 self._branch_pattern = value or '*'
4651 # set the Hash when setting the branch pattern
4651 # set the Hash when setting the branch pattern
4652 self._branch_hash = self.compute_hash(self._branch_pattern)
4652 self._branch_hash = self.compute_hash(self._branch_pattern)
4653
4653
4654 def matches(self, branch):
4654 def matches(self, branch):
4655 """
4655 """
4656 Check if this the branch matches entry
4656 Check if this the branch matches entry
4657
4657
4658 :param branch: branch name for the commit
4658 :param branch: branch name for the commit
4659 """
4659 """
4660
4660
4661 branch = branch or ''
4661 branch = branch or ''
4662
4662
4663 branch_matches = True
4663 branch_matches = True
4664 if branch:
4664 if branch:
4665 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4665 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4666 branch_matches = bool(branch_regex.search(branch))
4666 branch_matches = bool(branch_regex.search(branch))
4667
4667
4668 return branch_matches
4668 return branch_matches
4669
4669
4670
4670
4671 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4671 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4672 __tablename__ = 'user_to_repo_branch_permissions'
4672 __tablename__ = 'user_to_repo_branch_permissions'
4673 __table_args__ = (
4673 __table_args__ = (
4674 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4674 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4675 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4675 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4676 )
4676 )
4677
4677
4678 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4678 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4679
4679
4680 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4680 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4681 repo = relationship('Repository', backref='user_branch_perms')
4681 repo = relationship('Repository', backref='user_branch_perms')
4682
4682
4683 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4683 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4684 permission = relationship('Permission')
4684 permission = relationship('Permission')
4685
4685
4686 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4686 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4687 user_repo_to_perm = relationship('UserRepoToPerm')
4687 user_repo_to_perm = relationship('UserRepoToPerm')
4688
4688
4689 rule_order = Column('rule_order', Integer(), nullable=False)
4689 rule_order = Column('rule_order', Integer(), nullable=False)
4690 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4690 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4691 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4691 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4692
4692
4693 def __unicode__(self):
4693 def __unicode__(self):
4694 return u'<UserBranchPermission(%s => %r)>' % (
4694 return u'<UserBranchPermission(%s => %r)>' % (
4695 self.user_repo_to_perm, self.branch_pattern)
4695 self.user_repo_to_perm, self.branch_pattern)
4696
4696
4697
4697
4698 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4698 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4699 __tablename__ = 'user_group_to_repo_branch_permissions'
4699 __tablename__ = 'user_group_to_repo_branch_permissions'
4700 __table_args__ = (
4700 __table_args__ = (
4701 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4701 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4702 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4702 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4703 )
4703 )
4704
4704
4705 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4705 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4706
4706
4707 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4707 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4708 repo = relationship('Repository', backref='user_group_branch_perms')
4708 repo = relationship('Repository', backref='user_group_branch_perms')
4709
4709
4710 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4710 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4711 permission = relationship('Permission')
4711 permission = relationship('Permission')
4712
4712
4713 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)
4713 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)
4714 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4714 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4715
4715
4716 rule_order = Column('rule_order', Integer(), nullable=False)
4716 rule_order = Column('rule_order', Integer(), nullable=False)
4717 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4717 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4718 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4718 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4719
4719
4720 def __unicode__(self):
4720 def __unicode__(self):
4721 return u'<UserBranchPermission(%s => %r)>' % (
4721 return u'<UserBranchPermission(%s => %r)>' % (
4722 self.user_group_repo_to_perm, self.branch_pattern)
4722 self.user_group_repo_to_perm, self.branch_pattern)
4723
4723
4724
4724
4725 class DbMigrateVersion(Base, BaseModel):
4725 class DbMigrateVersion(Base, BaseModel):
4726 __tablename__ = 'db_migrate_version'
4726 __tablename__ = 'db_migrate_version'
4727 __table_args__ = (
4727 __table_args__ = (
4728 base_table_args,
4728 base_table_args,
4729 )
4729 )
4730
4730
4731 repository_id = Column('repository_id', String(250), primary_key=True)
4731 repository_id = Column('repository_id', String(250), primary_key=True)
4732 repository_path = Column('repository_path', Text)
4732 repository_path = Column('repository_path', Text)
4733 version = Column('version', Integer)
4733 version = Column('version', Integer)
4734
4734
4735 @classmethod
4735 @classmethod
4736 def set_version(cls, version):
4736 def set_version(cls, version):
4737 """
4737 """
4738 Helper for forcing a different version, usually for debugging purposes via ishell.
4738 Helper for forcing a different version, usually for debugging purposes via ishell.
4739 """
4739 """
4740 ver = DbMigrateVersion.query().first()
4740 ver = DbMigrateVersion.query().first()
4741 ver.version = version
4741 ver.version = version
4742 Session().commit()
4742 Session().commit()
4743
4743
4744
4744
4745 class DbSession(Base, BaseModel):
4745 class DbSession(Base, BaseModel):
4746 __tablename__ = 'db_session'
4746 __tablename__ = 'db_session'
4747 __table_args__ = (
4747 __table_args__ = (
4748 base_table_args,
4748 base_table_args,
4749 )
4749 )
4750
4750
4751 def __repr__(self):
4751 def __repr__(self):
4752 return '<DB:DbSession({})>'.format(self.id)
4752 return '<DB:DbSession({})>'.format(self.id)
4753
4753
4754 id = Column('id', Integer())
4754 id = Column('id', Integer())
4755 namespace = Column('namespace', String(255), primary_key=True)
4755 namespace = Column('namespace', String(255), primary_key=True)
4756 accessed = Column('accessed', DateTime, nullable=False)
4756 accessed = Column('accessed', DateTime, nullable=False)
4757 created = Column('created', DateTime, nullable=False)
4757 created = Column('created', DateTime, nullable=False)
4758 data = Column('data', PickleType, nullable=False)
4758 data = Column('data', PickleType, nullable=False)
@@ -1,4857 +1,4857 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import hashlib
28 import hashlib
29 import logging
29 import logging
30 import datetime
30 import datetime
31 import warnings
31 import warnings
32 import ipaddress
32 import ipaddress
33 import functools
33 import functools
34 import traceback
34 import traceback
35 import collections
35 import collections
36
36
37 from sqlalchemy import (
37 from sqlalchemy import (
38 or_, and_, not_, func, TypeDecorator, event,
38 or_, and_, not_, func, TypeDecorator, event,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 Text, Float, PickleType)
41 Text, Float, PickleType)
42 from sqlalchemy.sql.expression import true, false
42 from sqlalchemy.sql.expression import true, false
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
44 from sqlalchemy.orm import (
44 from sqlalchemy.orm import (
45 relationship, joinedload, class_mapper, validates, aliased)
45 relationship, joinedload, class_mapper, validates, aliased)
46 from sqlalchemy.ext.declarative import declared_attr
46 from sqlalchemy.ext.declarative import declared_attr
47 from sqlalchemy.ext.hybrid import hybrid_property
47 from sqlalchemy.ext.hybrid import hybrid_property
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
49 from sqlalchemy.dialects.mysql import LONGTEXT
49 from sqlalchemy.dialects.mysql import LONGTEXT
50 from zope.cachedescriptors.property import Lazy as LazyProperty
50 from zope.cachedescriptors.property import Lazy as LazyProperty
51 from pyramid import compat
51 from pyramid import compat
52 from pyramid.threadlocal import get_current_request
52 from pyramid.threadlocal import get_current_request
53
53
54 from rhodecode.translation import _
54 from rhodecode.translation import _
55 from rhodecode.lib.vcs import get_vcs_instance
55 from rhodecode.lib.vcs import get_vcs_instance
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
57 from rhodecode.lib.utils2 import (
57 from rhodecode.lib.utils2 import (
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
60 glob2re, StrictAttributeDict, cleaned_uri)
60 glob2re, StrictAttributeDict, cleaned_uri)
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
62 JsonRaw
62 JsonRaw
63 from rhodecode.lib.ext_json import json
63 from rhodecode.lib.ext_json import json
64 from rhodecode.lib.caching_query import FromCache
64 from rhodecode.lib.caching_query import FromCache
65 from rhodecode.lib.encrypt import AESCipher
65 from rhodecode.lib.encrypt import AESCipher
66
66
67 from rhodecode.model.meta import Base, Session
67 from rhodecode.model.meta import Base, Session
68
68
69 URL_SEP = '/'
69 URL_SEP = '/'
70 log = logging.getLogger(__name__)
70 log = logging.getLogger(__name__)
71
71
72 # =============================================================================
72 # =============================================================================
73 # BASE CLASSES
73 # BASE CLASSES
74 # =============================================================================
74 # =============================================================================
75
75
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
77 # beaker.session.secret if first is not set.
77 # beaker.session.secret if first is not set.
78 # and initialized at environment.py
78 # and initialized at environment.py
79 ENCRYPTION_KEY = None
79 ENCRYPTION_KEY = None
80
80
81 # used to sort permissions by types, '#' used here is not allowed to be in
81 # used to sort permissions by types, '#' used here is not allowed to be in
82 # usernames, and it's very early in sorted string.printable table.
82 # usernames, and it's very early in sorted string.printable table.
83 PERMISSION_TYPE_SORT = {
83 PERMISSION_TYPE_SORT = {
84 'admin': '####',
84 'admin': '####',
85 'write': '###',
85 'write': '###',
86 'read': '##',
86 'read': '##',
87 'none': '#',
87 'none': '#',
88 }
88 }
89
89
90
90
91 def display_user_sort(obj):
91 def display_user_sort(obj):
92 """
92 """
93 Sort function used to sort permissions in .permissions() function of
93 Sort function used to sort permissions in .permissions() function of
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
95 of all other resources
95 of all other resources
96 """
96 """
97
97
98 if obj.username == User.DEFAULT_USER:
98 if obj.username == User.DEFAULT_USER:
99 return '#####'
99 return '#####'
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
101 return prefix + obj.username
101 return prefix + obj.username
102
102
103
103
104 def display_user_group_sort(obj):
104 def display_user_group_sort(obj):
105 """
105 """
106 Sort function used to sort permissions in .permissions() function of
106 Sort function used to sort permissions in .permissions() function of
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
108 of all other resources
108 of all other resources
109 """
109 """
110
110
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
112 return prefix + obj.users_group_name
112 return prefix + obj.users_group_name
113
113
114
114
115 def _hash_key(k):
115 def _hash_key(k):
116 return sha1_safe(k)
116 return sha1_safe(k)
117
117
118
118
119 def in_filter_generator(qry, items, limit=500):
119 def in_filter_generator(qry, items, limit=500):
120 """
120 """
121 Splits IN() into multiple with OR
121 Splits IN() into multiple with OR
122 e.g.::
122 e.g.::
123 cnt = Repository.query().filter(
123 cnt = Repository.query().filter(
124 or_(
124 or_(
125 *in_filter_generator(Repository.repo_id, range(100000))
125 *in_filter_generator(Repository.repo_id, range(100000))
126 )).count()
126 )).count()
127 """
127 """
128 if not items:
128 if not items:
129 # empty list will cause empty query which might cause security issues
129 # empty list will cause empty query which might cause security issues
130 # this can lead to hidden unpleasant results
130 # this can lead to hidden unpleasant results
131 items = [-1]
131 items = [-1]
132
132
133 parts = []
133 parts = []
134 for chunk in xrange(0, len(items), limit):
134 for chunk in xrange(0, len(items), limit):
135 parts.append(
135 parts.append(
136 qry.in_(items[chunk: chunk + limit])
136 qry.in_(items[chunk: chunk + limit])
137 )
137 )
138
138
139 return parts
139 return parts
140
140
141
141
142 base_table_args = {
142 base_table_args = {
143 'extend_existing': True,
143 'extend_existing': True,
144 'mysql_engine': 'InnoDB',
144 'mysql_engine': 'InnoDB',
145 'mysql_charset': 'utf8',
145 'mysql_charset': 'utf8',
146 'sqlite_autoincrement': True
146 'sqlite_autoincrement': True
147 }
147 }
148
148
149
149
150 class EncryptedTextValue(TypeDecorator):
150 class EncryptedTextValue(TypeDecorator):
151 """
151 """
152 Special column for encrypted long text data, use like::
152 Special column for encrypted long text data, use like::
153
153
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
155
155
156 This column is intelligent so if value is in unencrypted form it return
156 This column is intelligent so if value is in unencrypted form it return
157 unencrypted form, but on save it always encrypts
157 unencrypted form, but on save it always encrypts
158 """
158 """
159 impl = Text
159 impl = Text
160
160
161 def process_bind_param(self, value, dialect):
161 def process_bind_param(self, value, dialect):
162 if not value:
162 if not value:
163 return value
163 return value
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
165 # protect against double encrypting if someone manually starts
165 # protect against double encrypting if someone manually starts
166 # doing
166 # doing
167 raise ValueError('value needs to be in unencrypted format, ie. '
167 raise ValueError('value needs to be in unencrypted format, ie. '
168 'not starting with enc$aes')
168 'not starting with enc$aes')
169 return 'enc$aes_hmac$%s' % AESCipher(
169 return 'enc$aes_hmac$%s' % AESCipher(
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
171
171
172 def process_result_value(self, value, dialect):
172 def process_result_value(self, value, dialect):
173 import rhodecode
173 import rhodecode
174
174
175 if not value:
175 if not value:
176 return value
176 return value
177
177
178 parts = value.split('$', 3)
178 parts = value.split('$', 3)
179 if not len(parts) == 3:
179 if not len(parts) == 3:
180 # probably not encrypted values
180 # probably not encrypted values
181 return value
181 return value
182 else:
182 else:
183 if parts[0] != 'enc':
183 if parts[0] != 'enc':
184 # parts ok but without our header ?
184 # parts ok but without our header ?
185 return value
185 return value
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
187 'rhodecode.encrypted_values.strict') or True)
187 'rhodecode.encrypted_values.strict') or True)
188 # at that stage we know it's our encryption
188 # at that stage we know it's our encryption
189 if parts[1] == 'aes':
189 if parts[1] == 'aes':
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
191 elif parts[1] == 'aes_hmac':
191 elif parts[1] == 'aes_hmac':
192 decrypted_data = AESCipher(
192 decrypted_data = AESCipher(
193 ENCRYPTION_KEY, hmac=True,
193 ENCRYPTION_KEY, hmac=True,
194 strict_verification=enc_strict_mode).decrypt(parts[2])
194 strict_verification=enc_strict_mode).decrypt(parts[2])
195 else:
195 else:
196 raise ValueError(
196 raise ValueError(
197 'Encryption type part is wrong, must be `aes` '
197 'Encryption type part is wrong, must be `aes` '
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
199 return decrypted_data
199 return decrypted_data
200
200
201
201
202 class BaseModel(object):
202 class BaseModel(object):
203 """
203 """
204 Base Model for all classes
204 Base Model for all classes
205 """
205 """
206
206
207 @classmethod
207 @classmethod
208 def _get_keys(cls):
208 def _get_keys(cls):
209 """return column names for this model """
209 """return column names for this model """
210 return class_mapper(cls).c.keys()
210 return class_mapper(cls).c.keys()
211
211
212 def get_dict(self):
212 def get_dict(self):
213 """
213 """
214 return dict with keys and values corresponding
214 return dict with keys and values corresponding
215 to this model data """
215 to this model data """
216
216
217 d = {}
217 d = {}
218 for k in self._get_keys():
218 for k in self._get_keys():
219 d[k] = getattr(self, k)
219 d[k] = getattr(self, k)
220
220
221 # also use __json__() if present to get additional fields
221 # also use __json__() if present to get additional fields
222 _json_attr = getattr(self, '__json__', None)
222 _json_attr = getattr(self, '__json__', None)
223 if _json_attr:
223 if _json_attr:
224 # update with attributes from __json__
224 # update with attributes from __json__
225 if callable(_json_attr):
225 if callable(_json_attr):
226 _json_attr = _json_attr()
226 _json_attr = _json_attr()
227 for k, val in _json_attr.iteritems():
227 for k, val in _json_attr.iteritems():
228 d[k] = val
228 d[k] = val
229 return d
229 return d
230
230
231 def get_appstruct(self):
231 def get_appstruct(self):
232 """return list with keys and values tuples corresponding
232 """return list with keys and values tuples corresponding
233 to this model data """
233 to this model data """
234
234
235 lst = []
235 lst = []
236 for k in self._get_keys():
236 for k in self._get_keys():
237 lst.append((k, getattr(self, k),))
237 lst.append((k, getattr(self, k),))
238 return lst
238 return lst
239
239
240 def populate_obj(self, populate_dict):
240 def populate_obj(self, populate_dict):
241 """populate model with data from given populate_dict"""
241 """populate model with data from given populate_dict"""
242
242
243 for k in self._get_keys():
243 for k in self._get_keys():
244 if k in populate_dict:
244 if k in populate_dict:
245 setattr(self, k, populate_dict[k])
245 setattr(self, k, populate_dict[k])
246
246
247 @classmethod
247 @classmethod
248 def query(cls):
248 def query(cls):
249 return Session().query(cls)
249 return Session().query(cls)
250
250
251 @classmethod
251 @classmethod
252 def get(cls, id_):
252 def get(cls, id_):
253 if id_:
253 if id_:
254 return cls.query().get(id_)
254 return cls.query().get(id_)
255
255
256 @classmethod
256 @classmethod
257 def get_or_404(cls, id_):
257 def get_or_404(cls, id_):
258 from pyramid.httpexceptions import HTTPNotFound
258 from pyramid.httpexceptions import HTTPNotFound
259
259
260 try:
260 try:
261 id_ = int(id_)
261 id_ = int(id_)
262 except (TypeError, ValueError):
262 except (TypeError, ValueError):
263 raise HTTPNotFound()
263 raise HTTPNotFound()
264
264
265 res = cls.query().get(id_)
265 res = cls.query().get(id_)
266 if not res:
266 if not res:
267 raise HTTPNotFound()
267 raise HTTPNotFound()
268 return res
268 return res
269
269
270 @classmethod
270 @classmethod
271 def getAll(cls):
271 def getAll(cls):
272 # deprecated and left for backward compatibility
272 # deprecated and left for backward compatibility
273 return cls.get_all()
273 return cls.get_all()
274
274
275 @classmethod
275 @classmethod
276 def get_all(cls):
276 def get_all(cls):
277 return cls.query().all()
277 return cls.query().all()
278
278
279 @classmethod
279 @classmethod
280 def delete(cls, id_):
280 def delete(cls, id_):
281 obj = cls.query().get(id_)
281 obj = cls.query().get(id_)
282 Session().delete(obj)
282 Session().delete(obj)
283
283
284 @classmethod
284 @classmethod
285 def identity_cache(cls, session, attr_name, value):
285 def identity_cache(cls, session, attr_name, value):
286 exist_in_session = []
286 exist_in_session = []
287 for (item_cls, pkey), instance in session.identity_map.items():
287 for (item_cls, pkey), instance in session.identity_map.items():
288 if cls == item_cls and getattr(instance, attr_name) == value:
288 if cls == item_cls and getattr(instance, attr_name) == value:
289 exist_in_session.append(instance)
289 exist_in_session.append(instance)
290 if exist_in_session:
290 if exist_in_session:
291 if len(exist_in_session) == 1:
291 if len(exist_in_session) == 1:
292 return exist_in_session[0]
292 return exist_in_session[0]
293 log.exception(
293 log.exception(
294 'multiple objects with attr %s and '
294 'multiple objects with attr %s and '
295 'value %s found with same name: %r',
295 'value %s found with same name: %r',
296 attr_name, value, exist_in_session)
296 attr_name, value, exist_in_session)
297
297
298 def __repr__(self):
298 def __repr__(self):
299 if hasattr(self, '__unicode__'):
299 if hasattr(self, '__unicode__'):
300 # python repr needs to return str
300 # python repr needs to return str
301 try:
301 try:
302 return safe_str(self.__unicode__())
302 return safe_str(self.__unicode__())
303 except UnicodeDecodeError:
303 except UnicodeDecodeError:
304 pass
304 pass
305 return '<DB:%s>' % (self.__class__.__name__)
305 return '<DB:%s>' % (self.__class__.__name__)
306
306
307
307
308 class RhodeCodeSetting(Base, BaseModel):
308 class RhodeCodeSetting(Base, BaseModel):
309 __tablename__ = 'rhodecode_settings'
309 __tablename__ = 'rhodecode_settings'
310 __table_args__ = (
310 __table_args__ = (
311 UniqueConstraint('app_settings_name'),
311 UniqueConstraint('app_settings_name'),
312 base_table_args
312 base_table_args
313 )
313 )
314
314
315 SETTINGS_TYPES = {
315 SETTINGS_TYPES = {
316 'str': safe_str,
316 'str': safe_str,
317 'int': safe_int,
317 'int': safe_int,
318 'unicode': safe_unicode,
318 'unicode': safe_unicode,
319 'bool': str2bool,
319 'bool': str2bool,
320 'list': functools.partial(aslist, sep=',')
320 'list': functools.partial(aslist, sep=',')
321 }
321 }
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
323 GLOBAL_CONF_KEY = 'app_settings'
323 GLOBAL_CONF_KEY = 'app_settings'
324
324
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
329
329
330 def __init__(self, key='', val='', type='unicode'):
330 def __init__(self, key='', val='', type='unicode'):
331 self.app_settings_name = key
331 self.app_settings_name = key
332 self.app_settings_type = type
332 self.app_settings_type = type
333 self.app_settings_value = val
333 self.app_settings_value = val
334
334
335 @validates('_app_settings_value')
335 @validates('_app_settings_value')
336 def validate_settings_value(self, key, val):
336 def validate_settings_value(self, key, val):
337 assert type(val) == unicode
337 assert type(val) == unicode
338 return val
338 return val
339
339
340 @hybrid_property
340 @hybrid_property
341 def app_settings_value(self):
341 def app_settings_value(self):
342 v = self._app_settings_value
342 v = self._app_settings_value
343 _type = self.app_settings_type
343 _type = self.app_settings_type
344 if _type:
344 if _type:
345 _type = self.app_settings_type.split('.')[0]
345 _type = self.app_settings_type.split('.')[0]
346 # decode the encrypted value
346 # decode the encrypted value
347 if 'encrypted' in self.app_settings_type:
347 if 'encrypted' in self.app_settings_type:
348 cipher = EncryptedTextValue()
348 cipher = EncryptedTextValue()
349 v = safe_unicode(cipher.process_result_value(v, None))
349 v = safe_unicode(cipher.process_result_value(v, None))
350
350
351 converter = self.SETTINGS_TYPES.get(_type) or \
351 converter = self.SETTINGS_TYPES.get(_type) or \
352 self.SETTINGS_TYPES['unicode']
352 self.SETTINGS_TYPES['unicode']
353 return converter(v)
353 return converter(v)
354
354
355 @app_settings_value.setter
355 @app_settings_value.setter
356 def app_settings_value(self, val):
356 def app_settings_value(self, val):
357 """
357 """
358 Setter that will always make sure we use unicode in app_settings_value
358 Setter that will always make sure we use unicode in app_settings_value
359
359
360 :param val:
360 :param val:
361 """
361 """
362 val = safe_unicode(val)
362 val = safe_unicode(val)
363 # encode the encrypted value
363 # encode the encrypted value
364 if 'encrypted' in self.app_settings_type:
364 if 'encrypted' in self.app_settings_type:
365 cipher = EncryptedTextValue()
365 cipher = EncryptedTextValue()
366 val = safe_unicode(cipher.process_bind_param(val, None))
366 val = safe_unicode(cipher.process_bind_param(val, None))
367 self._app_settings_value = val
367 self._app_settings_value = val
368
368
369 @hybrid_property
369 @hybrid_property
370 def app_settings_type(self):
370 def app_settings_type(self):
371 return self._app_settings_type
371 return self._app_settings_type
372
372
373 @app_settings_type.setter
373 @app_settings_type.setter
374 def app_settings_type(self, val):
374 def app_settings_type(self, val):
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
376 raise Exception('type must be one of %s got %s'
376 raise Exception('type must be one of %s got %s'
377 % (self.SETTINGS_TYPES.keys(), val))
377 % (self.SETTINGS_TYPES.keys(), val))
378 self._app_settings_type = val
378 self._app_settings_type = val
379
379
380 @classmethod
380 @classmethod
381 def get_by_prefix(cls, prefix):
381 def get_by_prefix(cls, prefix):
382 return RhodeCodeSetting.query()\
382 return RhodeCodeSetting.query()\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
384 .all()
384 .all()
385
385
386 def __unicode__(self):
386 def __unicode__(self):
387 return u"<%s('%s:%s[%s]')>" % (
387 return u"<%s('%s:%s[%s]')>" % (
388 self.__class__.__name__,
388 self.__class__.__name__,
389 self.app_settings_name, self.app_settings_value,
389 self.app_settings_name, self.app_settings_value,
390 self.app_settings_type
390 self.app_settings_type
391 )
391 )
392
392
393
393
394 class RhodeCodeUi(Base, BaseModel):
394 class RhodeCodeUi(Base, BaseModel):
395 __tablename__ = 'rhodecode_ui'
395 __tablename__ = 'rhodecode_ui'
396 __table_args__ = (
396 __table_args__ = (
397 UniqueConstraint('ui_key'),
397 UniqueConstraint('ui_key'),
398 base_table_args
398 base_table_args
399 )
399 )
400
400
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
402 # HG
402 # HG
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
404 HOOK_PULL = 'outgoing.pull_logger'
404 HOOK_PULL = 'outgoing.pull_logger'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
407 HOOK_PUSH = 'changegroup.push_logger'
407 HOOK_PUSH = 'changegroup.push_logger'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
409
409
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
411 # git part is currently hardcoded.
411 # git part is currently hardcoded.
412
412
413 # SVN PATTERNS
413 # SVN PATTERNS
414 SVN_BRANCH_ID = 'vcs_svn_branch'
414 SVN_BRANCH_ID = 'vcs_svn_branch'
415 SVN_TAG_ID = 'vcs_svn_tag'
415 SVN_TAG_ID = 'vcs_svn_tag'
416
416
417 ui_id = Column(
417 ui_id = Column(
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
419 primary_key=True)
419 primary_key=True)
420 ui_section = Column(
420 ui_section = Column(
421 "ui_section", String(255), nullable=True, unique=None, default=None)
421 "ui_section", String(255), nullable=True, unique=None, default=None)
422 ui_key = Column(
422 ui_key = Column(
423 "ui_key", String(255), nullable=True, unique=None, default=None)
423 "ui_key", String(255), nullable=True, unique=None, default=None)
424 ui_value = Column(
424 ui_value = Column(
425 "ui_value", String(255), nullable=True, unique=None, default=None)
425 "ui_value", String(255), nullable=True, unique=None, default=None)
426 ui_active = Column(
426 ui_active = Column(
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
428
428
429 def __repr__(self):
429 def __repr__(self):
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
431 self.ui_key, self.ui_value)
431 self.ui_key, self.ui_value)
432
432
433
433
434 class RepoRhodeCodeSetting(Base, BaseModel):
434 class RepoRhodeCodeSetting(Base, BaseModel):
435 __tablename__ = 'repo_rhodecode_settings'
435 __tablename__ = 'repo_rhodecode_settings'
436 __table_args__ = (
436 __table_args__ = (
437 UniqueConstraint(
437 UniqueConstraint(
438 'app_settings_name', 'repository_id',
438 'app_settings_name', 'repository_id',
439 name='uq_repo_rhodecode_setting_name_repo_id'),
439 name='uq_repo_rhodecode_setting_name_repo_id'),
440 base_table_args
440 base_table_args
441 )
441 )
442
442
443 repository_id = Column(
443 repository_id = Column(
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
445 nullable=False)
445 nullable=False)
446 app_settings_id = Column(
446 app_settings_id = Column(
447 "app_settings_id", Integer(), nullable=False, unique=True,
447 "app_settings_id", Integer(), nullable=False, unique=True,
448 default=None, primary_key=True)
448 default=None, primary_key=True)
449 app_settings_name = Column(
449 app_settings_name = Column(
450 "app_settings_name", String(255), nullable=True, unique=None,
450 "app_settings_name", String(255), nullable=True, unique=None,
451 default=None)
451 default=None)
452 _app_settings_value = Column(
452 _app_settings_value = Column(
453 "app_settings_value", String(4096), nullable=True, unique=None,
453 "app_settings_value", String(4096), nullable=True, unique=None,
454 default=None)
454 default=None)
455 _app_settings_type = Column(
455 _app_settings_type = Column(
456 "app_settings_type", String(255), nullable=True, unique=None,
456 "app_settings_type", String(255), nullable=True, unique=None,
457 default=None)
457 default=None)
458
458
459 repository = relationship('Repository')
459 repository = relationship('Repository')
460
460
461 def __init__(self, repository_id, key='', val='', type='unicode'):
461 def __init__(self, repository_id, key='', val='', type='unicode'):
462 self.repository_id = repository_id
462 self.repository_id = repository_id
463 self.app_settings_name = key
463 self.app_settings_name = key
464 self.app_settings_type = type
464 self.app_settings_type = type
465 self.app_settings_value = val
465 self.app_settings_value = val
466
466
467 @validates('_app_settings_value')
467 @validates('_app_settings_value')
468 def validate_settings_value(self, key, val):
468 def validate_settings_value(self, key, val):
469 assert type(val) == unicode
469 assert type(val) == unicode
470 return val
470 return val
471
471
472 @hybrid_property
472 @hybrid_property
473 def app_settings_value(self):
473 def app_settings_value(self):
474 v = self._app_settings_value
474 v = self._app_settings_value
475 type_ = self.app_settings_type
475 type_ = self.app_settings_type
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
478 return converter(v)
478 return converter(v)
479
479
480 @app_settings_value.setter
480 @app_settings_value.setter
481 def app_settings_value(self, val):
481 def app_settings_value(self, val):
482 """
482 """
483 Setter that will always make sure we use unicode in app_settings_value
483 Setter that will always make sure we use unicode in app_settings_value
484
484
485 :param val:
485 :param val:
486 """
486 """
487 self._app_settings_value = safe_unicode(val)
487 self._app_settings_value = safe_unicode(val)
488
488
489 @hybrid_property
489 @hybrid_property
490 def app_settings_type(self):
490 def app_settings_type(self):
491 return self._app_settings_type
491 return self._app_settings_type
492
492
493 @app_settings_type.setter
493 @app_settings_type.setter
494 def app_settings_type(self, val):
494 def app_settings_type(self, val):
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
496 if val not in SETTINGS_TYPES:
496 if val not in SETTINGS_TYPES:
497 raise Exception('type must be one of %s got %s'
497 raise Exception('type must be one of %s got %s'
498 % (SETTINGS_TYPES.keys(), val))
498 % (SETTINGS_TYPES.keys(), val))
499 self._app_settings_type = val
499 self._app_settings_type = val
500
500
501 def __unicode__(self):
501 def __unicode__(self):
502 return u"<%s('%s:%s:%s[%s]')>" % (
502 return u"<%s('%s:%s:%s[%s]')>" % (
503 self.__class__.__name__, self.repository.repo_name,
503 self.__class__.__name__, self.repository.repo_name,
504 self.app_settings_name, self.app_settings_value,
504 self.app_settings_name, self.app_settings_value,
505 self.app_settings_type
505 self.app_settings_type
506 )
506 )
507
507
508
508
509 class RepoRhodeCodeUi(Base, BaseModel):
509 class RepoRhodeCodeUi(Base, BaseModel):
510 __tablename__ = 'repo_rhodecode_ui'
510 __tablename__ = 'repo_rhodecode_ui'
511 __table_args__ = (
511 __table_args__ = (
512 UniqueConstraint(
512 UniqueConstraint(
513 'repository_id', 'ui_section', 'ui_key',
513 'repository_id', 'ui_section', 'ui_key',
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
515 base_table_args
515 base_table_args
516 )
516 )
517
517
518 repository_id = Column(
518 repository_id = Column(
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
520 nullable=False)
520 nullable=False)
521 ui_id = Column(
521 ui_id = Column(
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
523 primary_key=True)
523 primary_key=True)
524 ui_section = Column(
524 ui_section = Column(
525 "ui_section", String(255), nullable=True, unique=None, default=None)
525 "ui_section", String(255), nullable=True, unique=None, default=None)
526 ui_key = Column(
526 ui_key = Column(
527 "ui_key", String(255), nullable=True, unique=None, default=None)
527 "ui_key", String(255), nullable=True, unique=None, default=None)
528 ui_value = Column(
528 ui_value = Column(
529 "ui_value", String(255), nullable=True, unique=None, default=None)
529 "ui_value", String(255), nullable=True, unique=None, default=None)
530 ui_active = Column(
530 ui_active = Column(
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
532
532
533 repository = relationship('Repository')
533 repository = relationship('Repository')
534
534
535 def __repr__(self):
535 def __repr__(self):
536 return '<%s[%s:%s]%s=>%s]>' % (
536 return '<%s[%s:%s]%s=>%s]>' % (
537 self.__class__.__name__, self.repository.repo_name,
537 self.__class__.__name__, self.repository.repo_name,
538 self.ui_section, self.ui_key, self.ui_value)
538 self.ui_section, self.ui_key, self.ui_value)
539
539
540
540
541 class User(Base, BaseModel):
541 class User(Base, BaseModel):
542 __tablename__ = 'users'
542 __tablename__ = 'users'
543 __table_args__ = (
543 __table_args__ = (
544 UniqueConstraint('username'), UniqueConstraint('email'),
544 UniqueConstraint('username'), UniqueConstraint('email'),
545 Index('u_username_idx', 'username'),
545 Index('u_username_idx', 'username'),
546 Index('u_email_idx', 'email'),
546 Index('u_email_idx', 'email'),
547 base_table_args
547 base_table_args
548 )
548 )
549
549
550 DEFAULT_USER = 'default'
550 DEFAULT_USER = 'default'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
553
553
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
564
564
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
571
571
572 user_log = relationship('UserLog')
572 user_log = relationship('UserLog')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
574
574
575 repositories = relationship('Repository')
575 repositories = relationship('Repository')
576 repository_groups = relationship('RepoGroup')
576 repository_groups = relationship('RepoGroup')
577 user_groups = relationship('UserGroup')
577 user_groups = relationship('UserGroup')
578
578
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
581
581
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
585
585
586 group_member = relationship('UserGroupMember', cascade='all')
586 group_member = relationship('UserGroupMember', cascade='all')
587
587
588 notifications = relationship('UserNotification', cascade='all')
588 notifications = relationship('UserNotification', cascade='all')
589 # notifications assigned to this user
589 # notifications assigned to this user
590 user_created_notifications = relationship('Notification', cascade='all')
590 user_created_notifications = relationship('Notification', cascade='all')
591 # comments created by this user
591 # comments created by this user
592 user_comments = relationship('ChangesetComment', cascade='all')
592 user_comments = relationship('ChangesetComment', cascade='all')
593 # user profile extra info
593 # user profile extra info
594 user_emails = relationship('UserEmailMap', cascade='all')
594 user_emails = relationship('UserEmailMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
598
598
599 # gists
599 # gists
600 user_gists = relationship('Gist', cascade='all')
600 user_gists = relationship('Gist', cascade='all')
601 # user pull requests
601 # user pull requests
602 user_pull_requests = relationship('PullRequest', cascade='all')
602 user_pull_requests = relationship('PullRequest', cascade='all')
603 # external identities
603 # external identities
604 extenal_identities = relationship(
604 extenal_identities = relationship(
605 'ExternalIdentity',
605 'ExternalIdentity',
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
607 cascade='all')
607 cascade='all')
608 # review rules
608 # review rules
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
610
610
611 def __unicode__(self):
611 def __unicode__(self):
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
613 self.user_id, self.username)
613 self.user_id, self.username)
614
614
615 @hybrid_property
615 @hybrid_property
616 def email(self):
616 def email(self):
617 return self._email
617 return self._email
618
618
619 @email.setter
619 @email.setter
620 def email(self, val):
620 def email(self, val):
621 self._email = val.lower() if val else None
621 self._email = val.lower() if val else None
622
622
623 @hybrid_property
623 @hybrid_property
624 def first_name(self):
624 def first_name(self):
625 from rhodecode.lib import helpers as h
625 from rhodecode.lib import helpers as h
626 if self.name:
626 if self.name:
627 return h.escape(self.name)
627 return h.escape(self.name)
628 return self.name
628 return self.name
629
629
630 @hybrid_property
630 @hybrid_property
631 def last_name(self):
631 def last_name(self):
632 from rhodecode.lib import helpers as h
632 from rhodecode.lib import helpers as h
633 if self.lastname:
633 if self.lastname:
634 return h.escape(self.lastname)
634 return h.escape(self.lastname)
635 return self.lastname
635 return self.lastname
636
636
637 @hybrid_property
637 @hybrid_property
638 def api_key(self):
638 def api_key(self):
639 """
639 """
640 Fetch if exist an auth-token with role ALL connected to this user
640 Fetch if exist an auth-token with role ALL connected to this user
641 """
641 """
642 user_auth_token = UserApiKeys.query()\
642 user_auth_token = UserApiKeys.query()\
643 .filter(UserApiKeys.user_id == self.user_id)\
643 .filter(UserApiKeys.user_id == self.user_id)\
644 .filter(or_(UserApiKeys.expires == -1,
644 .filter(or_(UserApiKeys.expires == -1,
645 UserApiKeys.expires >= time.time()))\
645 UserApiKeys.expires >= time.time()))\
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
647 if user_auth_token:
647 if user_auth_token:
648 user_auth_token = user_auth_token.api_key
648 user_auth_token = user_auth_token.api_key
649
649
650 return user_auth_token
650 return user_auth_token
651
651
652 @api_key.setter
652 @api_key.setter
653 def api_key(self, val):
653 def api_key(self, val):
654 # don't allow to set API key this is deprecated for now
654 # don't allow to set API key this is deprecated for now
655 self._api_key = None
655 self._api_key = None
656
656
657 @property
657 @property
658 def reviewer_pull_requests(self):
658 def reviewer_pull_requests(self):
659 return PullRequestReviewers.query() \
659 return PullRequestReviewers.query() \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
662 .all()
662 .all()
663
663
664 @property
664 @property
665 def firstname(self):
665 def firstname(self):
666 # alias for future
666 # alias for future
667 return self.name
667 return self.name
668
668
669 @property
669 @property
670 def emails(self):
670 def emails(self):
671 other = UserEmailMap.query()\
671 other = UserEmailMap.query()\
672 .filter(UserEmailMap.user == self) \
672 .filter(UserEmailMap.user == self) \
673 .order_by(UserEmailMap.email_id.asc()) \
673 .order_by(UserEmailMap.email_id.asc()) \
674 .all()
674 .all()
675 return [self.email] + [x.email for x in other]
675 return [self.email] + [x.email for x in other]
676
676
677 @property
677 @property
678 def auth_tokens(self):
678 def auth_tokens(self):
679 auth_tokens = self.get_auth_tokens()
679 auth_tokens = self.get_auth_tokens()
680 return [x.api_key for x in auth_tokens]
680 return [x.api_key for x in auth_tokens]
681
681
682 def get_auth_tokens(self):
682 def get_auth_tokens(self):
683 return UserApiKeys.query()\
683 return UserApiKeys.query()\
684 .filter(UserApiKeys.user == self)\
684 .filter(UserApiKeys.user == self)\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
686 .all()
686 .all()
687
687
688 @LazyProperty
688 @LazyProperty
689 def feed_token(self):
689 def feed_token(self):
690 return self.get_feed_token()
690 return self.get_feed_token()
691
691
692 def get_feed_token(self, cache=True):
692 def get_feed_token(self, cache=True):
693 feed_tokens = UserApiKeys.query()\
693 feed_tokens = UserApiKeys.query()\
694 .filter(UserApiKeys.user == self)\
694 .filter(UserApiKeys.user == self)\
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
696 if cache:
696 if cache:
697 feed_tokens = feed_tokens.options(
697 feed_tokens = feed_tokens.options(
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
699
699
700 feed_tokens = feed_tokens.all()
700 feed_tokens = feed_tokens.all()
701 if feed_tokens:
701 if feed_tokens:
702 return feed_tokens[0].api_key
702 return feed_tokens[0].api_key
703 return 'NO_FEED_TOKEN_AVAILABLE'
703 return 'NO_FEED_TOKEN_AVAILABLE'
704
704
705 @classmethod
705 @classmethod
706 def get(cls, user_id, cache=False):
706 def get(cls, user_id, cache=False):
707 if not user_id:
707 if not user_id:
708 return
708 return
709
709
710 user = cls.query()
710 user = cls.query()
711 if cache:
711 if cache:
712 user = user.options(
712 user = user.options(
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
714 return user.get(user_id)
714 return user.get(user_id)
715
715
716 @classmethod
716 @classmethod
717 def extra_valid_auth_tokens(cls, user, role=None):
717 def extra_valid_auth_tokens(cls, user, role=None):
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
719 .filter(or_(UserApiKeys.expires == -1,
719 .filter(or_(UserApiKeys.expires == -1,
720 UserApiKeys.expires >= time.time()))
720 UserApiKeys.expires >= time.time()))
721 if role:
721 if role:
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
724 return tokens.all()
724 return tokens.all()
725
725
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
727 from rhodecode.lib import auth
727 from rhodecode.lib import auth
728
728
729 log.debug('Trying to authenticate user: %s via auth-token, '
729 log.debug('Trying to authenticate user: %s via auth-token, '
730 'and roles: %s', self, roles)
730 'and roles: %s', self, roles)
731
731
732 if not auth_token:
732 if not auth_token:
733 return False
733 return False
734
734
735 crypto_backend = auth.crypto_backend()
735 crypto_backend = auth.crypto_backend()
736
736
737 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
737 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
738 tokens_q = UserApiKeys.query()\
738 tokens_q = UserApiKeys.query()\
739 .filter(UserApiKeys.user_id == self.user_id)\
739 .filter(UserApiKeys.user_id == self.user_id)\
740 .filter(or_(UserApiKeys.expires == -1,
740 .filter(or_(UserApiKeys.expires == -1,
741 UserApiKeys.expires >= time.time()))
741 UserApiKeys.expires >= time.time()))
742
742
743 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
743 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
744
744
745 plain_tokens = []
745 plain_tokens = []
746 hash_tokens = []
746 hash_tokens = []
747
747
748 user_tokens = tokens_q.all()
748 user_tokens = tokens_q.all()
749 log.debug('Found %s user tokens to check for authentication', len(user_tokens))
749 log.debug('Found %s user tokens to check for authentication', len(user_tokens))
750 for token in user_tokens:
750 for token in user_tokens:
751 log.debug('AUTH_TOKEN: checking if user token with id `%s` matches',
751 log.debug('AUTH_TOKEN: checking if user token with id `%s` matches',
752 token.user_api_key_id)
752 token.user_api_key_id)
753 # verify scope first, since it's way faster than hash calculation of
753 # verify scope first, since it's way faster than hash calculation of
754 # encrypted tokens
754 # encrypted tokens
755 if token.repo_id:
755 if token.repo_id:
756 # token has a scope, we need to verify it
756 # token has a scope, we need to verify it
757 if scope_repo_id != token.repo_id:
757 if scope_repo_id != token.repo_id:
758 log.debug(
758 log.debug(
759 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
759 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
760 'and calling scope is:%s, skipping further checks',
760 'and calling scope is:%s, skipping further checks',
761 token.repo, scope_repo_id)
761 token.repo, scope_repo_id)
762 # token has a scope, and it doesn't match, skip token
762 # token has a scope, and it doesn't match, skip token
763 continue
763 continue
764
764
765 if token.api_key.startswith(crypto_backend.ENC_PREF):
765 if token.api_key.startswith(crypto_backend.ENC_PREF):
766 hash_tokens.append(token.api_key)
766 hash_tokens.append(token.api_key)
767 else:
767 else:
768 plain_tokens.append(token.api_key)
768 plain_tokens.append(token.api_key)
769
769
770 is_plain_match = auth_token in plain_tokens
770 is_plain_match = auth_token in plain_tokens
771 if is_plain_match:
771 if is_plain_match:
772 return True
772 return True
773
773
774 for hashed in hash_tokens:
774 for hashed in hash_tokens:
775 # NOTE(marcink): this is expensive to calculate, but most secure
775 # NOTE(marcink): this is expensive to calculate, but most secure
776 match = crypto_backend.hash_check(auth_token, hashed)
776 match = crypto_backend.hash_check(auth_token, hashed)
777 if match:
777 if match:
778 return True
778 return True
779
779
780 return False
780 return False
781
781
782 @property
782 @property
783 def ip_addresses(self):
783 def ip_addresses(self):
784 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
784 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
785 return [x.ip_addr for x in ret]
785 return [x.ip_addr for x in ret]
786
786
787 @property
787 @property
788 def username_and_name(self):
788 def username_and_name(self):
789 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
789 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
790
790
791 @property
791 @property
792 def username_or_name_or_email(self):
792 def username_or_name_or_email(self):
793 full_name = self.full_name if self.full_name is not ' ' else None
793 full_name = self.full_name if self.full_name is not ' ' else None
794 return self.username or full_name or self.email
794 return self.username or full_name or self.email
795
795
796 @property
796 @property
797 def full_name(self):
797 def full_name(self):
798 return '%s %s' % (self.first_name, self.last_name)
798 return '%s %s' % (self.first_name, self.last_name)
799
799
800 @property
800 @property
801 def full_name_or_username(self):
801 def full_name_or_username(self):
802 return ('%s %s' % (self.first_name, self.last_name)
802 return ('%s %s' % (self.first_name, self.last_name)
803 if (self.first_name and self.last_name) else self.username)
803 if (self.first_name and self.last_name) else self.username)
804
804
805 @property
805 @property
806 def full_contact(self):
806 def full_contact(self):
807 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
807 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
808
808
809 @property
809 @property
810 def short_contact(self):
810 def short_contact(self):
811 return '%s %s' % (self.first_name, self.last_name)
811 return '%s %s' % (self.first_name, self.last_name)
812
812
813 @property
813 @property
814 def is_admin(self):
814 def is_admin(self):
815 return self.admin
815 return self.admin
816
816
817 def AuthUser(self, **kwargs):
817 def AuthUser(self, **kwargs):
818 """
818 """
819 Returns instance of AuthUser for this user
819 Returns instance of AuthUser for this user
820 """
820 """
821 from rhodecode.lib.auth import AuthUser
821 from rhodecode.lib.auth import AuthUser
822 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
822 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
823
823
824 @hybrid_property
824 @hybrid_property
825 def user_data(self):
825 def user_data(self):
826 if not self._user_data:
826 if not self._user_data:
827 return {}
827 return {}
828
828
829 try:
829 try:
830 return json.loads(self._user_data)
830 return json.loads(self._user_data)
831 except TypeError:
831 except TypeError:
832 return {}
832 return {}
833
833
834 @user_data.setter
834 @user_data.setter
835 def user_data(self, val):
835 def user_data(self, val):
836 if not isinstance(val, dict):
836 if not isinstance(val, dict):
837 raise Exception('user_data must be dict, got %s' % type(val))
837 raise Exception('user_data must be dict, got %s' % type(val))
838 try:
838 try:
839 self._user_data = json.dumps(val)
839 self._user_data = json.dumps(val)
840 except Exception:
840 except Exception:
841 log.error(traceback.format_exc())
841 log.error(traceback.format_exc())
842
842
843 @classmethod
843 @classmethod
844 def get_by_username(cls, username, case_insensitive=False,
844 def get_by_username(cls, username, case_insensitive=False,
845 cache=False, identity_cache=False):
845 cache=False, identity_cache=False):
846 session = Session()
846 session = Session()
847
847
848 if case_insensitive:
848 if case_insensitive:
849 q = cls.query().filter(
849 q = cls.query().filter(
850 func.lower(cls.username) == func.lower(username))
850 func.lower(cls.username) == func.lower(username))
851 else:
851 else:
852 q = cls.query().filter(cls.username == username)
852 q = cls.query().filter(cls.username == username)
853
853
854 if cache:
854 if cache:
855 if identity_cache:
855 if identity_cache:
856 val = cls.identity_cache(session, 'username', username)
856 val = cls.identity_cache(session, 'username', username)
857 if val:
857 if val:
858 return val
858 return val
859 else:
859 else:
860 cache_key = "get_user_by_name_%s" % _hash_key(username)
860 cache_key = "get_user_by_name_%s" % _hash_key(username)
861 q = q.options(
861 q = q.options(
862 FromCache("sql_cache_short", cache_key))
862 FromCache("sql_cache_short", cache_key))
863
863
864 return q.scalar()
864 return q.scalar()
865
865
866 @classmethod
866 @classmethod
867 def get_by_auth_token(cls, auth_token, cache=False):
867 def get_by_auth_token(cls, auth_token, cache=False):
868 q = UserApiKeys.query()\
868 q = UserApiKeys.query()\
869 .filter(UserApiKeys.api_key == auth_token)\
869 .filter(UserApiKeys.api_key == auth_token)\
870 .filter(or_(UserApiKeys.expires == -1,
870 .filter(or_(UserApiKeys.expires == -1,
871 UserApiKeys.expires >= time.time()))
871 UserApiKeys.expires >= time.time()))
872 if cache:
872 if cache:
873 q = q.options(
873 q = q.options(
874 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
874 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
875
875
876 match = q.first()
876 match = q.first()
877 if match:
877 if match:
878 return match.user
878 return match.user
879
879
880 @classmethod
880 @classmethod
881 def get_by_email(cls, email, case_insensitive=False, cache=False):
881 def get_by_email(cls, email, case_insensitive=False, cache=False):
882
882
883 if case_insensitive:
883 if case_insensitive:
884 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
884 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
885
885
886 else:
886 else:
887 q = cls.query().filter(cls.email == email)
887 q = cls.query().filter(cls.email == email)
888
888
889 email_key = _hash_key(email)
889 email_key = _hash_key(email)
890 if cache:
890 if cache:
891 q = q.options(
891 q = q.options(
892 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
892 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
893
893
894 ret = q.scalar()
894 ret = q.scalar()
895 if ret is None:
895 if ret is None:
896 q = UserEmailMap.query()
896 q = UserEmailMap.query()
897 # try fetching in alternate email map
897 # try fetching in alternate email map
898 if case_insensitive:
898 if case_insensitive:
899 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
899 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
900 else:
900 else:
901 q = q.filter(UserEmailMap.email == email)
901 q = q.filter(UserEmailMap.email == email)
902 q = q.options(joinedload(UserEmailMap.user))
902 q = q.options(joinedload(UserEmailMap.user))
903 if cache:
903 if cache:
904 q = q.options(
904 q = q.options(
905 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
905 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
906 ret = getattr(q.scalar(), 'user', None)
906 ret = getattr(q.scalar(), 'user', None)
907
907
908 return ret
908 return ret
909
909
910 @classmethod
910 @classmethod
911 def get_from_cs_author(cls, author):
911 def get_from_cs_author(cls, author):
912 """
912 """
913 Tries to get User objects out of commit author string
913 Tries to get User objects out of commit author string
914
914
915 :param author:
915 :param author:
916 """
916 """
917 from rhodecode.lib.helpers import email, author_name
917 from rhodecode.lib.helpers import email, author_name
918 # Valid email in the attribute passed, see if they're in the system
918 # Valid email in the attribute passed, see if they're in the system
919 _email = email(author)
919 _email = email(author)
920 if _email:
920 if _email:
921 user = cls.get_by_email(_email, case_insensitive=True)
921 user = cls.get_by_email(_email, case_insensitive=True)
922 if user:
922 if user:
923 return user
923 return user
924 # Maybe we can match by username?
924 # Maybe we can match by username?
925 _author = author_name(author)
925 _author = author_name(author)
926 user = cls.get_by_username(_author, case_insensitive=True)
926 user = cls.get_by_username(_author, case_insensitive=True)
927 if user:
927 if user:
928 return user
928 return user
929
929
930 def update_userdata(self, **kwargs):
930 def update_userdata(self, **kwargs):
931 usr = self
931 usr = self
932 old = usr.user_data
932 old = usr.user_data
933 old.update(**kwargs)
933 old.update(**kwargs)
934 usr.user_data = old
934 usr.user_data = old
935 Session().add(usr)
935 Session().add(usr)
936 log.debug('updated userdata with ', kwargs)
936 log.debug('updated userdata with ', kwargs)
937
937
938 def update_lastlogin(self):
938 def update_lastlogin(self):
939 """Update user lastlogin"""
939 """Update user lastlogin"""
940 self.last_login = datetime.datetime.now()
940 self.last_login = datetime.datetime.now()
941 Session().add(self)
941 Session().add(self)
942 log.debug('updated user %s lastlogin', self.username)
942 log.debug('updated user %s lastlogin', self.username)
943
943
944 def update_password(self, new_password):
944 def update_password(self, new_password):
945 from rhodecode.lib.auth import get_crypt_password
945 from rhodecode.lib.auth import get_crypt_password
946
946
947 self.password = get_crypt_password(new_password)
947 self.password = get_crypt_password(new_password)
948 Session().add(self)
948 Session().add(self)
949
949
950 @classmethod
950 @classmethod
951 def get_first_super_admin(cls):
951 def get_first_super_admin(cls):
952 user = User.query()\
952 user = User.query()\
953 .filter(User.admin == true()) \
953 .filter(User.admin == true()) \
954 .order_by(User.user_id.asc()) \
954 .order_by(User.user_id.asc()) \
955 .first()
955 .first()
956
956
957 if user is None:
957 if user is None:
958 raise Exception('FATAL: Missing administrative account!')
958 raise Exception('FATAL: Missing administrative account!')
959 return user
959 return user
960
960
961 @classmethod
961 @classmethod
962 def get_all_super_admins(cls, only_active=False):
962 def get_all_super_admins(cls, only_active=False):
963 """
963 """
964 Returns all admin accounts sorted by username
964 Returns all admin accounts sorted by username
965 """
965 """
966 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
966 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
967 if only_active:
967 if only_active:
968 qry = qry.filter(User.active == true())
968 qry = qry.filter(User.active == true())
969 return qry.all()
969 return qry.all()
970
970
971 @classmethod
971 @classmethod
972 def get_default_user(cls, cache=False, refresh=False):
972 def get_default_user(cls, cache=False, refresh=False):
973 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
973 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
974 if user is None:
974 if user is None:
975 raise Exception('FATAL: Missing default account!')
975 raise Exception('FATAL: Missing default account!')
976 if refresh:
976 if refresh:
977 # The default user might be based on outdated state which
977 # The default user might be based on outdated state which
978 # has been loaded from the cache.
978 # has been loaded from the cache.
979 # A call to refresh() ensures that the
979 # A call to refresh() ensures that the
980 # latest state from the database is used.
980 # latest state from the database is used.
981 Session().refresh(user)
981 Session().refresh(user)
982 return user
982 return user
983
983
984 def _get_default_perms(self, user, suffix=''):
984 def _get_default_perms(self, user, suffix=''):
985 from rhodecode.model.permission import PermissionModel
985 from rhodecode.model.permission import PermissionModel
986 return PermissionModel().get_default_perms(user.user_perms, suffix)
986 return PermissionModel().get_default_perms(user.user_perms, suffix)
987
987
988 def get_default_perms(self, suffix=''):
988 def get_default_perms(self, suffix=''):
989 return self._get_default_perms(self, suffix)
989 return self._get_default_perms(self, suffix)
990
990
991 def get_api_data(self, include_secrets=False, details='full'):
991 def get_api_data(self, include_secrets=False, details='full'):
992 """
992 """
993 Common function for generating user related data for API
993 Common function for generating user related data for API
994
994
995 :param include_secrets: By default secrets in the API data will be replaced
995 :param include_secrets: By default secrets in the API data will be replaced
996 by a placeholder value to prevent exposing this data by accident. In case
996 by a placeholder value to prevent exposing this data by accident. In case
997 this data shall be exposed, set this flag to ``True``.
997 this data shall be exposed, set this flag to ``True``.
998
998
999 :param details: details can be 'basic|full' basic gives only a subset of
999 :param details: details can be 'basic|full' basic gives only a subset of
1000 the available user information that includes user_id, name and emails.
1000 the available user information that includes user_id, name and emails.
1001 """
1001 """
1002 user = self
1002 user = self
1003 user_data = self.user_data
1003 user_data = self.user_data
1004 data = {
1004 data = {
1005 'user_id': user.user_id,
1005 'user_id': user.user_id,
1006 'username': user.username,
1006 'username': user.username,
1007 'firstname': user.name,
1007 'firstname': user.name,
1008 'lastname': user.lastname,
1008 'lastname': user.lastname,
1009 'email': user.email,
1009 'email': user.email,
1010 'emails': user.emails,
1010 'emails': user.emails,
1011 }
1011 }
1012 if details == 'basic':
1012 if details == 'basic':
1013 return data
1013 return data
1014
1014
1015 auth_token_length = 40
1015 auth_token_length = 40
1016 auth_token_replacement = '*' * auth_token_length
1016 auth_token_replacement = '*' * auth_token_length
1017
1017
1018 extras = {
1018 extras = {
1019 'auth_tokens': [auth_token_replacement],
1019 'auth_tokens': [auth_token_replacement],
1020 'active': user.active,
1020 'active': user.active,
1021 'admin': user.admin,
1021 'admin': user.admin,
1022 'extern_type': user.extern_type,
1022 'extern_type': user.extern_type,
1023 'extern_name': user.extern_name,
1023 'extern_name': user.extern_name,
1024 'last_login': user.last_login,
1024 'last_login': user.last_login,
1025 'last_activity': user.last_activity,
1025 'last_activity': user.last_activity,
1026 'ip_addresses': user.ip_addresses,
1026 'ip_addresses': user.ip_addresses,
1027 'language': user_data.get('language')
1027 'language': user_data.get('language')
1028 }
1028 }
1029 data.update(extras)
1029 data.update(extras)
1030
1030
1031 if include_secrets:
1031 if include_secrets:
1032 data['auth_tokens'] = user.auth_tokens
1032 data['auth_tokens'] = user.auth_tokens
1033 return data
1033 return data
1034
1034
1035 def __json__(self):
1035 def __json__(self):
1036 data = {
1036 data = {
1037 'full_name': self.full_name,
1037 'full_name': self.full_name,
1038 'full_name_or_username': self.full_name_or_username,
1038 'full_name_or_username': self.full_name_or_username,
1039 'short_contact': self.short_contact,
1039 'short_contact': self.short_contact,
1040 'full_contact': self.full_contact,
1040 'full_contact': self.full_contact,
1041 }
1041 }
1042 data.update(self.get_api_data())
1042 data.update(self.get_api_data())
1043 return data
1043 return data
1044
1044
1045
1045
1046 class UserApiKeys(Base, BaseModel):
1046 class UserApiKeys(Base, BaseModel):
1047 __tablename__ = 'user_api_keys'
1047 __tablename__ = 'user_api_keys'
1048 __table_args__ = (
1048 __table_args__ = (
1049 Index('uak_api_key_idx', 'api_key', unique=True),
1049 Index('uak_api_key_idx', 'api_key', unique=True),
1050 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1050 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1051 base_table_args
1051 base_table_args
1052 )
1052 )
1053 __mapper_args__ = {}
1053 __mapper_args__ = {}
1054
1054
1055 # ApiKey role
1055 # ApiKey role
1056 ROLE_ALL = 'token_role_all'
1056 ROLE_ALL = 'token_role_all'
1057 ROLE_HTTP = 'token_role_http'
1057 ROLE_HTTP = 'token_role_http'
1058 ROLE_VCS = 'token_role_vcs'
1058 ROLE_VCS = 'token_role_vcs'
1059 ROLE_API = 'token_role_api'
1059 ROLE_API = 'token_role_api'
1060 ROLE_FEED = 'token_role_feed'
1060 ROLE_FEED = 'token_role_feed'
1061 ROLE_PASSWORD_RESET = 'token_password_reset'
1061 ROLE_PASSWORD_RESET = 'token_password_reset'
1062
1062
1063 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1063 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1064
1064
1065 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1065 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1066 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1066 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1067 api_key = Column("api_key", String(255), nullable=False, unique=True)
1067 api_key = Column("api_key", String(255), nullable=False, unique=True)
1068 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1068 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1069 expires = Column('expires', Float(53), nullable=False)
1069 expires = Column('expires', Float(53), nullable=False)
1070 role = Column('role', String(255), nullable=True)
1070 role = Column('role', String(255), nullable=True)
1071 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1071 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1072
1072
1073 # scope columns
1073 # scope columns
1074 repo_id = Column(
1074 repo_id = Column(
1075 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1075 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1076 nullable=True, unique=None, default=None)
1076 nullable=True, unique=None, default=None)
1077 repo = relationship('Repository', lazy='joined')
1077 repo = relationship('Repository', lazy='joined')
1078
1078
1079 repo_group_id = Column(
1079 repo_group_id = Column(
1080 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1080 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1081 nullable=True, unique=None, default=None)
1081 nullable=True, unique=None, default=None)
1082 repo_group = relationship('RepoGroup', lazy='joined')
1082 repo_group = relationship('RepoGroup', lazy='joined')
1083
1083
1084 user = relationship('User', lazy='joined')
1084 user = relationship('User', lazy='joined')
1085
1085
1086 def __unicode__(self):
1086 def __unicode__(self):
1087 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1087 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1088
1088
1089 def __json__(self):
1089 def __json__(self):
1090 data = {
1090 data = {
1091 'auth_token': self.api_key,
1091 'auth_token': self.api_key,
1092 'role': self.role,
1092 'role': self.role,
1093 'scope': self.scope_humanized,
1093 'scope': self.scope_humanized,
1094 'expired': self.expired
1094 'expired': self.expired
1095 }
1095 }
1096 return data
1096 return data
1097
1097
1098 def get_api_data(self, include_secrets=False):
1098 def get_api_data(self, include_secrets=False):
1099 data = self.__json__()
1099 data = self.__json__()
1100 if include_secrets:
1100 if include_secrets:
1101 return data
1101 return data
1102 else:
1102 else:
1103 data['auth_token'] = self.token_obfuscated
1103 data['auth_token'] = self.token_obfuscated
1104 return data
1104 return data
1105
1105
1106 @hybrid_property
1106 @hybrid_property
1107 def description_safe(self):
1107 def description_safe(self):
1108 from rhodecode.lib import helpers as h
1108 from rhodecode.lib import helpers as h
1109 return h.escape(self.description)
1109 return h.escape(self.description)
1110
1110
1111 @property
1111 @property
1112 def expired(self):
1112 def expired(self):
1113 if self.expires == -1:
1113 if self.expires == -1:
1114 return False
1114 return False
1115 return time.time() > self.expires
1115 return time.time() > self.expires
1116
1116
1117 @classmethod
1117 @classmethod
1118 def _get_role_name(cls, role):
1118 def _get_role_name(cls, role):
1119 return {
1119 return {
1120 cls.ROLE_ALL: _('all'),
1120 cls.ROLE_ALL: _('all'),
1121 cls.ROLE_HTTP: _('http/web interface'),
1121 cls.ROLE_HTTP: _('http/web interface'),
1122 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1122 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1123 cls.ROLE_API: _('api calls'),
1123 cls.ROLE_API: _('api calls'),
1124 cls.ROLE_FEED: _('feed access'),
1124 cls.ROLE_FEED: _('feed access'),
1125 }.get(role, role)
1125 }.get(role, role)
1126
1126
1127 @property
1127 @property
1128 def role_humanized(self):
1128 def role_humanized(self):
1129 return self._get_role_name(self.role)
1129 return self._get_role_name(self.role)
1130
1130
1131 def _get_scope(self):
1131 def _get_scope(self):
1132 if self.repo:
1132 if self.repo:
1133 return 'Repository: {}'.format(self.repo.repo_name)
1133 return 'Repository: {}'.format(self.repo.repo_name)
1134 if self.repo_group:
1134 if self.repo_group:
1135 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1135 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1136 return 'Global'
1136 return 'Global'
1137
1137
1138 @property
1138 @property
1139 def scope_humanized(self):
1139 def scope_humanized(self):
1140 return self._get_scope()
1140 return self._get_scope()
1141
1141
1142 @property
1142 @property
1143 def token_obfuscated(self):
1143 def token_obfuscated(self):
1144 if self.api_key:
1144 if self.api_key:
1145 return self.api_key[:4] + "****"
1145 return self.api_key[:4] + "****"
1146
1146
1147
1147
1148 class UserEmailMap(Base, BaseModel):
1148 class UserEmailMap(Base, BaseModel):
1149 __tablename__ = 'user_email_map'
1149 __tablename__ = 'user_email_map'
1150 __table_args__ = (
1150 __table_args__ = (
1151 Index('uem_email_idx', 'email'),
1151 Index('uem_email_idx', 'email'),
1152 UniqueConstraint('email'),
1152 UniqueConstraint('email'),
1153 base_table_args
1153 base_table_args
1154 )
1154 )
1155 __mapper_args__ = {}
1155 __mapper_args__ = {}
1156
1156
1157 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1157 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1158 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1158 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1159 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1159 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1160 user = relationship('User', lazy='joined')
1160 user = relationship('User', lazy='joined')
1161
1161
1162 @validates('_email')
1162 @validates('_email')
1163 def validate_email(self, key, email):
1163 def validate_email(self, key, email):
1164 # check if this email is not main one
1164 # check if this email is not main one
1165 main_email = Session().query(User).filter(User.email == email).scalar()
1165 main_email = Session().query(User).filter(User.email == email).scalar()
1166 if main_email is not None:
1166 if main_email is not None:
1167 raise AttributeError('email %s is present is user table' % email)
1167 raise AttributeError('email %s is present is user table' % email)
1168 return email
1168 return email
1169
1169
1170 @hybrid_property
1170 @hybrid_property
1171 def email(self):
1171 def email(self):
1172 return self._email
1172 return self._email
1173
1173
1174 @email.setter
1174 @email.setter
1175 def email(self, val):
1175 def email(self, val):
1176 self._email = val.lower() if val else None
1176 self._email = val.lower() if val else None
1177
1177
1178
1178
1179 class UserIpMap(Base, BaseModel):
1179 class UserIpMap(Base, BaseModel):
1180 __tablename__ = 'user_ip_map'
1180 __tablename__ = 'user_ip_map'
1181 __table_args__ = (
1181 __table_args__ = (
1182 UniqueConstraint('user_id', 'ip_addr'),
1182 UniqueConstraint('user_id', 'ip_addr'),
1183 base_table_args
1183 base_table_args
1184 )
1184 )
1185 __mapper_args__ = {}
1185 __mapper_args__ = {}
1186
1186
1187 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1187 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1188 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1188 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1189 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1189 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1190 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1190 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1191 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1191 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1192 user = relationship('User', lazy='joined')
1192 user = relationship('User', lazy='joined')
1193
1193
1194 @hybrid_property
1194 @hybrid_property
1195 def description_safe(self):
1195 def description_safe(self):
1196 from rhodecode.lib import helpers as h
1196 from rhodecode.lib import helpers as h
1197 return h.escape(self.description)
1197 return h.escape(self.description)
1198
1198
1199 @classmethod
1199 @classmethod
1200 def _get_ip_range(cls, ip_addr):
1200 def _get_ip_range(cls, ip_addr):
1201 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1201 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1202 return [str(net.network_address), str(net.broadcast_address)]
1202 return [str(net.network_address), str(net.broadcast_address)]
1203
1203
1204 def __json__(self):
1204 def __json__(self):
1205 return {
1205 return {
1206 'ip_addr': self.ip_addr,
1206 'ip_addr': self.ip_addr,
1207 'ip_range': self._get_ip_range(self.ip_addr),
1207 'ip_range': self._get_ip_range(self.ip_addr),
1208 }
1208 }
1209
1209
1210 def __unicode__(self):
1210 def __unicode__(self):
1211 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1211 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1212 self.user_id, self.ip_addr)
1212 self.user_id, self.ip_addr)
1213
1213
1214
1214
1215 class UserSshKeys(Base, BaseModel):
1215 class UserSshKeys(Base, BaseModel):
1216 __tablename__ = 'user_ssh_keys'
1216 __tablename__ = 'user_ssh_keys'
1217 __table_args__ = (
1217 __table_args__ = (
1218 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1218 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1219
1219
1220 UniqueConstraint('ssh_key_fingerprint'),
1220 UniqueConstraint('ssh_key_fingerprint'),
1221
1221
1222 base_table_args
1222 base_table_args
1223 )
1223 )
1224 __mapper_args__ = {}
1224 __mapper_args__ = {}
1225
1225
1226 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1226 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1227 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1227 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1228 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1228 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1229
1229
1230 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1230 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1231
1231
1232 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1232 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1233 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1233 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1234 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1234 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1235
1235
1236 user = relationship('User', lazy='joined')
1236 user = relationship('User', lazy='joined')
1237
1237
1238 def __json__(self):
1238 def __json__(self):
1239 data = {
1239 data = {
1240 'ssh_fingerprint': self.ssh_key_fingerprint,
1240 'ssh_fingerprint': self.ssh_key_fingerprint,
1241 'description': self.description,
1241 'description': self.description,
1242 'created_on': self.created_on
1242 'created_on': self.created_on
1243 }
1243 }
1244 return data
1244 return data
1245
1245
1246 def get_api_data(self):
1246 def get_api_data(self):
1247 data = self.__json__()
1247 data = self.__json__()
1248 return data
1248 return data
1249
1249
1250
1250
1251 class UserLog(Base, BaseModel):
1251 class UserLog(Base, BaseModel):
1252 __tablename__ = 'user_logs'
1252 __tablename__ = 'user_logs'
1253 __table_args__ = (
1253 __table_args__ = (
1254 base_table_args,
1254 base_table_args,
1255 )
1255 )
1256
1256
1257 VERSION_1 = 'v1'
1257 VERSION_1 = 'v1'
1258 VERSION_2 = 'v2'
1258 VERSION_2 = 'v2'
1259 VERSIONS = [VERSION_1, VERSION_2]
1259 VERSIONS = [VERSION_1, VERSION_2]
1260
1260
1261 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1261 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1262 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1262 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1263 username = Column("username", String(255), nullable=True, unique=None, default=None)
1263 username = Column("username", String(255), nullable=True, unique=None, default=None)
1264 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1264 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1265 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1265 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1266 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1266 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1267 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1267 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1268 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1268 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1269
1269
1270 version = Column("version", String(255), nullable=True, default=VERSION_1)
1270 version = Column("version", String(255), nullable=True, default=VERSION_1)
1271 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1271 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1272 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1272 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1273
1273
1274 def __unicode__(self):
1274 def __unicode__(self):
1275 return u"<%s('id:%s:%s')>" % (
1275 return u"<%s('id:%s:%s')>" % (
1276 self.__class__.__name__, self.repository_name, self.action)
1276 self.__class__.__name__, self.repository_name, self.action)
1277
1277
1278 def __json__(self):
1278 def __json__(self):
1279 return {
1279 return {
1280 'user_id': self.user_id,
1280 'user_id': self.user_id,
1281 'username': self.username,
1281 'username': self.username,
1282 'repository_id': self.repository_id,
1282 'repository_id': self.repository_id,
1283 'repository_name': self.repository_name,
1283 'repository_name': self.repository_name,
1284 'user_ip': self.user_ip,
1284 'user_ip': self.user_ip,
1285 'action_date': self.action_date,
1285 'action_date': self.action_date,
1286 'action': self.action,
1286 'action': self.action,
1287 }
1287 }
1288
1288
1289 @hybrid_property
1289 @hybrid_property
1290 def entry_id(self):
1290 def entry_id(self):
1291 return self.user_log_id
1291 return self.user_log_id
1292
1292
1293 @property
1293 @property
1294 def action_as_day(self):
1294 def action_as_day(self):
1295 return datetime.date(*self.action_date.timetuple()[:3])
1295 return datetime.date(*self.action_date.timetuple()[:3])
1296
1296
1297 user = relationship('User')
1297 user = relationship('User')
1298 repository = relationship('Repository', cascade='')
1298 repository = relationship('Repository', cascade='')
1299
1299
1300
1300
1301 class UserGroup(Base, BaseModel):
1301 class UserGroup(Base, BaseModel):
1302 __tablename__ = 'users_groups'
1302 __tablename__ = 'users_groups'
1303 __table_args__ = (
1303 __table_args__ = (
1304 base_table_args,
1304 base_table_args,
1305 )
1305 )
1306
1306
1307 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1307 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1308 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1308 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1309 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1309 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1310 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1310 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1311 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1311 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1312 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1312 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1313 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1313 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1314 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1314 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1315
1315
1316 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1316 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1317 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1317 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1318 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1318 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1319 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1319 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1320 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1320 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1321 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1321 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1322
1322
1323 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1323 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1324 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1324 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1325
1325
1326 @classmethod
1326 @classmethod
1327 def _load_group_data(cls, column):
1327 def _load_group_data(cls, column):
1328 if not column:
1328 if not column:
1329 return {}
1329 return {}
1330
1330
1331 try:
1331 try:
1332 return json.loads(column) or {}
1332 return json.loads(column) or {}
1333 except TypeError:
1333 except TypeError:
1334 return {}
1334 return {}
1335
1335
1336 @hybrid_property
1336 @hybrid_property
1337 def description_safe(self):
1337 def description_safe(self):
1338 from rhodecode.lib import helpers as h
1338 from rhodecode.lib import helpers as h
1339 return h.escape(self.user_group_description)
1339 return h.escape(self.user_group_description)
1340
1340
1341 @hybrid_property
1341 @hybrid_property
1342 def group_data(self):
1342 def group_data(self):
1343 return self._load_group_data(self._group_data)
1343 return self._load_group_data(self._group_data)
1344
1344
1345 @group_data.expression
1345 @group_data.expression
1346 def group_data(self, **kwargs):
1346 def group_data(self, **kwargs):
1347 return self._group_data
1347 return self._group_data
1348
1348
1349 @group_data.setter
1349 @group_data.setter
1350 def group_data(self, val):
1350 def group_data(self, val):
1351 try:
1351 try:
1352 self._group_data = json.dumps(val)
1352 self._group_data = json.dumps(val)
1353 except Exception:
1353 except Exception:
1354 log.error(traceback.format_exc())
1354 log.error(traceback.format_exc())
1355
1355
1356 @classmethod
1356 @classmethod
1357 def _load_sync(cls, group_data):
1357 def _load_sync(cls, group_data):
1358 if group_data:
1358 if group_data:
1359 return group_data.get('extern_type')
1359 return group_data.get('extern_type')
1360
1360
1361 @property
1361 @property
1362 def sync(self):
1362 def sync(self):
1363 return self._load_sync(self.group_data)
1363 return self._load_sync(self.group_data)
1364
1364
1365 def __unicode__(self):
1365 def __unicode__(self):
1366 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1366 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1367 self.users_group_id,
1367 self.users_group_id,
1368 self.users_group_name)
1368 self.users_group_name)
1369
1369
1370 @classmethod
1370 @classmethod
1371 def get_by_group_name(cls, group_name, cache=False,
1371 def get_by_group_name(cls, group_name, cache=False,
1372 case_insensitive=False):
1372 case_insensitive=False):
1373 if case_insensitive:
1373 if case_insensitive:
1374 q = cls.query().filter(func.lower(cls.users_group_name) ==
1374 q = cls.query().filter(func.lower(cls.users_group_name) ==
1375 func.lower(group_name))
1375 func.lower(group_name))
1376
1376
1377 else:
1377 else:
1378 q = cls.query().filter(cls.users_group_name == group_name)
1378 q = cls.query().filter(cls.users_group_name == group_name)
1379 if cache:
1379 if cache:
1380 q = q.options(
1380 q = q.options(
1381 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1381 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1382 return q.scalar()
1382 return q.scalar()
1383
1383
1384 @classmethod
1384 @classmethod
1385 def get(cls, user_group_id, cache=False):
1385 def get(cls, user_group_id, cache=False):
1386 if not user_group_id:
1386 if not user_group_id:
1387 return
1387 return
1388
1388
1389 user_group = cls.query()
1389 user_group = cls.query()
1390 if cache:
1390 if cache:
1391 user_group = user_group.options(
1391 user_group = user_group.options(
1392 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1392 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1393 return user_group.get(user_group_id)
1393 return user_group.get(user_group_id)
1394
1394
1395 def permissions(self, with_admins=True, with_owner=True,
1395 def permissions(self, with_admins=True, with_owner=True,
1396 expand_from_user_groups=False):
1396 expand_from_user_groups=False):
1397 """
1397 """
1398 Permissions for user groups
1398 Permissions for user groups
1399 """
1399 """
1400 _admin_perm = 'usergroup.admin'
1400 _admin_perm = 'usergroup.admin'
1401
1401
1402 owner_row = []
1402 owner_row = []
1403 if with_owner:
1403 if with_owner:
1404 usr = AttributeDict(self.user.get_dict())
1404 usr = AttributeDict(self.user.get_dict())
1405 usr.owner_row = True
1405 usr.owner_row = True
1406 usr.permission = _admin_perm
1406 usr.permission = _admin_perm
1407 owner_row.append(usr)
1407 owner_row.append(usr)
1408
1408
1409 super_admin_ids = []
1409 super_admin_ids = []
1410 super_admin_rows = []
1410 super_admin_rows = []
1411 if with_admins:
1411 if with_admins:
1412 for usr in User.get_all_super_admins():
1412 for usr in User.get_all_super_admins():
1413 super_admin_ids.append(usr.user_id)
1413 super_admin_ids.append(usr.user_id)
1414 # if this admin is also owner, don't double the record
1414 # if this admin is also owner, don't double the record
1415 if usr.user_id == owner_row[0].user_id:
1415 if usr.user_id == owner_row[0].user_id:
1416 owner_row[0].admin_row = True
1416 owner_row[0].admin_row = True
1417 else:
1417 else:
1418 usr = AttributeDict(usr.get_dict())
1418 usr = AttributeDict(usr.get_dict())
1419 usr.admin_row = True
1419 usr.admin_row = True
1420 usr.permission = _admin_perm
1420 usr.permission = _admin_perm
1421 super_admin_rows.append(usr)
1421 super_admin_rows.append(usr)
1422
1422
1423 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1423 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1424 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1424 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1425 joinedload(UserUserGroupToPerm.user),
1425 joinedload(UserUserGroupToPerm.user),
1426 joinedload(UserUserGroupToPerm.permission),)
1426 joinedload(UserUserGroupToPerm.permission),)
1427
1427
1428 # get owners and admins and permissions. We do a trick of re-writing
1428 # get owners and admins and permissions. We do a trick of re-writing
1429 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1429 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1430 # has a global reference and changing one object propagates to all
1430 # has a global reference and changing one object propagates to all
1431 # others. This means if admin is also an owner admin_row that change
1431 # others. This means if admin is also an owner admin_row that change
1432 # would propagate to both objects
1432 # would propagate to both objects
1433 perm_rows = []
1433 perm_rows = []
1434 for _usr in q.all():
1434 for _usr in q.all():
1435 usr = AttributeDict(_usr.user.get_dict())
1435 usr = AttributeDict(_usr.user.get_dict())
1436 # if this user is also owner/admin, mark as duplicate record
1436 # if this user is also owner/admin, mark as duplicate record
1437 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1437 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1438 usr.duplicate_perm = True
1438 usr.duplicate_perm = True
1439 usr.permission = _usr.permission.permission_name
1439 usr.permission = _usr.permission.permission_name
1440 perm_rows.append(usr)
1440 perm_rows.append(usr)
1441
1441
1442 # filter the perm rows by 'default' first and then sort them by
1442 # filter the perm rows by 'default' first and then sort them by
1443 # admin,write,read,none permissions sorted again alphabetically in
1443 # admin,write,read,none permissions sorted again alphabetically in
1444 # each group
1444 # each group
1445 perm_rows = sorted(perm_rows, key=display_user_sort)
1445 perm_rows = sorted(perm_rows, key=display_user_sort)
1446
1446
1447 user_groups_rows = []
1447 user_groups_rows = []
1448 if expand_from_user_groups:
1448 if expand_from_user_groups:
1449 for ug in self.permission_user_groups(with_members=True):
1449 for ug in self.permission_user_groups(with_members=True):
1450 for user_data in ug.members:
1450 for user_data in ug.members:
1451 user_groups_rows.append(user_data)
1451 user_groups_rows.append(user_data)
1452
1452
1453 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1453 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1454
1454
1455 def permission_user_groups(self, with_members=False):
1455 def permission_user_groups(self, with_members=False):
1456 q = UserGroupUserGroupToPerm.query()\
1456 q = UserGroupUserGroupToPerm.query()\
1457 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1457 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1458 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1458 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1459 joinedload(UserGroupUserGroupToPerm.target_user_group),
1459 joinedload(UserGroupUserGroupToPerm.target_user_group),
1460 joinedload(UserGroupUserGroupToPerm.permission),)
1460 joinedload(UserGroupUserGroupToPerm.permission),)
1461
1461
1462 perm_rows = []
1462 perm_rows = []
1463 for _user_group in q.all():
1463 for _user_group in q.all():
1464 entry = AttributeDict(_user_group.user_group.get_dict())
1464 entry = AttributeDict(_user_group.user_group.get_dict())
1465 entry.permission = _user_group.permission.permission_name
1465 entry.permission = _user_group.permission.permission_name
1466 if with_members:
1466 if with_members:
1467 entry.members = [x.user.get_dict()
1467 entry.members = [x.user.get_dict()
1468 for x in _user_group.users_group.members]
1468 for x in _user_group.users_group.members]
1469 perm_rows.append(entry)
1469 perm_rows.append(entry)
1470
1470
1471 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1471 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1472 return perm_rows
1472 return perm_rows
1473
1473
1474 def _get_default_perms(self, user_group, suffix=''):
1474 def _get_default_perms(self, user_group, suffix=''):
1475 from rhodecode.model.permission import PermissionModel
1475 from rhodecode.model.permission import PermissionModel
1476 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1476 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1477
1477
1478 def get_default_perms(self, suffix=''):
1478 def get_default_perms(self, suffix=''):
1479 return self._get_default_perms(self, suffix)
1479 return self._get_default_perms(self, suffix)
1480
1480
1481 def get_api_data(self, with_group_members=True, include_secrets=False):
1481 def get_api_data(self, with_group_members=True, include_secrets=False):
1482 """
1482 """
1483 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1483 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1484 basically forwarded.
1484 basically forwarded.
1485
1485
1486 """
1486 """
1487 user_group = self
1487 user_group = self
1488 data = {
1488 data = {
1489 'users_group_id': user_group.users_group_id,
1489 'users_group_id': user_group.users_group_id,
1490 'group_name': user_group.users_group_name,
1490 'group_name': user_group.users_group_name,
1491 'group_description': user_group.user_group_description,
1491 'group_description': user_group.user_group_description,
1492 'active': user_group.users_group_active,
1492 'active': user_group.users_group_active,
1493 'owner': user_group.user.username,
1493 'owner': user_group.user.username,
1494 'sync': user_group.sync,
1494 'sync': user_group.sync,
1495 'owner_email': user_group.user.email,
1495 'owner_email': user_group.user.email,
1496 }
1496 }
1497
1497
1498 if with_group_members:
1498 if with_group_members:
1499 users = []
1499 users = []
1500 for user in user_group.members:
1500 for user in user_group.members:
1501 user = user.user
1501 user = user.user
1502 users.append(user.get_api_data(include_secrets=include_secrets))
1502 users.append(user.get_api_data(include_secrets=include_secrets))
1503 data['users'] = users
1503 data['users'] = users
1504
1504
1505 return data
1505 return data
1506
1506
1507
1507
1508 class UserGroupMember(Base, BaseModel):
1508 class UserGroupMember(Base, BaseModel):
1509 __tablename__ = 'users_groups_members'
1509 __tablename__ = 'users_groups_members'
1510 __table_args__ = (
1510 __table_args__ = (
1511 base_table_args,
1511 base_table_args,
1512 )
1512 )
1513
1513
1514 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1514 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1515 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1515 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1516 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1516 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1517
1517
1518 user = relationship('User', lazy='joined')
1518 user = relationship('User', lazy='joined')
1519 users_group = relationship('UserGroup')
1519 users_group = relationship('UserGroup')
1520
1520
1521 def __init__(self, gr_id='', u_id=''):
1521 def __init__(self, gr_id='', u_id=''):
1522 self.users_group_id = gr_id
1522 self.users_group_id = gr_id
1523 self.user_id = u_id
1523 self.user_id = u_id
1524
1524
1525
1525
1526 class RepositoryField(Base, BaseModel):
1526 class RepositoryField(Base, BaseModel):
1527 __tablename__ = 'repositories_fields'
1527 __tablename__ = 'repositories_fields'
1528 __table_args__ = (
1528 __table_args__ = (
1529 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1529 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1530 base_table_args,
1530 base_table_args,
1531 )
1531 )
1532
1532
1533 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1533 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1534
1534
1535 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1535 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1536 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1536 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1537 field_key = Column("field_key", String(250))
1537 field_key = Column("field_key", String(250))
1538 field_label = Column("field_label", String(1024), nullable=False)
1538 field_label = Column("field_label", String(1024), nullable=False)
1539 field_value = Column("field_value", String(10000), nullable=False)
1539 field_value = Column("field_value", String(10000), nullable=False)
1540 field_desc = Column("field_desc", String(1024), nullable=False)
1540 field_desc = Column("field_desc", String(1024), nullable=False)
1541 field_type = Column("field_type", String(255), nullable=False, unique=None)
1541 field_type = Column("field_type", String(255), nullable=False, unique=None)
1542 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1542 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1543
1543
1544 repository = relationship('Repository')
1544 repository = relationship('Repository')
1545
1545
1546 @property
1546 @property
1547 def field_key_prefixed(self):
1547 def field_key_prefixed(self):
1548 return 'ex_%s' % self.field_key
1548 return 'ex_%s' % self.field_key
1549
1549
1550 @classmethod
1550 @classmethod
1551 def un_prefix_key(cls, key):
1551 def un_prefix_key(cls, key):
1552 if key.startswith(cls.PREFIX):
1552 if key.startswith(cls.PREFIX):
1553 return key[len(cls.PREFIX):]
1553 return key[len(cls.PREFIX):]
1554 return key
1554 return key
1555
1555
1556 @classmethod
1556 @classmethod
1557 def get_by_key_name(cls, key, repo):
1557 def get_by_key_name(cls, key, repo):
1558 row = cls.query()\
1558 row = cls.query()\
1559 .filter(cls.repository == repo)\
1559 .filter(cls.repository == repo)\
1560 .filter(cls.field_key == key).scalar()
1560 .filter(cls.field_key == key).scalar()
1561 return row
1561 return row
1562
1562
1563
1563
1564 class Repository(Base, BaseModel):
1564 class Repository(Base, BaseModel):
1565 __tablename__ = 'repositories'
1565 __tablename__ = 'repositories'
1566 __table_args__ = (
1566 __table_args__ = (
1567 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1567 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1568 base_table_args,
1568 base_table_args,
1569 )
1569 )
1570 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1570 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1571 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1571 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1572 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1572 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1573
1573
1574 STATE_CREATED = 'repo_state_created'
1574 STATE_CREATED = 'repo_state_created'
1575 STATE_PENDING = 'repo_state_pending'
1575 STATE_PENDING = 'repo_state_pending'
1576 STATE_ERROR = 'repo_state_error'
1576 STATE_ERROR = 'repo_state_error'
1577
1577
1578 LOCK_AUTOMATIC = 'lock_auto'
1578 LOCK_AUTOMATIC = 'lock_auto'
1579 LOCK_API = 'lock_api'
1579 LOCK_API = 'lock_api'
1580 LOCK_WEB = 'lock_web'
1580 LOCK_WEB = 'lock_web'
1581 LOCK_PULL = 'lock_pull'
1581 LOCK_PULL = 'lock_pull'
1582
1582
1583 NAME_SEP = URL_SEP
1583 NAME_SEP = URL_SEP
1584
1584
1585 repo_id = Column(
1585 repo_id = Column(
1586 "repo_id", Integer(), nullable=False, unique=True, default=None,
1586 "repo_id", Integer(), nullable=False, unique=True, default=None,
1587 primary_key=True)
1587 primary_key=True)
1588 _repo_name = Column(
1588 _repo_name = Column(
1589 "repo_name", Text(), nullable=False, default=None)
1589 "repo_name", Text(), nullable=False, default=None)
1590 _repo_name_hash = Column(
1590 _repo_name_hash = Column(
1591 "repo_name_hash", String(255), nullable=False, unique=True)
1591 "repo_name_hash", String(255), nullable=False, unique=True)
1592 repo_state = Column("repo_state", String(255), nullable=True)
1592 repo_state = Column("repo_state", String(255), nullable=True)
1593
1593
1594 clone_uri = Column(
1594 clone_uri = Column(
1595 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1595 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1596 default=None)
1596 default=None)
1597 push_uri = Column(
1597 push_uri = Column(
1598 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1598 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1599 default=None)
1599 default=None)
1600 repo_type = Column(
1600 repo_type = Column(
1601 "repo_type", String(255), nullable=False, unique=False, default=None)
1601 "repo_type", String(255), nullable=False, unique=False, default=None)
1602 user_id = Column(
1602 user_id = Column(
1603 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1603 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1604 unique=False, default=None)
1604 unique=False, default=None)
1605 private = Column(
1605 private = Column(
1606 "private", Boolean(), nullable=True, unique=None, default=None)
1606 "private", Boolean(), nullable=True, unique=None, default=None)
1607 archived = Column(
1607 archived = Column(
1608 "archived", Boolean(), nullable=True, unique=None, default=None)
1608 "archived", Boolean(), nullable=True, unique=None, default=None)
1609 enable_statistics = Column(
1609 enable_statistics = Column(
1610 "statistics", Boolean(), nullable=True, unique=None, default=True)
1610 "statistics", Boolean(), nullable=True, unique=None, default=True)
1611 enable_downloads = Column(
1611 enable_downloads = Column(
1612 "downloads", Boolean(), nullable=True, unique=None, default=True)
1612 "downloads", Boolean(), nullable=True, unique=None, default=True)
1613 description = Column(
1613 description = Column(
1614 "description", String(10000), nullable=True, unique=None, default=None)
1614 "description", String(10000), nullable=True, unique=None, default=None)
1615 created_on = Column(
1615 created_on = Column(
1616 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1616 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1617 default=datetime.datetime.now)
1617 default=datetime.datetime.now)
1618 updated_on = Column(
1618 updated_on = Column(
1619 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1619 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1620 default=datetime.datetime.now)
1620 default=datetime.datetime.now)
1621 _landing_revision = Column(
1621 _landing_revision = Column(
1622 "landing_revision", String(255), nullable=False, unique=False,
1622 "landing_revision", String(255), nullable=False, unique=False,
1623 default=None)
1623 default=None)
1624 enable_locking = Column(
1624 enable_locking = Column(
1625 "enable_locking", Boolean(), nullable=False, unique=None,
1625 "enable_locking", Boolean(), nullable=False, unique=None,
1626 default=False)
1626 default=False)
1627 _locked = Column(
1627 _locked = Column(
1628 "locked", String(255), nullable=True, unique=False, default=None)
1628 "locked", String(255), nullable=True, unique=False, default=None)
1629 _changeset_cache = Column(
1629 _changeset_cache = Column(
1630 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1630 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1631
1631
1632 fork_id = Column(
1632 fork_id = Column(
1633 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1633 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1634 nullable=True, unique=False, default=None)
1634 nullable=True, unique=False, default=None)
1635 group_id = Column(
1635 group_id = Column(
1636 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1636 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1637 unique=False, default=None)
1637 unique=False, default=None)
1638
1638
1639 user = relationship('User', lazy='joined')
1639 user = relationship('User', lazy='joined')
1640 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1640 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1641 group = relationship('RepoGroup', lazy='joined')
1641 group = relationship('RepoGroup', lazy='joined')
1642 repo_to_perm = relationship(
1642 repo_to_perm = relationship(
1643 'UserRepoToPerm', cascade='all',
1643 'UserRepoToPerm', cascade='all',
1644 order_by='UserRepoToPerm.repo_to_perm_id')
1644 order_by='UserRepoToPerm.repo_to_perm_id')
1645 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1645 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1646 stats = relationship('Statistics', cascade='all', uselist=False)
1646 stats = relationship('Statistics', cascade='all', uselist=False)
1647
1647
1648 followers = relationship(
1648 followers = relationship(
1649 'UserFollowing',
1649 'UserFollowing',
1650 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1650 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1651 cascade='all')
1651 cascade='all')
1652 extra_fields = relationship(
1652 extra_fields = relationship(
1653 'RepositoryField', cascade="all, delete, delete-orphan")
1653 'RepositoryField', cascade="all, delete, delete-orphan")
1654 logs = relationship('UserLog')
1654 logs = relationship('UserLog')
1655 comments = relationship(
1655 comments = relationship(
1656 'ChangesetComment', cascade="all, delete, delete-orphan")
1656 'ChangesetComment', cascade="all, delete, delete-orphan")
1657 pull_requests_source = relationship(
1657 pull_requests_source = relationship(
1658 'PullRequest',
1658 'PullRequest',
1659 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1659 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1660 cascade="all, delete, delete-orphan")
1660 cascade="all, delete, delete-orphan")
1661 pull_requests_target = relationship(
1661 pull_requests_target = relationship(
1662 'PullRequest',
1662 'PullRequest',
1663 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1663 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1664 cascade="all, delete, delete-orphan")
1664 cascade="all, delete, delete-orphan")
1665 ui = relationship('RepoRhodeCodeUi', cascade="all")
1665 ui = relationship('RepoRhodeCodeUi', cascade="all")
1666 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1666 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1667 integrations = relationship('Integration',
1667 integrations = relationship('Integration',
1668 cascade="all, delete, delete-orphan")
1668 cascade="all, delete, delete-orphan")
1669
1669
1670 scoped_tokens = relationship('UserApiKeys', cascade="all")
1670 scoped_tokens = relationship('UserApiKeys', cascade="all")
1671
1671
1672 def __unicode__(self):
1672 def __unicode__(self):
1673 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1673 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1674 safe_unicode(self.repo_name))
1674 safe_unicode(self.repo_name))
1675
1675
1676 @hybrid_property
1676 @hybrid_property
1677 def description_safe(self):
1677 def description_safe(self):
1678 from rhodecode.lib import helpers as h
1678 from rhodecode.lib import helpers as h
1679 return h.escape(self.description)
1679 return h.escape(self.description)
1680
1680
1681 @hybrid_property
1681 @hybrid_property
1682 def landing_rev(self):
1682 def landing_rev(self):
1683 # always should return [rev_type, rev]
1683 # always should return [rev_type, rev]
1684 if self._landing_revision:
1684 if self._landing_revision:
1685 _rev_info = self._landing_revision.split(':')
1685 _rev_info = self._landing_revision.split(':')
1686 if len(_rev_info) < 2:
1686 if len(_rev_info) < 2:
1687 _rev_info.insert(0, 'rev')
1687 _rev_info.insert(0, 'rev')
1688 return [_rev_info[0], _rev_info[1]]
1688 return [_rev_info[0], _rev_info[1]]
1689 return [None, None]
1689 return [None, None]
1690
1690
1691 @landing_rev.setter
1691 @landing_rev.setter
1692 def landing_rev(self, val):
1692 def landing_rev(self, val):
1693 if ':' not in val:
1693 if ':' not in val:
1694 raise ValueError('value must be delimited with `:` and consist '
1694 raise ValueError('value must be delimited with `:` and consist '
1695 'of <rev_type>:<rev>, got %s instead' % val)
1695 'of <rev_type>:<rev>, got %s instead' % val)
1696 self._landing_revision = val
1696 self._landing_revision = val
1697
1697
1698 @hybrid_property
1698 @hybrid_property
1699 def locked(self):
1699 def locked(self):
1700 if self._locked:
1700 if self._locked:
1701 user_id, timelocked, reason = self._locked.split(':')
1701 user_id, timelocked, reason = self._locked.split(':')
1702 lock_values = int(user_id), timelocked, reason
1702 lock_values = int(user_id), timelocked, reason
1703 else:
1703 else:
1704 lock_values = [None, None, None]
1704 lock_values = [None, None, None]
1705 return lock_values
1705 return lock_values
1706
1706
1707 @locked.setter
1707 @locked.setter
1708 def locked(self, val):
1708 def locked(self, val):
1709 if val and isinstance(val, (list, tuple)):
1709 if val and isinstance(val, (list, tuple)):
1710 self._locked = ':'.join(map(str, val))
1710 self._locked = ':'.join(map(str, val))
1711 else:
1711 else:
1712 self._locked = None
1712 self._locked = None
1713
1713
1714 @hybrid_property
1714 @hybrid_property
1715 def changeset_cache(self):
1715 def changeset_cache(self):
1716 from rhodecode.lib.vcs.backends.base import EmptyCommit
1716 from rhodecode.lib.vcs.backends.base import EmptyCommit
1717 dummy = EmptyCommit().__json__()
1717 dummy = EmptyCommit().__json__()
1718 if not self._changeset_cache:
1718 if not self._changeset_cache:
1719 return dummy
1719 return dummy
1720 try:
1720 try:
1721 return json.loads(self._changeset_cache)
1721 return json.loads(self._changeset_cache)
1722 except TypeError:
1722 except TypeError:
1723 return dummy
1723 return dummy
1724 except Exception:
1724 except Exception:
1725 log.error(traceback.format_exc())
1725 log.error(traceback.format_exc())
1726 return dummy
1726 return dummy
1727
1727
1728 @changeset_cache.setter
1728 @changeset_cache.setter
1729 def changeset_cache(self, val):
1729 def changeset_cache(self, val):
1730 try:
1730 try:
1731 self._changeset_cache = json.dumps(val)
1731 self._changeset_cache = json.dumps(val)
1732 except Exception:
1732 except Exception:
1733 log.error(traceback.format_exc())
1733 log.error(traceback.format_exc())
1734
1734
1735 @hybrid_property
1735 @hybrid_property
1736 def repo_name(self):
1736 def repo_name(self):
1737 return self._repo_name
1737 return self._repo_name
1738
1738
1739 @repo_name.setter
1739 @repo_name.setter
1740 def repo_name(self, value):
1740 def repo_name(self, value):
1741 self._repo_name = value
1741 self._repo_name = value
1742 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1742 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1743
1743
1744 @classmethod
1744 @classmethod
1745 def normalize_repo_name(cls, repo_name):
1745 def normalize_repo_name(cls, repo_name):
1746 """
1746 """
1747 Normalizes os specific repo_name to the format internally stored inside
1747 Normalizes os specific repo_name to the format internally stored inside
1748 database using URL_SEP
1748 database using URL_SEP
1749
1749
1750 :param cls:
1750 :param cls:
1751 :param repo_name:
1751 :param repo_name:
1752 """
1752 """
1753 return cls.NAME_SEP.join(repo_name.split(os.sep))
1753 return cls.NAME_SEP.join(repo_name.split(os.sep))
1754
1754
1755 @classmethod
1755 @classmethod
1756 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1756 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1757 session = Session()
1757 session = Session()
1758 q = session.query(cls).filter(cls.repo_name == repo_name)
1758 q = session.query(cls).filter(cls.repo_name == repo_name)
1759
1759
1760 if cache:
1760 if cache:
1761 if identity_cache:
1761 if identity_cache:
1762 val = cls.identity_cache(session, 'repo_name', repo_name)
1762 val = cls.identity_cache(session, 'repo_name', repo_name)
1763 if val:
1763 if val:
1764 return val
1764 return val
1765 else:
1765 else:
1766 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1766 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1767 q = q.options(
1767 q = q.options(
1768 FromCache("sql_cache_short", cache_key))
1768 FromCache("sql_cache_short", cache_key))
1769
1769
1770 return q.scalar()
1770 return q.scalar()
1771
1771
1772 @classmethod
1772 @classmethod
1773 def get_by_id_or_repo_name(cls, repoid):
1773 def get_by_id_or_repo_name(cls, repoid):
1774 if isinstance(repoid, (int, long)):
1774 if isinstance(repoid, (int, long)):
1775 try:
1775 try:
1776 repo = cls.get(repoid)
1776 repo = cls.get(repoid)
1777 except ValueError:
1777 except ValueError:
1778 repo = None
1778 repo = None
1779 else:
1779 else:
1780 repo = cls.get_by_repo_name(repoid)
1780 repo = cls.get_by_repo_name(repoid)
1781 return repo
1781 return repo
1782
1782
1783 @classmethod
1783 @classmethod
1784 def get_by_full_path(cls, repo_full_path):
1784 def get_by_full_path(cls, repo_full_path):
1785 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1785 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1786 repo_name = cls.normalize_repo_name(repo_name)
1786 repo_name = cls.normalize_repo_name(repo_name)
1787 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1787 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1788
1788
1789 @classmethod
1789 @classmethod
1790 def get_repo_forks(cls, repo_id):
1790 def get_repo_forks(cls, repo_id):
1791 return cls.query().filter(Repository.fork_id == repo_id)
1791 return cls.query().filter(Repository.fork_id == repo_id)
1792
1792
1793 @classmethod
1793 @classmethod
1794 def base_path(cls):
1794 def base_path(cls):
1795 """
1795 """
1796 Returns base path when all repos are stored
1796 Returns base path when all repos are stored
1797
1797
1798 :param cls:
1798 :param cls:
1799 """
1799 """
1800 q = Session().query(RhodeCodeUi)\
1800 q = Session().query(RhodeCodeUi)\
1801 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1801 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1802 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1802 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1803 return q.one().ui_value
1803 return q.one().ui_value
1804
1804
1805 @classmethod
1805 @classmethod
1806 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1806 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1807 case_insensitive=True, archived=False):
1807 case_insensitive=True, archived=False):
1808 q = Repository.query()
1808 q = Repository.query()
1809
1809
1810 if not archived:
1810 if not archived:
1811 q = q.filter(Repository.archived.isnot(true()))
1811 q = q.filter(Repository.archived.isnot(true()))
1812
1812
1813 if not isinstance(user_id, Optional):
1813 if not isinstance(user_id, Optional):
1814 q = q.filter(Repository.user_id == user_id)
1814 q = q.filter(Repository.user_id == user_id)
1815
1815
1816 if not isinstance(group_id, Optional):
1816 if not isinstance(group_id, Optional):
1817 q = q.filter(Repository.group_id == group_id)
1817 q = q.filter(Repository.group_id == group_id)
1818
1818
1819 if case_insensitive:
1819 if case_insensitive:
1820 q = q.order_by(func.lower(Repository.repo_name))
1820 q = q.order_by(func.lower(Repository.repo_name))
1821 else:
1821 else:
1822 q = q.order_by(Repository.repo_name)
1822 q = q.order_by(Repository.repo_name)
1823
1823
1824 return q.all()
1824 return q.all()
1825
1825
1826 @property
1826 @property
1827 def forks(self):
1827 def forks(self):
1828 """
1828 """
1829 Return forks of this repo
1829 Return forks of this repo
1830 """
1830 """
1831 return Repository.get_repo_forks(self.repo_id)
1831 return Repository.get_repo_forks(self.repo_id)
1832
1832
1833 @property
1833 @property
1834 def parent(self):
1834 def parent(self):
1835 """
1835 """
1836 Returns fork parent
1836 Returns fork parent
1837 """
1837 """
1838 return self.fork
1838 return self.fork
1839
1839
1840 @property
1840 @property
1841 def just_name(self):
1841 def just_name(self):
1842 return self.repo_name.split(self.NAME_SEP)[-1]
1842 return self.repo_name.split(self.NAME_SEP)[-1]
1843
1843
1844 @property
1844 @property
1845 def groups_with_parents(self):
1845 def groups_with_parents(self):
1846 groups = []
1846 groups = []
1847 if self.group is None:
1847 if self.group is None:
1848 return groups
1848 return groups
1849
1849
1850 cur_gr = self.group
1850 cur_gr = self.group
1851 groups.insert(0, cur_gr)
1851 groups.insert(0, cur_gr)
1852 while 1:
1852 while 1:
1853 gr = getattr(cur_gr, 'parent_group', None)
1853 gr = getattr(cur_gr, 'parent_group', None)
1854 cur_gr = cur_gr.parent_group
1854 cur_gr = cur_gr.parent_group
1855 if gr is None:
1855 if gr is None:
1856 break
1856 break
1857 groups.insert(0, gr)
1857 groups.insert(0, gr)
1858
1858
1859 return groups
1859 return groups
1860
1860
1861 @property
1861 @property
1862 def groups_and_repo(self):
1862 def groups_and_repo(self):
1863 return self.groups_with_parents, self
1863 return self.groups_with_parents, self
1864
1864
1865 @LazyProperty
1865 @LazyProperty
1866 def repo_path(self):
1866 def repo_path(self):
1867 """
1867 """
1868 Returns base full path for that repository means where it actually
1868 Returns base full path for that repository means where it actually
1869 exists on a filesystem
1869 exists on a filesystem
1870 """
1870 """
1871 q = Session().query(RhodeCodeUi).filter(
1871 q = Session().query(RhodeCodeUi).filter(
1872 RhodeCodeUi.ui_key == self.NAME_SEP)
1872 RhodeCodeUi.ui_key == self.NAME_SEP)
1873 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1873 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1874 return q.one().ui_value
1874 return q.one().ui_value
1875
1875
1876 @property
1876 @property
1877 def repo_full_path(self):
1877 def repo_full_path(self):
1878 p = [self.repo_path]
1878 p = [self.repo_path]
1879 # we need to split the name by / since this is how we store the
1879 # we need to split the name by / since this is how we store the
1880 # names in the database, but that eventually needs to be converted
1880 # names in the database, but that eventually needs to be converted
1881 # into a valid system path
1881 # into a valid system path
1882 p += self.repo_name.split(self.NAME_SEP)
1882 p += self.repo_name.split(self.NAME_SEP)
1883 return os.path.join(*map(safe_unicode, p))
1883 return os.path.join(*map(safe_unicode, p))
1884
1884
1885 @property
1885 @property
1886 def cache_keys(self):
1886 def cache_keys(self):
1887 """
1887 """
1888 Returns associated cache keys for that repo
1888 Returns associated cache keys for that repo
1889 """
1889 """
1890 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1890 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1891 repo_id=self.repo_id)
1891 repo_id=self.repo_id)
1892 return CacheKey.query()\
1892 return CacheKey.query()\
1893 .filter(CacheKey.cache_args == invalidation_namespace)\
1893 .filter(CacheKey.cache_args == invalidation_namespace)\
1894 .order_by(CacheKey.cache_key)\
1894 .order_by(CacheKey.cache_key)\
1895 .all()
1895 .all()
1896
1896
1897 @property
1897 @property
1898 def cached_diffs_relative_dir(self):
1898 def cached_diffs_relative_dir(self):
1899 """
1899 """
1900 Return a relative to the repository store path of cached diffs
1900 Return a relative to the repository store path of cached diffs
1901 used for safe display for users, who shouldn't know the absolute store
1901 used for safe display for users, who shouldn't know the absolute store
1902 path
1902 path
1903 """
1903 """
1904 return os.path.join(
1904 return os.path.join(
1905 os.path.dirname(self.repo_name),
1905 os.path.dirname(self.repo_name),
1906 self.cached_diffs_dir.split(os.path.sep)[-1])
1906 self.cached_diffs_dir.split(os.path.sep)[-1])
1907
1907
1908 @property
1908 @property
1909 def cached_diffs_dir(self):
1909 def cached_diffs_dir(self):
1910 path = self.repo_full_path
1910 path = self.repo_full_path
1911 return os.path.join(
1911 return os.path.join(
1912 os.path.dirname(path),
1912 os.path.dirname(path),
1913 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1913 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1914
1914
1915 def cached_diffs(self):
1915 def cached_diffs(self):
1916 diff_cache_dir = self.cached_diffs_dir
1916 diff_cache_dir = self.cached_diffs_dir
1917 if os.path.isdir(diff_cache_dir):
1917 if os.path.isdir(diff_cache_dir):
1918 return os.listdir(diff_cache_dir)
1918 return os.listdir(diff_cache_dir)
1919 return []
1919 return []
1920
1920
1921 def shadow_repos(self):
1921 def shadow_repos(self):
1922 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1922 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1923 return [
1923 return [
1924 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1924 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1925 if x.startswith(shadow_repos_pattern)]
1925 if x.startswith(shadow_repos_pattern)]
1926
1926
1927 def get_new_name(self, repo_name):
1927 def get_new_name(self, repo_name):
1928 """
1928 """
1929 returns new full repository name based on assigned group and new new
1929 returns new full repository name based on assigned group and new new
1930
1930
1931 :param group_name:
1931 :param group_name:
1932 """
1932 """
1933 path_prefix = self.group.full_path_splitted if self.group else []
1933 path_prefix = self.group.full_path_splitted if self.group else []
1934 return self.NAME_SEP.join(path_prefix + [repo_name])
1934 return self.NAME_SEP.join(path_prefix + [repo_name])
1935
1935
1936 @property
1936 @property
1937 def _config(self):
1937 def _config(self):
1938 """
1938 """
1939 Returns db based config object.
1939 Returns db based config object.
1940 """
1940 """
1941 from rhodecode.lib.utils import make_db_config
1941 from rhodecode.lib.utils import make_db_config
1942 return make_db_config(clear_session=False, repo=self)
1942 return make_db_config(clear_session=False, repo=self)
1943
1943
1944 def permissions(self, with_admins=True, with_owner=True,
1944 def permissions(self, with_admins=True, with_owner=True,
1945 expand_from_user_groups=False):
1945 expand_from_user_groups=False):
1946 """
1946 """
1947 Permissions for repositories
1947 Permissions for repositories
1948 """
1948 """
1949 _admin_perm = 'repository.admin'
1949 _admin_perm = 'repository.admin'
1950
1950
1951 owner_row = []
1951 owner_row = []
1952 if with_owner:
1952 if with_owner:
1953 usr = AttributeDict(self.user.get_dict())
1953 usr = AttributeDict(self.user.get_dict())
1954 usr.owner_row = True
1954 usr.owner_row = True
1955 usr.permission = _admin_perm
1955 usr.permission = _admin_perm
1956 usr.permission_id = None
1956 usr.permission_id = None
1957 owner_row.append(usr)
1957 owner_row.append(usr)
1958
1958
1959 super_admin_ids = []
1959 super_admin_ids = []
1960 super_admin_rows = []
1960 super_admin_rows = []
1961 if with_admins:
1961 if with_admins:
1962 for usr in User.get_all_super_admins():
1962 for usr in User.get_all_super_admins():
1963 super_admin_ids.append(usr.user_id)
1963 super_admin_ids.append(usr.user_id)
1964 # if this admin is also owner, don't double the record
1964 # if this admin is also owner, don't double the record
1965 if usr.user_id == owner_row[0].user_id:
1965 if usr.user_id == owner_row[0].user_id:
1966 owner_row[0].admin_row = True
1966 owner_row[0].admin_row = True
1967 else:
1967 else:
1968 usr = AttributeDict(usr.get_dict())
1968 usr = AttributeDict(usr.get_dict())
1969 usr.admin_row = True
1969 usr.admin_row = True
1970 usr.permission = _admin_perm
1970 usr.permission = _admin_perm
1971 usr.permission_id = None
1971 usr.permission_id = None
1972 super_admin_rows.append(usr)
1972 super_admin_rows.append(usr)
1973
1973
1974 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1974 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1975 q = q.options(joinedload(UserRepoToPerm.repository),
1975 q = q.options(joinedload(UserRepoToPerm.repository),
1976 joinedload(UserRepoToPerm.user),
1976 joinedload(UserRepoToPerm.user),
1977 joinedload(UserRepoToPerm.permission),)
1977 joinedload(UserRepoToPerm.permission),)
1978
1978
1979 # get owners and admins and permissions. We do a trick of re-writing
1979 # get owners and admins and permissions. We do a trick of re-writing
1980 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1980 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1981 # has a global reference and changing one object propagates to all
1981 # has a global reference and changing one object propagates to all
1982 # others. This means if admin is also an owner admin_row that change
1982 # others. This means if admin is also an owner admin_row that change
1983 # would propagate to both objects
1983 # would propagate to both objects
1984 perm_rows = []
1984 perm_rows = []
1985 for _usr in q.all():
1985 for _usr in q.all():
1986 usr = AttributeDict(_usr.user.get_dict())
1986 usr = AttributeDict(_usr.user.get_dict())
1987 # if this user is also owner/admin, mark as duplicate record
1987 # if this user is also owner/admin, mark as duplicate record
1988 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1988 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1989 usr.duplicate_perm = True
1989 usr.duplicate_perm = True
1990 # also check if this permission is maybe used by branch_permissions
1990 # also check if this permission is maybe used by branch_permissions
1991 if _usr.branch_perm_entry:
1991 if _usr.branch_perm_entry:
1992 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1992 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1993
1993
1994 usr.permission = _usr.permission.permission_name
1994 usr.permission = _usr.permission.permission_name
1995 usr.permission_id = _usr.repo_to_perm_id
1995 usr.permission_id = _usr.repo_to_perm_id
1996 perm_rows.append(usr)
1996 perm_rows.append(usr)
1997
1997
1998 # filter the perm rows by 'default' first and then sort them by
1998 # filter the perm rows by 'default' first and then sort them by
1999 # admin,write,read,none permissions sorted again alphabetically in
1999 # admin,write,read,none permissions sorted again alphabetically in
2000 # each group
2000 # each group
2001 perm_rows = sorted(perm_rows, key=display_user_sort)
2001 perm_rows = sorted(perm_rows, key=display_user_sort)
2002
2002
2003 user_groups_rows = []
2003 user_groups_rows = []
2004 if expand_from_user_groups:
2004 if expand_from_user_groups:
2005 for ug in self.permission_user_groups(with_members=True):
2005 for ug in self.permission_user_groups(with_members=True):
2006 for user_data in ug.members:
2006 for user_data in ug.members:
2007 user_groups_rows.append(user_data)
2007 user_groups_rows.append(user_data)
2008
2008
2009 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2009 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2010
2010
2011 def permission_user_groups(self, with_members=True):
2011 def permission_user_groups(self, with_members=True):
2012 q = UserGroupRepoToPerm.query()\
2012 q = UserGroupRepoToPerm.query()\
2013 .filter(UserGroupRepoToPerm.repository == self)
2013 .filter(UserGroupRepoToPerm.repository == self)
2014 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2014 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2015 joinedload(UserGroupRepoToPerm.users_group),
2015 joinedload(UserGroupRepoToPerm.users_group),
2016 joinedload(UserGroupRepoToPerm.permission),)
2016 joinedload(UserGroupRepoToPerm.permission),)
2017
2017
2018 perm_rows = []
2018 perm_rows = []
2019 for _user_group in q.all():
2019 for _user_group in q.all():
2020 entry = AttributeDict(_user_group.users_group.get_dict())
2020 entry = AttributeDict(_user_group.users_group.get_dict())
2021 entry.permission = _user_group.permission.permission_name
2021 entry.permission = _user_group.permission.permission_name
2022 if with_members:
2022 if with_members:
2023 entry.members = [x.user.get_dict()
2023 entry.members = [x.user.get_dict()
2024 for x in _user_group.users_group.members]
2024 for x in _user_group.users_group.members]
2025 perm_rows.append(entry)
2025 perm_rows.append(entry)
2026
2026
2027 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2027 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2028 return perm_rows
2028 return perm_rows
2029
2029
2030 def get_api_data(self, include_secrets=False):
2030 def get_api_data(self, include_secrets=False):
2031 """
2031 """
2032 Common function for generating repo api data
2032 Common function for generating repo api data
2033
2033
2034 :param include_secrets: See :meth:`User.get_api_data`.
2034 :param include_secrets: See :meth:`User.get_api_data`.
2035
2035
2036 """
2036 """
2037 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2037 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2038 # move this methods on models level.
2038 # move this methods on models level.
2039 from rhodecode.model.settings import SettingsModel
2039 from rhodecode.model.settings import SettingsModel
2040 from rhodecode.model.repo import RepoModel
2040 from rhodecode.model.repo import RepoModel
2041
2041
2042 repo = self
2042 repo = self
2043 _user_id, _time, _reason = self.locked
2043 _user_id, _time, _reason = self.locked
2044
2044
2045 data = {
2045 data = {
2046 'repo_id': repo.repo_id,
2046 'repo_id': repo.repo_id,
2047 'repo_name': repo.repo_name,
2047 'repo_name': repo.repo_name,
2048 'repo_type': repo.repo_type,
2048 'repo_type': repo.repo_type,
2049 'clone_uri': repo.clone_uri or '',
2049 'clone_uri': repo.clone_uri or '',
2050 'push_uri': repo.push_uri or '',
2050 'push_uri': repo.push_uri or '',
2051 'url': RepoModel().get_url(self),
2051 'url': RepoModel().get_url(self),
2052 'private': repo.private,
2052 'private': repo.private,
2053 'created_on': repo.created_on,
2053 'created_on': repo.created_on,
2054 'description': repo.description_safe,
2054 'description': repo.description_safe,
2055 'landing_rev': repo.landing_rev,
2055 'landing_rev': repo.landing_rev,
2056 'owner': repo.user.username,
2056 'owner': repo.user.username,
2057 'fork_of': repo.fork.repo_name if repo.fork else None,
2057 'fork_of': repo.fork.repo_name if repo.fork else None,
2058 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2058 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2059 'enable_statistics': repo.enable_statistics,
2059 'enable_statistics': repo.enable_statistics,
2060 'enable_locking': repo.enable_locking,
2060 'enable_locking': repo.enable_locking,
2061 'enable_downloads': repo.enable_downloads,
2061 'enable_downloads': repo.enable_downloads,
2062 'last_changeset': repo.changeset_cache,
2062 'last_changeset': repo.changeset_cache,
2063 'locked_by': User.get(_user_id).get_api_data(
2063 'locked_by': User.get(_user_id).get_api_data(
2064 include_secrets=include_secrets) if _user_id else None,
2064 include_secrets=include_secrets) if _user_id else None,
2065 'locked_date': time_to_datetime(_time) if _time else None,
2065 'locked_date': time_to_datetime(_time) if _time else None,
2066 'lock_reason': _reason if _reason else None,
2066 'lock_reason': _reason if _reason else None,
2067 }
2067 }
2068
2068
2069 # TODO: mikhail: should be per-repo settings here
2069 # TODO: mikhail: should be per-repo settings here
2070 rc_config = SettingsModel().get_all_settings()
2070 rc_config = SettingsModel().get_all_settings()
2071 repository_fields = str2bool(
2071 repository_fields = str2bool(
2072 rc_config.get('rhodecode_repository_fields'))
2072 rc_config.get('rhodecode_repository_fields'))
2073 if repository_fields:
2073 if repository_fields:
2074 for f in self.extra_fields:
2074 for f in self.extra_fields:
2075 data[f.field_key_prefixed] = f.field_value
2075 data[f.field_key_prefixed] = f.field_value
2076
2076
2077 return data
2077 return data
2078
2078
2079 @classmethod
2079 @classmethod
2080 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2080 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2081 if not lock_time:
2081 if not lock_time:
2082 lock_time = time.time()
2082 lock_time = time.time()
2083 if not lock_reason:
2083 if not lock_reason:
2084 lock_reason = cls.LOCK_AUTOMATIC
2084 lock_reason = cls.LOCK_AUTOMATIC
2085 repo.locked = [user_id, lock_time, lock_reason]
2085 repo.locked = [user_id, lock_time, lock_reason]
2086 Session().add(repo)
2086 Session().add(repo)
2087 Session().commit()
2087 Session().commit()
2088
2088
2089 @classmethod
2089 @classmethod
2090 def unlock(cls, repo):
2090 def unlock(cls, repo):
2091 repo.locked = None
2091 repo.locked = None
2092 Session().add(repo)
2092 Session().add(repo)
2093 Session().commit()
2093 Session().commit()
2094
2094
2095 @classmethod
2095 @classmethod
2096 def getlock(cls, repo):
2096 def getlock(cls, repo):
2097 return repo.locked
2097 return repo.locked
2098
2098
2099 def is_user_lock(self, user_id):
2099 def is_user_lock(self, user_id):
2100 if self.lock[0]:
2100 if self.lock[0]:
2101 lock_user_id = safe_int(self.lock[0])
2101 lock_user_id = safe_int(self.lock[0])
2102 user_id = safe_int(user_id)
2102 user_id = safe_int(user_id)
2103 # both are ints, and they are equal
2103 # both are ints, and they are equal
2104 return all([lock_user_id, user_id]) and lock_user_id == user_id
2104 return all([lock_user_id, user_id]) and lock_user_id == user_id
2105
2105
2106 return False
2106 return False
2107
2107
2108 def get_locking_state(self, action, user_id, only_when_enabled=True):
2108 def get_locking_state(self, action, user_id, only_when_enabled=True):
2109 """
2109 """
2110 Checks locking on this repository, if locking is enabled and lock is
2110 Checks locking on this repository, if locking is enabled and lock is
2111 present returns a tuple of make_lock, locked, locked_by.
2111 present returns a tuple of make_lock, locked, locked_by.
2112 make_lock can have 3 states None (do nothing) True, make lock
2112 make_lock can have 3 states None (do nothing) True, make lock
2113 False release lock, This value is later propagated to hooks, which
2113 False release lock, This value is later propagated to hooks, which
2114 do the locking. Think about this as signals passed to hooks what to do.
2114 do the locking. Think about this as signals passed to hooks what to do.
2115
2115
2116 """
2116 """
2117 # TODO: johbo: This is part of the business logic and should be moved
2117 # TODO: johbo: This is part of the business logic and should be moved
2118 # into the RepositoryModel.
2118 # into the RepositoryModel.
2119
2119
2120 if action not in ('push', 'pull'):
2120 if action not in ('push', 'pull'):
2121 raise ValueError("Invalid action value: %s" % repr(action))
2121 raise ValueError("Invalid action value: %s" % repr(action))
2122
2122
2123 # defines if locked error should be thrown to user
2123 # defines if locked error should be thrown to user
2124 currently_locked = False
2124 currently_locked = False
2125 # defines if new lock should be made, tri-state
2125 # defines if new lock should be made, tri-state
2126 make_lock = None
2126 make_lock = None
2127 repo = self
2127 repo = self
2128 user = User.get(user_id)
2128 user = User.get(user_id)
2129
2129
2130 lock_info = repo.locked
2130 lock_info = repo.locked
2131
2131
2132 if repo and (repo.enable_locking or not only_when_enabled):
2132 if repo and (repo.enable_locking or not only_when_enabled):
2133 if action == 'push':
2133 if action == 'push':
2134 # check if it's already locked !, if it is compare users
2134 # check if it's already locked !, if it is compare users
2135 locked_by_user_id = lock_info[0]
2135 locked_by_user_id = lock_info[0]
2136 if user.user_id == locked_by_user_id:
2136 if user.user_id == locked_by_user_id:
2137 log.debug(
2137 log.debug(
2138 'Got `push` action from user %s, now unlocking', user)
2138 'Got `push` action from user %s, now unlocking', user)
2139 # unlock if we have push from user who locked
2139 # unlock if we have push from user who locked
2140 make_lock = False
2140 make_lock = False
2141 else:
2141 else:
2142 # we're not the same user who locked, ban with
2142 # we're not the same user who locked, ban with
2143 # code defined in settings (default is 423 HTTP Locked) !
2143 # code defined in settings (default is 423 HTTP Locked) !
2144 log.debug('Repo %s is currently locked by %s', repo, user)
2144 log.debug('Repo %s is currently locked by %s', repo, user)
2145 currently_locked = True
2145 currently_locked = True
2146 elif action == 'pull':
2146 elif action == 'pull':
2147 # [0] user [1] date
2147 # [0] user [1] date
2148 if lock_info[0] and lock_info[1]:
2148 if lock_info[0] and lock_info[1]:
2149 log.debug('Repo %s is currently locked by %s', repo, user)
2149 log.debug('Repo %s is currently locked by %s', repo, user)
2150 currently_locked = True
2150 currently_locked = True
2151 else:
2151 else:
2152 log.debug('Setting lock on repo %s by %s', repo, user)
2152 log.debug('Setting lock on repo %s by %s', repo, user)
2153 make_lock = True
2153 make_lock = True
2154
2154
2155 else:
2155 else:
2156 log.debug('Repository %s do not have locking enabled', repo)
2156 log.debug('Repository %s do not have locking enabled', repo)
2157
2157
2158 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2158 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2159 make_lock, currently_locked, lock_info)
2159 make_lock, currently_locked, lock_info)
2160
2160
2161 from rhodecode.lib.auth import HasRepoPermissionAny
2161 from rhodecode.lib.auth import HasRepoPermissionAny
2162 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2162 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2163 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2163 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2164 # if we don't have at least write permission we cannot make a lock
2164 # if we don't have at least write permission we cannot make a lock
2165 log.debug('lock state reset back to FALSE due to lack '
2165 log.debug('lock state reset back to FALSE due to lack '
2166 'of at least read permission')
2166 'of at least read permission')
2167 make_lock = False
2167 make_lock = False
2168
2168
2169 return make_lock, currently_locked, lock_info
2169 return make_lock, currently_locked, lock_info
2170
2170
2171 @property
2171 @property
2172 def last_db_change(self):
2172 def last_db_change(self):
2173 return self.updated_on
2173 return self.updated_on
2174
2174
2175 @property
2175 @property
2176 def clone_uri_hidden(self):
2176 def clone_uri_hidden(self):
2177 clone_uri = self.clone_uri
2177 clone_uri = self.clone_uri
2178 if clone_uri:
2178 if clone_uri:
2179 import urlobject
2179 import urlobject
2180 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2180 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2181 if url_obj.password:
2181 if url_obj.password:
2182 clone_uri = url_obj.with_password('*****')
2182 clone_uri = url_obj.with_password('*****')
2183 return clone_uri
2183 return clone_uri
2184
2184
2185 @property
2185 @property
2186 def push_uri_hidden(self):
2186 def push_uri_hidden(self):
2187 push_uri = self.push_uri
2187 push_uri = self.push_uri
2188 if push_uri:
2188 if push_uri:
2189 import urlobject
2189 import urlobject
2190 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2190 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2191 if url_obj.password:
2191 if url_obj.password:
2192 push_uri = url_obj.with_password('*****')
2192 push_uri = url_obj.with_password('*****')
2193 return push_uri
2193 return push_uri
2194
2194
2195 def clone_url(self, **override):
2195 def clone_url(self, **override):
2196 from rhodecode.model.settings import SettingsModel
2196 from rhodecode.model.settings import SettingsModel
2197
2197
2198 uri_tmpl = None
2198 uri_tmpl = None
2199 if 'with_id' in override:
2199 if 'with_id' in override:
2200 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2200 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2201 del override['with_id']
2201 del override['with_id']
2202
2202
2203 if 'uri_tmpl' in override:
2203 if 'uri_tmpl' in override:
2204 uri_tmpl = override['uri_tmpl']
2204 uri_tmpl = override['uri_tmpl']
2205 del override['uri_tmpl']
2205 del override['uri_tmpl']
2206
2206
2207 ssh = False
2207 ssh = False
2208 if 'ssh' in override:
2208 if 'ssh' in override:
2209 ssh = True
2209 ssh = True
2210 del override['ssh']
2210 del override['ssh']
2211
2211
2212 # we didn't override our tmpl from **overrides
2212 # we didn't override our tmpl from **overrides
2213 if not uri_tmpl:
2213 if not uri_tmpl:
2214 rc_config = SettingsModel().get_all_settings(cache=True)
2214 rc_config = SettingsModel().get_all_settings(cache=True)
2215 if ssh:
2215 if ssh:
2216 uri_tmpl = rc_config.get(
2216 uri_tmpl = rc_config.get(
2217 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2217 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2218 else:
2218 else:
2219 uri_tmpl = rc_config.get(
2219 uri_tmpl = rc_config.get(
2220 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2220 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2221
2221
2222 request = get_current_request()
2222 request = get_current_request()
2223 return get_clone_url(request=request,
2223 return get_clone_url(request=request,
2224 uri_tmpl=uri_tmpl,
2224 uri_tmpl=uri_tmpl,
2225 repo_name=self.repo_name,
2225 repo_name=self.repo_name,
2226 repo_id=self.repo_id, **override)
2226 repo_id=self.repo_id, **override)
2227
2227
2228 def set_state(self, state):
2228 def set_state(self, state):
2229 self.repo_state = state
2229 self.repo_state = state
2230 Session().add(self)
2230 Session().add(self)
2231 #==========================================================================
2231 #==========================================================================
2232 # SCM PROPERTIES
2232 # SCM PROPERTIES
2233 #==========================================================================
2233 #==========================================================================
2234
2234
2235 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2235 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2236 return get_commit_safe(
2236 return get_commit_safe(
2237 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2237 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2238
2238
2239 def get_changeset(self, rev=None, pre_load=None):
2239 def get_changeset(self, rev=None, pre_load=None):
2240 warnings.warn("Use get_commit", DeprecationWarning)
2240 warnings.warn("Use get_commit", DeprecationWarning)
2241 commit_id = None
2241 commit_id = None
2242 commit_idx = None
2242 commit_idx = None
2243 if isinstance(rev, compat.string_types):
2243 if isinstance(rev, compat.string_types):
2244 commit_id = rev
2244 commit_id = rev
2245 else:
2245 else:
2246 commit_idx = rev
2246 commit_idx = rev
2247 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2247 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2248 pre_load=pre_load)
2248 pre_load=pre_load)
2249
2249
2250 def get_landing_commit(self):
2250 def get_landing_commit(self):
2251 """
2251 """
2252 Returns landing commit, or if that doesn't exist returns the tip
2252 Returns landing commit, or if that doesn't exist returns the tip
2253 """
2253 """
2254 _rev_type, _rev = self.landing_rev
2254 _rev_type, _rev = self.landing_rev
2255 commit = self.get_commit(_rev)
2255 commit = self.get_commit(_rev)
2256 if isinstance(commit, EmptyCommit):
2256 if isinstance(commit, EmptyCommit):
2257 return self.get_commit()
2257 return self.get_commit()
2258 return commit
2258 return commit
2259
2259
2260 def update_commit_cache(self, cs_cache=None, config=None):
2260 def update_commit_cache(self, cs_cache=None, config=None):
2261 """
2261 """
2262 Update cache of last changeset for repository, keys should be::
2262 Update cache of last changeset for repository, keys should be::
2263
2263
2264 short_id
2264 short_id
2265 raw_id
2265 raw_id
2266 revision
2266 revision
2267 parents
2267 parents
2268 message
2268 message
2269 date
2269 date
2270 author
2270 author
2271
2271
2272 :param cs_cache:
2272 :param cs_cache:
2273 """
2273 """
2274 from rhodecode.lib.vcs.backends.base import BaseChangeset
2274 from rhodecode.lib.vcs.backends.base import BaseChangeset
2275 if cs_cache is None:
2275 if cs_cache is None:
2276 # use no-cache version here
2276 # use no-cache version here
2277 scm_repo = self.scm_instance(cache=False, config=config)
2277 scm_repo = self.scm_instance(cache=False, config=config)
2278
2278
2279 empty = not scm_repo or scm_repo.is_empty()
2279 empty = not scm_repo or scm_repo.is_empty()
2280 if not empty:
2280 if not empty:
2281 cs_cache = scm_repo.get_commit(
2281 cs_cache = scm_repo.get_commit(
2282 pre_load=["author", "date", "message", "parents"])
2282 pre_load=["author", "date", "message", "parents"])
2283 else:
2283 else:
2284 cs_cache = EmptyCommit()
2284 cs_cache = EmptyCommit()
2285
2285
2286 if isinstance(cs_cache, BaseChangeset):
2286 if isinstance(cs_cache, BaseChangeset):
2287 cs_cache = cs_cache.__json__()
2287 cs_cache = cs_cache.__json__()
2288
2288
2289 def is_outdated(new_cs_cache):
2289 def is_outdated(new_cs_cache):
2290 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2290 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2291 new_cs_cache['revision'] != self.changeset_cache['revision']):
2291 new_cs_cache['revision'] != self.changeset_cache['revision']):
2292 return True
2292 return True
2293 return False
2293 return False
2294
2294
2295 # check if we have maybe already latest cached revision
2295 # check if we have maybe already latest cached revision
2296 if is_outdated(cs_cache) or not self.changeset_cache:
2296 if is_outdated(cs_cache) or not self.changeset_cache:
2297 _default = datetime.datetime.utcnow()
2297 _default = datetime.datetime.utcnow()
2298 last_change = cs_cache.get('date') or _default
2298 last_change = cs_cache.get('date') or _default
2299 if self.updated_on and self.updated_on > last_change:
2299 if self.updated_on and self.updated_on > last_change:
2300 # we check if last update is newer than the new value
2300 # we check if last update is newer than the new value
2301 # if yes, we use the current timestamp instead. Imagine you get
2301 # if yes, we use the current timestamp instead. Imagine you get
2302 # old commit pushed 1y ago, we'd set last update 1y to ago.
2302 # old commit pushed 1y ago, we'd set last update 1y to ago.
2303 last_change = _default
2303 last_change = _default
2304 log.debug('updated repo %s with new commit cache %s',
2304 log.debug('updated repo %s with new commit cache %s',
2305 self.repo_name, cs_cache)
2305 self.repo_name, cs_cache)
2306 self.updated_on = last_change
2306 self.updated_on = last_change
2307 self.changeset_cache = cs_cache
2307 self.changeset_cache = cs_cache
2308 Session().add(self)
2308 Session().add(self)
2309 Session().commit()
2309 Session().commit()
2310 else:
2310 else:
2311 log.debug('Skipping update_commit_cache for repo:`%s` '
2311 log.debug('Skipping update_commit_cache for repo:`%s` '
2312 'commit already with latest changes', self.repo_name)
2312 'commit already with latest changes', self.repo_name)
2313
2313
2314 @property
2314 @property
2315 def tip(self):
2315 def tip(self):
2316 return self.get_commit('tip')
2316 return self.get_commit('tip')
2317
2317
2318 @property
2318 @property
2319 def author(self):
2319 def author(self):
2320 return self.tip.author
2320 return self.tip.author
2321
2321
2322 @property
2322 @property
2323 def last_change(self):
2323 def last_change(self):
2324 return self.scm_instance().last_change
2324 return self.scm_instance().last_change
2325
2325
2326 def get_comments(self, revisions=None):
2326 def get_comments(self, revisions=None):
2327 """
2327 """
2328 Returns comments for this repository grouped by revisions
2328 Returns comments for this repository grouped by revisions
2329
2329
2330 :param revisions: filter query by revisions only
2330 :param revisions: filter query by revisions only
2331 """
2331 """
2332 cmts = ChangesetComment.query()\
2332 cmts = ChangesetComment.query()\
2333 .filter(ChangesetComment.repo == self)
2333 .filter(ChangesetComment.repo == self)
2334 if revisions:
2334 if revisions:
2335 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2335 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2336 grouped = collections.defaultdict(list)
2336 grouped = collections.defaultdict(list)
2337 for cmt in cmts.all():
2337 for cmt in cmts.all():
2338 grouped[cmt.revision].append(cmt)
2338 grouped[cmt.revision].append(cmt)
2339 return grouped
2339 return grouped
2340
2340
2341 def statuses(self, revisions=None):
2341 def statuses(self, revisions=None):
2342 """
2342 """
2343 Returns statuses for this repository
2343 Returns statuses for this repository
2344
2344
2345 :param revisions: list of revisions to get statuses for
2345 :param revisions: list of revisions to get statuses for
2346 """
2346 """
2347 statuses = ChangesetStatus.query()\
2347 statuses = ChangesetStatus.query()\
2348 .filter(ChangesetStatus.repo == self)\
2348 .filter(ChangesetStatus.repo == self)\
2349 .filter(ChangesetStatus.version == 0)
2349 .filter(ChangesetStatus.version == 0)
2350
2350
2351 if revisions:
2351 if revisions:
2352 # Try doing the filtering in chunks to avoid hitting limits
2352 # Try doing the filtering in chunks to avoid hitting limits
2353 size = 500
2353 size = 500
2354 status_results = []
2354 status_results = []
2355 for chunk in xrange(0, len(revisions), size):
2355 for chunk in xrange(0, len(revisions), size):
2356 status_results += statuses.filter(
2356 status_results += statuses.filter(
2357 ChangesetStatus.revision.in_(
2357 ChangesetStatus.revision.in_(
2358 revisions[chunk: chunk+size])
2358 revisions[chunk: chunk+size])
2359 ).all()
2359 ).all()
2360 else:
2360 else:
2361 status_results = statuses.all()
2361 status_results = statuses.all()
2362
2362
2363 grouped = {}
2363 grouped = {}
2364
2364
2365 # maybe we have open new pullrequest without a status?
2365 # maybe we have open new pullrequest without a status?
2366 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2366 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2367 status_lbl = ChangesetStatus.get_status_lbl(stat)
2367 status_lbl = ChangesetStatus.get_status_lbl(stat)
2368 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2368 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2369 for rev in pr.revisions:
2369 for rev in pr.revisions:
2370 pr_id = pr.pull_request_id
2370 pr_id = pr.pull_request_id
2371 pr_repo = pr.target_repo.repo_name
2371 pr_repo = pr.target_repo.repo_name
2372 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2372 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2373
2373
2374 for stat in status_results:
2374 for stat in status_results:
2375 pr_id = pr_repo = None
2375 pr_id = pr_repo = None
2376 if stat.pull_request:
2376 if stat.pull_request:
2377 pr_id = stat.pull_request.pull_request_id
2377 pr_id = stat.pull_request.pull_request_id
2378 pr_repo = stat.pull_request.target_repo.repo_name
2378 pr_repo = stat.pull_request.target_repo.repo_name
2379 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2379 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2380 pr_id, pr_repo]
2380 pr_id, pr_repo]
2381 return grouped
2381 return grouped
2382
2382
2383 # ==========================================================================
2383 # ==========================================================================
2384 # SCM CACHE INSTANCE
2384 # SCM CACHE INSTANCE
2385 # ==========================================================================
2385 # ==========================================================================
2386
2386
2387 def scm_instance(self, **kwargs):
2387 def scm_instance(self, **kwargs):
2388 import rhodecode
2388 import rhodecode
2389
2389
2390 # Passing a config will not hit the cache currently only used
2390 # Passing a config will not hit the cache currently only used
2391 # for repo2dbmapper
2391 # for repo2dbmapper
2392 config = kwargs.pop('config', None)
2392 config = kwargs.pop('config', None)
2393 cache = kwargs.pop('cache', None)
2393 cache = kwargs.pop('cache', None)
2394 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2394 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2395 # if cache is NOT defined use default global, else we have a full
2395 # if cache is NOT defined use default global, else we have a full
2396 # control over cache behaviour
2396 # control over cache behaviour
2397 if cache is None and full_cache and not config:
2397 if cache is None and full_cache and not config:
2398 return self._get_instance_cached()
2398 return self._get_instance_cached()
2399 return self._get_instance(cache=bool(cache), config=config)
2399 return self._get_instance(cache=bool(cache), config=config)
2400
2400
2401 def _get_instance_cached(self):
2401 def _get_instance_cached(self):
2402 from rhodecode.lib import rc_cache
2402 from rhodecode.lib import rc_cache
2403
2403
2404 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2404 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2405 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2405 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2406 repo_id=self.repo_id)
2406 repo_id=self.repo_id)
2407 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2407 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2408
2408
2409 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2409 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2410 def get_instance_cached(repo_id, context_id):
2410 def get_instance_cached(repo_id, context_id):
2411 return self._get_instance()
2411 return self._get_instance()
2412
2412
2413 # we must use thread scoped cache here,
2413 # we must use thread scoped cache here,
2414 # because each thread of gevent needs it's own not shared connection and cache
2414 # because each thread of gevent needs it's own not shared connection and cache
2415 # we also alter `args` so the cache key is individual for every green thread.
2415 # we also alter `args` so the cache key is individual for every green thread.
2416 inv_context_manager = rc_cache.InvalidationContext(
2416 inv_context_manager = rc_cache.InvalidationContext(
2417 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2417 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2418 thread_scoped=True)
2418 thread_scoped=True)
2419 with inv_context_manager as invalidation_context:
2419 with inv_context_manager as invalidation_context:
2420 args = (self.repo_id, inv_context_manager.cache_key)
2420 args = (self.repo_id, inv_context_manager.cache_key)
2421 # re-compute and store cache if we get invalidate signal
2421 # re-compute and store cache if we get invalidate signal
2422 if invalidation_context.should_invalidate():
2422 if invalidation_context.should_invalidate():
2423 instance = get_instance_cached.refresh(*args)
2423 instance = get_instance_cached.refresh(*args)
2424 else:
2424 else:
2425 instance = get_instance_cached(*args)
2425 instance = get_instance_cached(*args)
2426
2426
2427 log.debug(
2427 log.debug(
2428 'Repo instance fetched in %.3fs', inv_context_manager.compute_time)
2428 'Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2429 return instance
2429 return instance
2430
2430
2431 def _get_instance(self, cache=True, config=None):
2431 def _get_instance(self, cache=True, config=None):
2432 config = config or self._config
2432 config = config or self._config
2433 custom_wire = {
2433 custom_wire = {
2434 'cache': cache # controls the vcs.remote cache
2434 'cache': cache # controls the vcs.remote cache
2435 }
2435 }
2436 repo = get_vcs_instance(
2436 repo = get_vcs_instance(
2437 repo_path=safe_str(self.repo_full_path),
2437 repo_path=safe_str(self.repo_full_path),
2438 config=config,
2438 config=config,
2439 with_wire=custom_wire,
2439 with_wire=custom_wire,
2440 create=False,
2440 create=False,
2441 _vcs_alias=self.repo_type)
2441 _vcs_alias=self.repo_type)
2442
2442
2443 return repo
2443 return repo
2444
2444
2445 def __json__(self):
2445 def __json__(self):
2446 return {'landing_rev': self.landing_rev}
2446 return {'landing_rev': self.landing_rev}
2447
2447
2448 def get_dict(self):
2448 def get_dict(self):
2449
2449
2450 # Since we transformed `repo_name` to a hybrid property, we need to
2450 # Since we transformed `repo_name` to a hybrid property, we need to
2451 # keep compatibility with the code which uses `repo_name` field.
2451 # keep compatibility with the code which uses `repo_name` field.
2452
2452
2453 result = super(Repository, self).get_dict()
2453 result = super(Repository, self).get_dict()
2454 result['repo_name'] = result.pop('_repo_name', None)
2454 result['repo_name'] = result.pop('_repo_name', None)
2455 return result
2455 return result
2456
2456
2457
2457
2458 class RepoGroup(Base, BaseModel):
2458 class RepoGroup(Base, BaseModel):
2459 __tablename__ = 'groups'
2459 __tablename__ = 'groups'
2460 __table_args__ = (
2460 __table_args__ = (
2461 UniqueConstraint('group_name', 'group_parent_id'),
2461 UniqueConstraint('group_name', 'group_parent_id'),
2462 base_table_args,
2462 base_table_args,
2463 )
2463 )
2464 __mapper_args__ = {'order_by': 'group_name'}
2464 __mapper_args__ = {'order_by': 'group_name'}
2465
2465
2466 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2466 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2467
2467
2468 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2468 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2469 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2469 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2470 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2470 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2471 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2471 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2472 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2472 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2473 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2473 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2474 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2474 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2475 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2475 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2476 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2476 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2477
2477
2478 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2478 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2479 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2479 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2480 parent_group = relationship('RepoGroup', remote_side=group_id)
2480 parent_group = relationship('RepoGroup', remote_side=group_id)
2481 user = relationship('User')
2481 user = relationship('User')
2482 integrations = relationship('Integration',
2482 integrations = relationship('Integration',
2483 cascade="all, delete, delete-orphan")
2483 cascade="all, delete, delete-orphan")
2484
2484
2485 def __init__(self, group_name='', parent_group=None):
2485 def __init__(self, group_name='', parent_group=None):
2486 self.group_name = group_name
2486 self.group_name = group_name
2487 self.parent_group = parent_group
2487 self.parent_group = parent_group
2488
2488
2489 def __unicode__(self):
2489 def __unicode__(self):
2490 return u"<%s('id:%s:%s')>" % (
2490 return u"<%s('id:%s:%s')>" % (
2491 self.__class__.__name__, self.group_id, self.group_name)
2491 self.__class__.__name__, self.group_id, self.group_name)
2492
2492
2493 @hybrid_property
2493 @hybrid_property
2494 def description_safe(self):
2494 def description_safe(self):
2495 from rhodecode.lib import helpers as h
2495 from rhodecode.lib import helpers as h
2496 return h.escape(self.group_description)
2496 return h.escape(self.group_description)
2497
2497
2498 @classmethod
2498 @classmethod
2499 def _generate_choice(cls, repo_group):
2499 def _generate_choice(cls, repo_group):
2500 from webhelpers.html import literal as _literal
2500 from webhelpers.html import literal as _literal
2501 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2501 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2502 return repo_group.group_id, _name(repo_group.full_path_splitted)
2502 return repo_group.group_id, _name(repo_group.full_path_splitted)
2503
2503
2504 @classmethod
2504 @classmethod
2505 def groups_choices(cls, groups=None, show_empty_group=True):
2505 def groups_choices(cls, groups=None, show_empty_group=True):
2506 if not groups:
2506 if not groups:
2507 groups = cls.query().all()
2507 groups = cls.query().all()
2508
2508
2509 repo_groups = []
2509 repo_groups = []
2510 if show_empty_group:
2510 if show_empty_group:
2511 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2511 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2512
2512
2513 repo_groups.extend([cls._generate_choice(x) for x in groups])
2513 repo_groups.extend([cls._generate_choice(x) for x in groups])
2514
2514
2515 repo_groups = sorted(
2515 repo_groups = sorted(
2516 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2516 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2517 return repo_groups
2517 return repo_groups
2518
2518
2519 @classmethod
2519 @classmethod
2520 def url_sep(cls):
2520 def url_sep(cls):
2521 return URL_SEP
2521 return URL_SEP
2522
2522
2523 @classmethod
2523 @classmethod
2524 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2524 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2525 if case_insensitive:
2525 if case_insensitive:
2526 gr = cls.query().filter(func.lower(cls.group_name)
2526 gr = cls.query().filter(func.lower(cls.group_name)
2527 == func.lower(group_name))
2527 == func.lower(group_name))
2528 else:
2528 else:
2529 gr = cls.query().filter(cls.group_name == group_name)
2529 gr = cls.query().filter(cls.group_name == group_name)
2530 if cache:
2530 if cache:
2531 name_key = _hash_key(group_name)
2531 name_key = _hash_key(group_name)
2532 gr = gr.options(
2532 gr = gr.options(
2533 FromCache("sql_cache_short", "get_group_%s" % name_key))
2533 FromCache("sql_cache_short", "get_group_%s" % name_key))
2534 return gr.scalar()
2534 return gr.scalar()
2535
2535
2536 @classmethod
2536 @classmethod
2537 def get_user_personal_repo_group(cls, user_id):
2537 def get_user_personal_repo_group(cls, user_id):
2538 user = User.get(user_id)
2538 user = User.get(user_id)
2539 if user.username == User.DEFAULT_USER:
2539 if user.username == User.DEFAULT_USER:
2540 return None
2540 return None
2541
2541
2542 return cls.query()\
2542 return cls.query()\
2543 .filter(cls.personal == true()) \
2543 .filter(cls.personal == true()) \
2544 .filter(cls.user == user) \
2544 .filter(cls.user == user) \
2545 .order_by(cls.group_id.asc()) \
2545 .order_by(cls.group_id.asc()) \
2546 .first()
2546 .first()
2547
2547
2548 @classmethod
2548 @classmethod
2549 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2549 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2550 case_insensitive=True):
2550 case_insensitive=True):
2551 q = RepoGroup.query()
2551 q = RepoGroup.query()
2552
2552
2553 if not isinstance(user_id, Optional):
2553 if not isinstance(user_id, Optional):
2554 q = q.filter(RepoGroup.user_id == user_id)
2554 q = q.filter(RepoGroup.user_id == user_id)
2555
2555
2556 if not isinstance(group_id, Optional):
2556 if not isinstance(group_id, Optional):
2557 q = q.filter(RepoGroup.group_parent_id == group_id)
2557 q = q.filter(RepoGroup.group_parent_id == group_id)
2558
2558
2559 if case_insensitive:
2559 if case_insensitive:
2560 q = q.order_by(func.lower(RepoGroup.group_name))
2560 q = q.order_by(func.lower(RepoGroup.group_name))
2561 else:
2561 else:
2562 q = q.order_by(RepoGroup.group_name)
2562 q = q.order_by(RepoGroup.group_name)
2563 return q.all()
2563 return q.all()
2564
2564
2565 @property
2565 @property
2566 def parents(self):
2566 def parents(self):
2567 parents_recursion_limit = 10
2567 parents_recursion_limit = 10
2568 groups = []
2568 groups = []
2569 if self.parent_group is None:
2569 if self.parent_group is None:
2570 return groups
2570 return groups
2571 cur_gr = self.parent_group
2571 cur_gr = self.parent_group
2572 groups.insert(0, cur_gr)
2572 groups.insert(0, cur_gr)
2573 cnt = 0
2573 cnt = 0
2574 while 1:
2574 while 1:
2575 cnt += 1
2575 cnt += 1
2576 gr = getattr(cur_gr, 'parent_group', None)
2576 gr = getattr(cur_gr, 'parent_group', None)
2577 cur_gr = cur_gr.parent_group
2577 cur_gr = cur_gr.parent_group
2578 if gr is None:
2578 if gr is None:
2579 break
2579 break
2580 if cnt == parents_recursion_limit:
2580 if cnt == parents_recursion_limit:
2581 # this will prevent accidental infinit loops
2581 # this will prevent accidental infinit loops
2582 log.error('more than %s parents found for group %s, stopping '
2582 log.error('more than %s parents found for group %s, stopping '
2583 'recursive parent fetching', parents_recursion_limit, self)
2583 'recursive parent fetching', parents_recursion_limit, self)
2584 break
2584 break
2585
2585
2586 groups.insert(0, gr)
2586 groups.insert(0, gr)
2587 return groups
2587 return groups
2588
2588
2589 @property
2589 @property
2590 def last_db_change(self):
2590 def last_db_change(self):
2591 return self.updated_on
2591 return self.updated_on
2592
2592
2593 @property
2593 @property
2594 def children(self):
2594 def children(self):
2595 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2595 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2596
2596
2597 @property
2597 @property
2598 def name(self):
2598 def name(self):
2599 return self.group_name.split(RepoGroup.url_sep())[-1]
2599 return self.group_name.split(RepoGroup.url_sep())[-1]
2600
2600
2601 @property
2601 @property
2602 def full_path(self):
2602 def full_path(self):
2603 return self.group_name
2603 return self.group_name
2604
2604
2605 @property
2605 @property
2606 def full_path_splitted(self):
2606 def full_path_splitted(self):
2607 return self.group_name.split(RepoGroup.url_sep())
2607 return self.group_name.split(RepoGroup.url_sep())
2608
2608
2609 @property
2609 @property
2610 def repositories(self):
2610 def repositories(self):
2611 return Repository.query()\
2611 return Repository.query()\
2612 .filter(Repository.group == self)\
2612 .filter(Repository.group == self)\
2613 .order_by(Repository.repo_name)
2613 .order_by(Repository.repo_name)
2614
2614
2615 @property
2615 @property
2616 def repositories_recursive_count(self):
2616 def repositories_recursive_count(self):
2617 cnt = self.repositories.count()
2617 cnt = self.repositories.count()
2618
2618
2619 def children_count(group):
2619 def children_count(group):
2620 cnt = 0
2620 cnt = 0
2621 for child in group.children:
2621 for child in group.children:
2622 cnt += child.repositories.count()
2622 cnt += child.repositories.count()
2623 cnt += children_count(child)
2623 cnt += children_count(child)
2624 return cnt
2624 return cnt
2625
2625
2626 return cnt + children_count(self)
2626 return cnt + children_count(self)
2627
2627
2628 def _recursive_objects(self, include_repos=True):
2628 def _recursive_objects(self, include_repos=True):
2629 all_ = []
2629 all_ = []
2630
2630
2631 def _get_members(root_gr):
2631 def _get_members(root_gr):
2632 if include_repos:
2632 if include_repos:
2633 for r in root_gr.repositories:
2633 for r in root_gr.repositories:
2634 all_.append(r)
2634 all_.append(r)
2635 childs = root_gr.children.all()
2635 childs = root_gr.children.all()
2636 if childs:
2636 if childs:
2637 for gr in childs:
2637 for gr in childs:
2638 all_.append(gr)
2638 all_.append(gr)
2639 _get_members(gr)
2639 _get_members(gr)
2640
2640
2641 _get_members(self)
2641 _get_members(self)
2642 return [self] + all_
2642 return [self] + all_
2643
2643
2644 def recursive_groups_and_repos(self):
2644 def recursive_groups_and_repos(self):
2645 """
2645 """
2646 Recursive return all groups, with repositories in those groups
2646 Recursive return all groups, with repositories in those groups
2647 """
2647 """
2648 return self._recursive_objects()
2648 return self._recursive_objects()
2649
2649
2650 def recursive_groups(self):
2650 def recursive_groups(self):
2651 """
2651 """
2652 Returns all children groups for this group including children of children
2652 Returns all children groups for this group including children of children
2653 """
2653 """
2654 return self._recursive_objects(include_repos=False)
2654 return self._recursive_objects(include_repos=False)
2655
2655
2656 def get_new_name(self, group_name):
2656 def get_new_name(self, group_name):
2657 """
2657 """
2658 returns new full group name based on parent and new name
2658 returns new full group name based on parent and new name
2659
2659
2660 :param group_name:
2660 :param group_name:
2661 """
2661 """
2662 path_prefix = (self.parent_group.full_path_splitted if
2662 path_prefix = (self.parent_group.full_path_splitted if
2663 self.parent_group else [])
2663 self.parent_group else [])
2664 return RepoGroup.url_sep().join(path_prefix + [group_name])
2664 return RepoGroup.url_sep().join(path_prefix + [group_name])
2665
2665
2666 def permissions(self, with_admins=True, with_owner=True,
2666 def permissions(self, with_admins=True, with_owner=True,
2667 expand_from_user_groups=False):
2667 expand_from_user_groups=False):
2668 """
2668 """
2669 Permissions for repository groups
2669 Permissions for repository groups
2670 """
2670 """
2671 _admin_perm = 'group.admin'
2671 _admin_perm = 'group.admin'
2672
2672
2673 owner_row = []
2673 owner_row = []
2674 if with_owner:
2674 if with_owner:
2675 usr = AttributeDict(self.user.get_dict())
2675 usr = AttributeDict(self.user.get_dict())
2676 usr.owner_row = True
2676 usr.owner_row = True
2677 usr.permission = _admin_perm
2677 usr.permission = _admin_perm
2678 owner_row.append(usr)
2678 owner_row.append(usr)
2679
2679
2680 super_admin_ids = []
2680 super_admin_ids = []
2681 super_admin_rows = []
2681 super_admin_rows = []
2682 if with_admins:
2682 if with_admins:
2683 for usr in User.get_all_super_admins():
2683 for usr in User.get_all_super_admins():
2684 super_admin_ids.append(usr.user_id)
2684 super_admin_ids.append(usr.user_id)
2685 # if this admin is also owner, don't double the record
2685 # if this admin is also owner, don't double the record
2686 if usr.user_id == owner_row[0].user_id:
2686 if usr.user_id == owner_row[0].user_id:
2687 owner_row[0].admin_row = True
2687 owner_row[0].admin_row = True
2688 else:
2688 else:
2689 usr = AttributeDict(usr.get_dict())
2689 usr = AttributeDict(usr.get_dict())
2690 usr.admin_row = True
2690 usr.admin_row = True
2691 usr.permission = _admin_perm
2691 usr.permission = _admin_perm
2692 super_admin_rows.append(usr)
2692 super_admin_rows.append(usr)
2693
2693
2694 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2694 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2695 q = q.options(joinedload(UserRepoGroupToPerm.group),
2695 q = q.options(joinedload(UserRepoGroupToPerm.group),
2696 joinedload(UserRepoGroupToPerm.user),
2696 joinedload(UserRepoGroupToPerm.user),
2697 joinedload(UserRepoGroupToPerm.permission),)
2697 joinedload(UserRepoGroupToPerm.permission),)
2698
2698
2699 # get owners and admins and permissions. We do a trick of re-writing
2699 # get owners and admins and permissions. We do a trick of re-writing
2700 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2700 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2701 # has a global reference and changing one object propagates to all
2701 # has a global reference and changing one object propagates to all
2702 # others. This means if admin is also an owner admin_row that change
2702 # others. This means if admin is also an owner admin_row that change
2703 # would propagate to both objects
2703 # would propagate to both objects
2704 perm_rows = []
2704 perm_rows = []
2705 for _usr in q.all():
2705 for _usr in q.all():
2706 usr = AttributeDict(_usr.user.get_dict())
2706 usr = AttributeDict(_usr.user.get_dict())
2707 # if this user is also owner/admin, mark as duplicate record
2707 # if this user is also owner/admin, mark as duplicate record
2708 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2708 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2709 usr.duplicate_perm = True
2709 usr.duplicate_perm = True
2710 usr.permission = _usr.permission.permission_name
2710 usr.permission = _usr.permission.permission_name
2711 perm_rows.append(usr)
2711 perm_rows.append(usr)
2712
2712
2713 # filter the perm rows by 'default' first and then sort them by
2713 # filter the perm rows by 'default' first and then sort them by
2714 # admin,write,read,none permissions sorted again alphabetically in
2714 # admin,write,read,none permissions sorted again alphabetically in
2715 # each group
2715 # each group
2716 perm_rows = sorted(perm_rows, key=display_user_sort)
2716 perm_rows = sorted(perm_rows, key=display_user_sort)
2717
2717
2718 user_groups_rows = []
2718 user_groups_rows = []
2719 if expand_from_user_groups:
2719 if expand_from_user_groups:
2720 for ug in self.permission_user_groups(with_members=True):
2720 for ug in self.permission_user_groups(with_members=True):
2721 for user_data in ug.members:
2721 for user_data in ug.members:
2722 user_groups_rows.append(user_data)
2722 user_groups_rows.append(user_data)
2723
2723
2724 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2724 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2725
2725
2726 def permission_user_groups(self, with_members=False):
2726 def permission_user_groups(self, with_members=False):
2727 q = UserGroupRepoGroupToPerm.query()\
2727 q = UserGroupRepoGroupToPerm.query()\
2728 .filter(UserGroupRepoGroupToPerm.group == self)
2728 .filter(UserGroupRepoGroupToPerm.group == self)
2729 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2729 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2730 joinedload(UserGroupRepoGroupToPerm.users_group),
2730 joinedload(UserGroupRepoGroupToPerm.users_group),
2731 joinedload(UserGroupRepoGroupToPerm.permission),)
2731 joinedload(UserGroupRepoGroupToPerm.permission),)
2732
2732
2733 perm_rows = []
2733 perm_rows = []
2734 for _user_group in q.all():
2734 for _user_group in q.all():
2735 entry = AttributeDict(_user_group.users_group.get_dict())
2735 entry = AttributeDict(_user_group.users_group.get_dict())
2736 entry.permission = _user_group.permission.permission_name
2736 entry.permission = _user_group.permission.permission_name
2737 if with_members:
2737 if with_members:
2738 entry.members = [x.user.get_dict()
2738 entry.members = [x.user.get_dict()
2739 for x in _user_group.users_group.members]
2739 for x in _user_group.users_group.members]
2740 perm_rows.append(entry)
2740 perm_rows.append(entry)
2741
2741
2742 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2742 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2743 return perm_rows
2743 return perm_rows
2744
2744
2745 def get_api_data(self):
2745 def get_api_data(self):
2746 """
2746 """
2747 Common function for generating api data
2747 Common function for generating api data
2748
2748
2749 """
2749 """
2750 group = self
2750 group = self
2751 data = {
2751 data = {
2752 'group_id': group.group_id,
2752 'group_id': group.group_id,
2753 'group_name': group.group_name,
2753 'group_name': group.group_name,
2754 'group_description': group.description_safe,
2754 'group_description': group.description_safe,
2755 'parent_group': group.parent_group.group_name if group.parent_group else None,
2755 'parent_group': group.parent_group.group_name if group.parent_group else None,
2756 'repositories': [x.repo_name for x in group.repositories],
2756 'repositories': [x.repo_name for x in group.repositories],
2757 'owner': group.user.username,
2757 'owner': group.user.username,
2758 }
2758 }
2759 return data
2759 return data
2760
2760
2761
2761
2762 class Permission(Base, BaseModel):
2762 class Permission(Base, BaseModel):
2763 __tablename__ = 'permissions'
2763 __tablename__ = 'permissions'
2764 __table_args__ = (
2764 __table_args__ = (
2765 Index('p_perm_name_idx', 'permission_name'),
2765 Index('p_perm_name_idx', 'permission_name'),
2766 base_table_args,
2766 base_table_args,
2767 )
2767 )
2768
2768
2769 PERMS = [
2769 PERMS = [
2770 ('hg.admin', _('RhodeCode Super Administrator')),
2770 ('hg.admin', _('RhodeCode Super Administrator')),
2771
2771
2772 ('repository.none', _('Repository no access')),
2772 ('repository.none', _('Repository no access')),
2773 ('repository.read', _('Repository read access')),
2773 ('repository.read', _('Repository read access')),
2774 ('repository.write', _('Repository write access')),
2774 ('repository.write', _('Repository write access')),
2775 ('repository.admin', _('Repository admin access')),
2775 ('repository.admin', _('Repository admin access')),
2776
2776
2777 ('group.none', _('Repository group no access')),
2777 ('group.none', _('Repository group no access')),
2778 ('group.read', _('Repository group read access')),
2778 ('group.read', _('Repository group read access')),
2779 ('group.write', _('Repository group write access')),
2779 ('group.write', _('Repository group write access')),
2780 ('group.admin', _('Repository group admin access')),
2780 ('group.admin', _('Repository group admin access')),
2781
2781
2782 ('usergroup.none', _('User group no access')),
2782 ('usergroup.none', _('User group no access')),
2783 ('usergroup.read', _('User group read access')),
2783 ('usergroup.read', _('User group read access')),
2784 ('usergroup.write', _('User group write access')),
2784 ('usergroup.write', _('User group write access')),
2785 ('usergroup.admin', _('User group admin access')),
2785 ('usergroup.admin', _('User group admin access')),
2786
2786
2787 ('branch.none', _('Branch no permissions')),
2787 ('branch.none', _('Branch no permissions')),
2788 ('branch.merge', _('Branch access by web merge')),
2788 ('branch.merge', _('Branch access by web merge')),
2789 ('branch.push', _('Branch access by push')),
2789 ('branch.push', _('Branch access by push')),
2790 ('branch.push_force', _('Branch access by push with force')),
2790 ('branch.push_force', _('Branch access by push with force')),
2791
2791
2792 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2792 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2793 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2793 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2794
2794
2795 ('hg.usergroup.create.false', _('User Group creation disabled')),
2795 ('hg.usergroup.create.false', _('User Group creation disabled')),
2796 ('hg.usergroup.create.true', _('User Group creation enabled')),
2796 ('hg.usergroup.create.true', _('User Group creation enabled')),
2797
2797
2798 ('hg.create.none', _('Repository creation disabled')),
2798 ('hg.create.none', _('Repository creation disabled')),
2799 ('hg.create.repository', _('Repository creation enabled')),
2799 ('hg.create.repository', _('Repository creation enabled')),
2800 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2800 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2801 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2801 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2802
2802
2803 ('hg.fork.none', _('Repository forking disabled')),
2803 ('hg.fork.none', _('Repository forking disabled')),
2804 ('hg.fork.repository', _('Repository forking enabled')),
2804 ('hg.fork.repository', _('Repository forking enabled')),
2805
2805
2806 ('hg.register.none', _('Registration disabled')),
2806 ('hg.register.none', _('Registration disabled')),
2807 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2807 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2808 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2808 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2809
2809
2810 ('hg.password_reset.enabled', _('Password reset enabled')),
2810 ('hg.password_reset.enabled', _('Password reset enabled')),
2811 ('hg.password_reset.hidden', _('Password reset hidden')),
2811 ('hg.password_reset.hidden', _('Password reset hidden')),
2812 ('hg.password_reset.disabled', _('Password reset disabled')),
2812 ('hg.password_reset.disabled', _('Password reset disabled')),
2813
2813
2814 ('hg.extern_activate.manual', _('Manual activation of external account')),
2814 ('hg.extern_activate.manual', _('Manual activation of external account')),
2815 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2815 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2816
2816
2817 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2817 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2818 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2818 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2819 ]
2819 ]
2820
2820
2821 # definition of system default permissions for DEFAULT user, created on
2821 # definition of system default permissions for DEFAULT user, created on
2822 # system setup
2822 # system setup
2823 DEFAULT_USER_PERMISSIONS = [
2823 DEFAULT_USER_PERMISSIONS = [
2824 # object perms
2824 # object perms
2825 'repository.read',
2825 'repository.read',
2826 'group.read',
2826 'group.read',
2827 'usergroup.read',
2827 'usergroup.read',
2828 # branch, for backward compat we need same value as before so forced pushed
2828 # branch, for backward compat we need same value as before so forced pushed
2829 'branch.push_force',
2829 'branch.push_force',
2830 # global
2830 # global
2831 'hg.create.repository',
2831 'hg.create.repository',
2832 'hg.repogroup.create.false',
2832 'hg.repogroup.create.false',
2833 'hg.usergroup.create.false',
2833 'hg.usergroup.create.false',
2834 'hg.create.write_on_repogroup.true',
2834 'hg.create.write_on_repogroup.true',
2835 'hg.fork.repository',
2835 'hg.fork.repository',
2836 'hg.register.manual_activate',
2836 'hg.register.manual_activate',
2837 'hg.password_reset.enabled',
2837 'hg.password_reset.enabled',
2838 'hg.extern_activate.auto',
2838 'hg.extern_activate.auto',
2839 'hg.inherit_default_perms.true',
2839 'hg.inherit_default_perms.true',
2840 ]
2840 ]
2841
2841
2842 # defines which permissions are more important higher the more important
2842 # defines which permissions are more important higher the more important
2843 # Weight defines which permissions are more important.
2843 # Weight defines which permissions are more important.
2844 # The higher number the more important.
2844 # The higher number the more important.
2845 PERM_WEIGHTS = {
2845 PERM_WEIGHTS = {
2846 'repository.none': 0,
2846 'repository.none': 0,
2847 'repository.read': 1,
2847 'repository.read': 1,
2848 'repository.write': 3,
2848 'repository.write': 3,
2849 'repository.admin': 4,
2849 'repository.admin': 4,
2850
2850
2851 'group.none': 0,
2851 'group.none': 0,
2852 'group.read': 1,
2852 'group.read': 1,
2853 'group.write': 3,
2853 'group.write': 3,
2854 'group.admin': 4,
2854 'group.admin': 4,
2855
2855
2856 'usergroup.none': 0,
2856 'usergroup.none': 0,
2857 'usergroup.read': 1,
2857 'usergroup.read': 1,
2858 'usergroup.write': 3,
2858 'usergroup.write': 3,
2859 'usergroup.admin': 4,
2859 'usergroup.admin': 4,
2860
2860
2861 'branch.none': 0,
2861 'branch.none': 0,
2862 'branch.merge': 1,
2862 'branch.merge': 1,
2863 'branch.push': 3,
2863 'branch.push': 3,
2864 'branch.push_force': 4,
2864 'branch.push_force': 4,
2865
2865
2866 'hg.repogroup.create.false': 0,
2866 'hg.repogroup.create.false': 0,
2867 'hg.repogroup.create.true': 1,
2867 'hg.repogroup.create.true': 1,
2868
2868
2869 'hg.usergroup.create.false': 0,
2869 'hg.usergroup.create.false': 0,
2870 'hg.usergroup.create.true': 1,
2870 'hg.usergroup.create.true': 1,
2871
2871
2872 'hg.fork.none': 0,
2872 'hg.fork.none': 0,
2873 'hg.fork.repository': 1,
2873 'hg.fork.repository': 1,
2874 'hg.create.none': 0,
2874 'hg.create.none': 0,
2875 'hg.create.repository': 1
2875 'hg.create.repository': 1
2876 }
2876 }
2877
2877
2878 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2878 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2879 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2879 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2880 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2880 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2881
2881
2882 def __unicode__(self):
2882 def __unicode__(self):
2883 return u"<%s('%s:%s')>" % (
2883 return u"<%s('%s:%s')>" % (
2884 self.__class__.__name__, self.permission_id, self.permission_name
2884 self.__class__.__name__, self.permission_id, self.permission_name
2885 )
2885 )
2886
2886
2887 @classmethod
2887 @classmethod
2888 def get_by_key(cls, key):
2888 def get_by_key(cls, key):
2889 return cls.query().filter(cls.permission_name == key).scalar()
2889 return cls.query().filter(cls.permission_name == key).scalar()
2890
2890
2891 @classmethod
2891 @classmethod
2892 def get_default_repo_perms(cls, user_id, repo_id=None):
2892 def get_default_repo_perms(cls, user_id, repo_id=None):
2893 q = Session().query(UserRepoToPerm, Repository, Permission)\
2893 q = Session().query(UserRepoToPerm, Repository, Permission)\
2894 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2894 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2895 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2895 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2896 .filter(UserRepoToPerm.user_id == user_id)
2896 .filter(UserRepoToPerm.user_id == user_id)
2897 if repo_id:
2897 if repo_id:
2898 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2898 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2899 return q.all()
2899 return q.all()
2900
2900
2901 @classmethod
2901 @classmethod
2902 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2902 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2903 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2903 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2904 .join(
2904 .join(
2905 Permission,
2905 Permission,
2906 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2906 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2907 .join(
2907 .join(
2908 UserRepoToPerm,
2908 UserRepoToPerm,
2909 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2909 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2910 .filter(UserRepoToPerm.user_id == user_id)
2910 .filter(UserRepoToPerm.user_id == user_id)
2911
2911
2912 if repo_id:
2912 if repo_id:
2913 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2913 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2914 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2914 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2915
2915
2916 @classmethod
2916 @classmethod
2917 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2917 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2918 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2918 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2919 .join(
2919 .join(
2920 Permission,
2920 Permission,
2921 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2921 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2922 .join(
2922 .join(
2923 Repository,
2923 Repository,
2924 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2924 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2925 .join(
2925 .join(
2926 UserGroup,
2926 UserGroup,
2927 UserGroupRepoToPerm.users_group_id ==
2927 UserGroupRepoToPerm.users_group_id ==
2928 UserGroup.users_group_id)\
2928 UserGroup.users_group_id)\
2929 .join(
2929 .join(
2930 UserGroupMember,
2930 UserGroupMember,
2931 UserGroupRepoToPerm.users_group_id ==
2931 UserGroupRepoToPerm.users_group_id ==
2932 UserGroupMember.users_group_id)\
2932 UserGroupMember.users_group_id)\
2933 .filter(
2933 .filter(
2934 UserGroupMember.user_id == user_id,
2934 UserGroupMember.user_id == user_id,
2935 UserGroup.users_group_active == true())
2935 UserGroup.users_group_active == true())
2936 if repo_id:
2936 if repo_id:
2937 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2937 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2938 return q.all()
2938 return q.all()
2939
2939
2940 @classmethod
2940 @classmethod
2941 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2941 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2942 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2942 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2943 .join(
2943 .join(
2944 Permission,
2944 Permission,
2945 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2945 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2946 .join(
2946 .join(
2947 UserGroupRepoToPerm,
2947 UserGroupRepoToPerm,
2948 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2948 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2949 .join(
2949 .join(
2950 UserGroup,
2950 UserGroup,
2951 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2951 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2952 .join(
2952 .join(
2953 UserGroupMember,
2953 UserGroupMember,
2954 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2954 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2955 .filter(
2955 .filter(
2956 UserGroupMember.user_id == user_id,
2956 UserGroupMember.user_id == user_id,
2957 UserGroup.users_group_active == true())
2957 UserGroup.users_group_active == true())
2958
2958
2959 if repo_id:
2959 if repo_id:
2960 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2960 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2961 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2961 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2962
2962
2963 @classmethod
2963 @classmethod
2964 def get_default_group_perms(cls, user_id, repo_group_id=None):
2964 def get_default_group_perms(cls, user_id, repo_group_id=None):
2965 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2965 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2966 .join(
2966 .join(
2967 Permission,
2967 Permission,
2968 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2968 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2969 .join(
2969 .join(
2970 RepoGroup,
2970 RepoGroup,
2971 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2971 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2972 .filter(UserRepoGroupToPerm.user_id == user_id)
2972 .filter(UserRepoGroupToPerm.user_id == user_id)
2973 if repo_group_id:
2973 if repo_group_id:
2974 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2974 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2975 return q.all()
2975 return q.all()
2976
2976
2977 @classmethod
2977 @classmethod
2978 def get_default_group_perms_from_user_group(
2978 def get_default_group_perms_from_user_group(
2979 cls, user_id, repo_group_id=None):
2979 cls, user_id, repo_group_id=None):
2980 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2980 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2981 .join(
2981 .join(
2982 Permission,
2982 Permission,
2983 UserGroupRepoGroupToPerm.permission_id ==
2983 UserGroupRepoGroupToPerm.permission_id ==
2984 Permission.permission_id)\
2984 Permission.permission_id)\
2985 .join(
2985 .join(
2986 RepoGroup,
2986 RepoGroup,
2987 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2987 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2988 .join(
2988 .join(
2989 UserGroup,
2989 UserGroup,
2990 UserGroupRepoGroupToPerm.users_group_id ==
2990 UserGroupRepoGroupToPerm.users_group_id ==
2991 UserGroup.users_group_id)\
2991 UserGroup.users_group_id)\
2992 .join(
2992 .join(
2993 UserGroupMember,
2993 UserGroupMember,
2994 UserGroupRepoGroupToPerm.users_group_id ==
2994 UserGroupRepoGroupToPerm.users_group_id ==
2995 UserGroupMember.users_group_id)\
2995 UserGroupMember.users_group_id)\
2996 .filter(
2996 .filter(
2997 UserGroupMember.user_id == user_id,
2997 UserGroupMember.user_id == user_id,
2998 UserGroup.users_group_active == true())
2998 UserGroup.users_group_active == true())
2999 if repo_group_id:
2999 if repo_group_id:
3000 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3000 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3001 return q.all()
3001 return q.all()
3002
3002
3003 @classmethod
3003 @classmethod
3004 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3004 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3005 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3005 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3006 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3006 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3007 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3007 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3008 .filter(UserUserGroupToPerm.user_id == user_id)
3008 .filter(UserUserGroupToPerm.user_id == user_id)
3009 if user_group_id:
3009 if user_group_id:
3010 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3010 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3011 return q.all()
3011 return q.all()
3012
3012
3013 @classmethod
3013 @classmethod
3014 def get_default_user_group_perms_from_user_group(
3014 def get_default_user_group_perms_from_user_group(
3015 cls, user_id, user_group_id=None):
3015 cls, user_id, user_group_id=None):
3016 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3016 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3017 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3017 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3018 .join(
3018 .join(
3019 Permission,
3019 Permission,
3020 UserGroupUserGroupToPerm.permission_id ==
3020 UserGroupUserGroupToPerm.permission_id ==
3021 Permission.permission_id)\
3021 Permission.permission_id)\
3022 .join(
3022 .join(
3023 TargetUserGroup,
3023 TargetUserGroup,
3024 UserGroupUserGroupToPerm.target_user_group_id ==
3024 UserGroupUserGroupToPerm.target_user_group_id ==
3025 TargetUserGroup.users_group_id)\
3025 TargetUserGroup.users_group_id)\
3026 .join(
3026 .join(
3027 UserGroup,
3027 UserGroup,
3028 UserGroupUserGroupToPerm.user_group_id ==
3028 UserGroupUserGroupToPerm.user_group_id ==
3029 UserGroup.users_group_id)\
3029 UserGroup.users_group_id)\
3030 .join(
3030 .join(
3031 UserGroupMember,
3031 UserGroupMember,
3032 UserGroupUserGroupToPerm.user_group_id ==
3032 UserGroupUserGroupToPerm.user_group_id ==
3033 UserGroupMember.users_group_id)\
3033 UserGroupMember.users_group_id)\
3034 .filter(
3034 .filter(
3035 UserGroupMember.user_id == user_id,
3035 UserGroupMember.user_id == user_id,
3036 UserGroup.users_group_active == true())
3036 UserGroup.users_group_active == true())
3037 if user_group_id:
3037 if user_group_id:
3038 q = q.filter(
3038 q = q.filter(
3039 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3039 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3040
3040
3041 return q.all()
3041 return q.all()
3042
3042
3043
3043
3044 class UserRepoToPerm(Base, BaseModel):
3044 class UserRepoToPerm(Base, BaseModel):
3045 __tablename__ = 'repo_to_perm'
3045 __tablename__ = 'repo_to_perm'
3046 __table_args__ = (
3046 __table_args__ = (
3047 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3047 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3048 base_table_args
3048 base_table_args
3049 )
3049 )
3050
3050
3051 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3051 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3052 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3052 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3053 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3053 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3054 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3054 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3055
3055
3056 user = relationship('User')
3056 user = relationship('User')
3057 repository = relationship('Repository')
3057 repository = relationship('Repository')
3058 permission = relationship('Permission')
3058 permission = relationship('Permission')
3059
3059
3060 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3060 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3061
3061
3062 @classmethod
3062 @classmethod
3063 def create(cls, user, repository, permission):
3063 def create(cls, user, repository, permission):
3064 n = cls()
3064 n = cls()
3065 n.user = user
3065 n.user = user
3066 n.repository = repository
3066 n.repository = repository
3067 n.permission = permission
3067 n.permission = permission
3068 Session().add(n)
3068 Session().add(n)
3069 return n
3069 return n
3070
3070
3071 def __unicode__(self):
3071 def __unicode__(self):
3072 return u'<%s => %s >' % (self.user, self.repository)
3072 return u'<%s => %s >' % (self.user, self.repository)
3073
3073
3074
3074
3075 class UserUserGroupToPerm(Base, BaseModel):
3075 class UserUserGroupToPerm(Base, BaseModel):
3076 __tablename__ = 'user_user_group_to_perm'
3076 __tablename__ = 'user_user_group_to_perm'
3077 __table_args__ = (
3077 __table_args__ = (
3078 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3078 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3079 base_table_args
3079 base_table_args
3080 )
3080 )
3081
3081
3082 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3082 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3083 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3083 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3084 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3084 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3085 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3085 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3086
3086
3087 user = relationship('User')
3087 user = relationship('User')
3088 user_group = relationship('UserGroup')
3088 user_group = relationship('UserGroup')
3089 permission = relationship('Permission')
3089 permission = relationship('Permission')
3090
3090
3091 @classmethod
3091 @classmethod
3092 def create(cls, user, user_group, permission):
3092 def create(cls, user, user_group, permission):
3093 n = cls()
3093 n = cls()
3094 n.user = user
3094 n.user = user
3095 n.user_group = user_group
3095 n.user_group = user_group
3096 n.permission = permission
3096 n.permission = permission
3097 Session().add(n)
3097 Session().add(n)
3098 return n
3098 return n
3099
3099
3100 def __unicode__(self):
3100 def __unicode__(self):
3101 return u'<%s => %s >' % (self.user, self.user_group)
3101 return u'<%s => %s >' % (self.user, self.user_group)
3102
3102
3103
3103
3104 class UserToPerm(Base, BaseModel):
3104 class UserToPerm(Base, BaseModel):
3105 __tablename__ = 'user_to_perm'
3105 __tablename__ = 'user_to_perm'
3106 __table_args__ = (
3106 __table_args__ = (
3107 UniqueConstraint('user_id', 'permission_id'),
3107 UniqueConstraint('user_id', 'permission_id'),
3108 base_table_args
3108 base_table_args
3109 )
3109 )
3110
3110
3111 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3111 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3112 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3112 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3113 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3113 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3114
3114
3115 user = relationship('User')
3115 user = relationship('User')
3116 permission = relationship('Permission', lazy='joined')
3116 permission = relationship('Permission', lazy='joined')
3117
3117
3118 def __unicode__(self):
3118 def __unicode__(self):
3119 return u'<%s => %s >' % (self.user, self.permission)
3119 return u'<%s => %s >' % (self.user, self.permission)
3120
3120
3121
3121
3122 class UserGroupRepoToPerm(Base, BaseModel):
3122 class UserGroupRepoToPerm(Base, BaseModel):
3123 __tablename__ = 'users_group_repo_to_perm'
3123 __tablename__ = 'users_group_repo_to_perm'
3124 __table_args__ = (
3124 __table_args__ = (
3125 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3125 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3126 base_table_args
3126 base_table_args
3127 )
3127 )
3128
3128
3129 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3129 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3130 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3130 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3131 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3131 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3132 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3132 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3133
3133
3134 users_group = relationship('UserGroup')
3134 users_group = relationship('UserGroup')
3135 permission = relationship('Permission')
3135 permission = relationship('Permission')
3136 repository = relationship('Repository')
3136 repository = relationship('Repository')
3137 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3137 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3138
3138
3139 @classmethod
3139 @classmethod
3140 def create(cls, users_group, repository, permission):
3140 def create(cls, users_group, repository, permission):
3141 n = cls()
3141 n = cls()
3142 n.users_group = users_group
3142 n.users_group = users_group
3143 n.repository = repository
3143 n.repository = repository
3144 n.permission = permission
3144 n.permission = permission
3145 Session().add(n)
3145 Session().add(n)
3146 return n
3146 return n
3147
3147
3148 def __unicode__(self):
3148 def __unicode__(self):
3149 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3149 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3150
3150
3151
3151
3152 class UserGroupUserGroupToPerm(Base, BaseModel):
3152 class UserGroupUserGroupToPerm(Base, BaseModel):
3153 __tablename__ = 'user_group_user_group_to_perm'
3153 __tablename__ = 'user_group_user_group_to_perm'
3154 __table_args__ = (
3154 __table_args__ = (
3155 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3155 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3156 CheckConstraint('target_user_group_id != user_group_id'),
3156 CheckConstraint('target_user_group_id != user_group_id'),
3157 base_table_args
3157 base_table_args
3158 )
3158 )
3159
3159
3160 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)
3160 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3161 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3161 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3162 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3162 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3163 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3163 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3164
3164
3165 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3165 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3166 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3166 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3167 permission = relationship('Permission')
3167 permission = relationship('Permission')
3168
3168
3169 @classmethod
3169 @classmethod
3170 def create(cls, target_user_group, user_group, permission):
3170 def create(cls, target_user_group, user_group, permission):
3171 n = cls()
3171 n = cls()
3172 n.target_user_group = target_user_group
3172 n.target_user_group = target_user_group
3173 n.user_group = user_group
3173 n.user_group = user_group
3174 n.permission = permission
3174 n.permission = permission
3175 Session().add(n)
3175 Session().add(n)
3176 return n
3176 return n
3177
3177
3178 def __unicode__(self):
3178 def __unicode__(self):
3179 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3179 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3180
3180
3181
3181
3182 class UserGroupToPerm(Base, BaseModel):
3182 class UserGroupToPerm(Base, BaseModel):
3183 __tablename__ = 'users_group_to_perm'
3183 __tablename__ = 'users_group_to_perm'
3184 __table_args__ = (
3184 __table_args__ = (
3185 UniqueConstraint('users_group_id', 'permission_id',),
3185 UniqueConstraint('users_group_id', 'permission_id',),
3186 base_table_args
3186 base_table_args
3187 )
3187 )
3188
3188
3189 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3189 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3190 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3190 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3191 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3191 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3192
3192
3193 users_group = relationship('UserGroup')
3193 users_group = relationship('UserGroup')
3194 permission = relationship('Permission')
3194 permission = relationship('Permission')
3195
3195
3196
3196
3197 class UserRepoGroupToPerm(Base, BaseModel):
3197 class UserRepoGroupToPerm(Base, BaseModel):
3198 __tablename__ = 'user_repo_group_to_perm'
3198 __tablename__ = 'user_repo_group_to_perm'
3199 __table_args__ = (
3199 __table_args__ = (
3200 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3200 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3201 base_table_args
3201 base_table_args
3202 )
3202 )
3203
3203
3204 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3204 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3205 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3205 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3206 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3206 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3207 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3207 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3208
3208
3209 user = relationship('User')
3209 user = relationship('User')
3210 group = relationship('RepoGroup')
3210 group = relationship('RepoGroup')
3211 permission = relationship('Permission')
3211 permission = relationship('Permission')
3212
3212
3213 @classmethod
3213 @classmethod
3214 def create(cls, user, repository_group, permission):
3214 def create(cls, user, repository_group, permission):
3215 n = cls()
3215 n = cls()
3216 n.user = user
3216 n.user = user
3217 n.group = repository_group
3217 n.group = repository_group
3218 n.permission = permission
3218 n.permission = permission
3219 Session().add(n)
3219 Session().add(n)
3220 return n
3220 return n
3221
3221
3222
3222
3223 class UserGroupRepoGroupToPerm(Base, BaseModel):
3223 class UserGroupRepoGroupToPerm(Base, BaseModel):
3224 __tablename__ = 'users_group_repo_group_to_perm'
3224 __tablename__ = 'users_group_repo_group_to_perm'
3225 __table_args__ = (
3225 __table_args__ = (
3226 UniqueConstraint('users_group_id', 'group_id'),
3226 UniqueConstraint('users_group_id', 'group_id'),
3227 base_table_args
3227 base_table_args
3228 )
3228 )
3229
3229
3230 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)
3230 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3231 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3231 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3232 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3232 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3233 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3233 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3234
3234
3235 users_group = relationship('UserGroup')
3235 users_group = relationship('UserGroup')
3236 permission = relationship('Permission')
3236 permission = relationship('Permission')
3237 group = relationship('RepoGroup')
3237 group = relationship('RepoGroup')
3238
3238
3239 @classmethod
3239 @classmethod
3240 def create(cls, user_group, repository_group, permission):
3240 def create(cls, user_group, repository_group, permission):
3241 n = cls()
3241 n = cls()
3242 n.users_group = user_group
3242 n.users_group = user_group
3243 n.group = repository_group
3243 n.group = repository_group
3244 n.permission = permission
3244 n.permission = permission
3245 Session().add(n)
3245 Session().add(n)
3246 return n
3246 return n
3247
3247
3248 def __unicode__(self):
3248 def __unicode__(self):
3249 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3249 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3250
3250
3251
3251
3252 class Statistics(Base, BaseModel):
3252 class Statistics(Base, BaseModel):
3253 __tablename__ = 'statistics'
3253 __tablename__ = 'statistics'
3254 __table_args__ = (
3254 __table_args__ = (
3255 base_table_args
3255 base_table_args
3256 )
3256 )
3257
3257
3258 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3258 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3259 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3259 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3260 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3260 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3261 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3261 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3262 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3262 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3263 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3263 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3264
3264
3265 repository = relationship('Repository', single_parent=True)
3265 repository = relationship('Repository', single_parent=True)
3266
3266
3267
3267
3268 class UserFollowing(Base, BaseModel):
3268 class UserFollowing(Base, BaseModel):
3269 __tablename__ = 'user_followings'
3269 __tablename__ = 'user_followings'
3270 __table_args__ = (
3270 __table_args__ = (
3271 UniqueConstraint('user_id', 'follows_repository_id'),
3271 UniqueConstraint('user_id', 'follows_repository_id'),
3272 UniqueConstraint('user_id', 'follows_user_id'),
3272 UniqueConstraint('user_id', 'follows_user_id'),
3273 base_table_args
3273 base_table_args
3274 )
3274 )
3275
3275
3276 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3276 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3277 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3277 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3278 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3278 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3279 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3279 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3280 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3280 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3281
3281
3282 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3282 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3283
3283
3284 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3284 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3285 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3285 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3286
3286
3287 @classmethod
3287 @classmethod
3288 def get_repo_followers(cls, repo_id):
3288 def get_repo_followers(cls, repo_id):
3289 return cls.query().filter(cls.follows_repo_id == repo_id)
3289 return cls.query().filter(cls.follows_repo_id == repo_id)
3290
3290
3291
3291
3292 class CacheKey(Base, BaseModel):
3292 class CacheKey(Base, BaseModel):
3293 __tablename__ = 'cache_invalidation'
3293 __tablename__ = 'cache_invalidation'
3294 __table_args__ = (
3294 __table_args__ = (
3295 UniqueConstraint('cache_key'),
3295 UniqueConstraint('cache_key'),
3296 Index('key_idx', 'cache_key'),
3296 Index('key_idx', 'cache_key'),
3297 base_table_args,
3297 base_table_args,
3298 )
3298 )
3299
3299
3300 CACHE_TYPE_FEED = 'FEED'
3300 CACHE_TYPE_FEED = 'FEED'
3301 CACHE_TYPE_README = 'README'
3301 CACHE_TYPE_README = 'README'
3302 # namespaces used to register process/thread aware caches
3302 # namespaces used to register process/thread aware caches
3303 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3303 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3304 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3304 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3305
3305
3306 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3306 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3307 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3307 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3308 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3308 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3309 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3309 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3310
3310
3311 def __init__(self, cache_key, cache_args=''):
3311 def __init__(self, cache_key, cache_args=''):
3312 self.cache_key = cache_key
3312 self.cache_key = cache_key
3313 self.cache_args = cache_args
3313 self.cache_args = cache_args
3314 self.cache_active = False
3314 self.cache_active = False
3315
3315
3316 def __unicode__(self):
3316 def __unicode__(self):
3317 return u"<%s('%s:%s[%s]')>" % (
3317 return u"<%s('%s:%s[%s]')>" % (
3318 self.__class__.__name__,
3318 self.__class__.__name__,
3319 self.cache_id, self.cache_key, self.cache_active)
3319 self.cache_id, self.cache_key, self.cache_active)
3320
3320
3321 def _cache_key_partition(self):
3321 def _cache_key_partition(self):
3322 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3322 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3323 return prefix, repo_name, suffix
3323 return prefix, repo_name, suffix
3324
3324
3325 def get_prefix(self):
3325 def get_prefix(self):
3326 """
3326 """
3327 Try to extract prefix from existing cache key. The key could consist
3327 Try to extract prefix from existing cache key. The key could consist
3328 of prefix, repo_name, suffix
3328 of prefix, repo_name, suffix
3329 """
3329 """
3330 # this returns prefix, repo_name, suffix
3330 # this returns prefix, repo_name, suffix
3331 return self._cache_key_partition()[0]
3331 return self._cache_key_partition()[0]
3332
3332
3333 def get_suffix(self):
3333 def get_suffix(self):
3334 """
3334 """
3335 get suffix that might have been used in _get_cache_key to
3335 get suffix that might have been used in _get_cache_key to
3336 generate self.cache_key. Only used for informational purposes
3336 generate self.cache_key. Only used for informational purposes
3337 in repo_edit.mako.
3337 in repo_edit.mako.
3338 """
3338 """
3339 # prefix, repo_name, suffix
3339 # prefix, repo_name, suffix
3340 return self._cache_key_partition()[2]
3340 return self._cache_key_partition()[2]
3341
3341
3342 @classmethod
3342 @classmethod
3343 def delete_all_cache(cls):
3343 def delete_all_cache(cls):
3344 """
3344 """
3345 Delete all cache keys from database.
3345 Delete all cache keys from database.
3346 Should only be run when all instances are down and all entries
3346 Should only be run when all instances are down and all entries
3347 thus stale.
3347 thus stale.
3348 """
3348 """
3349 cls.query().delete()
3349 cls.query().delete()
3350 Session().commit()
3350 Session().commit()
3351
3351
3352 @classmethod
3352 @classmethod
3353 def set_invalidate(cls, cache_uid, delete=False):
3353 def set_invalidate(cls, cache_uid, delete=False):
3354 """
3354 """
3355 Mark all caches of a repo as invalid in the database.
3355 Mark all caches of a repo as invalid in the database.
3356 """
3356 """
3357
3357
3358 try:
3358 try:
3359 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3359 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3360 if delete:
3360 if delete:
3361 qry.delete()
3361 qry.delete()
3362 log.debug('cache objects deleted for cache args %s',
3362 log.debug('cache objects deleted for cache args %s',
3363 safe_str(cache_uid))
3363 safe_str(cache_uid))
3364 else:
3364 else:
3365 qry.update({"cache_active": False})
3365 qry.update({"cache_active": False})
3366 log.debug('cache objects marked as invalid for cache args %s',
3366 log.debug('cache objects marked as invalid for cache args %s',
3367 safe_str(cache_uid))
3367 safe_str(cache_uid))
3368
3368
3369 Session().commit()
3369 Session().commit()
3370 except Exception:
3370 except Exception:
3371 log.exception(
3371 log.exception(
3372 'Cache key invalidation failed for cache args %s',
3372 'Cache key invalidation failed for cache args %s',
3373 safe_str(cache_uid))
3373 safe_str(cache_uid))
3374 Session().rollback()
3374 Session().rollback()
3375
3375
3376 @classmethod
3376 @classmethod
3377 def get_active_cache(cls, cache_key):
3377 def get_active_cache(cls, cache_key):
3378 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3378 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3379 if inv_obj:
3379 if inv_obj:
3380 return inv_obj
3380 return inv_obj
3381 return None
3381 return None
3382
3382
3383
3383
3384 class ChangesetComment(Base, BaseModel):
3384 class ChangesetComment(Base, BaseModel):
3385 __tablename__ = 'changeset_comments'
3385 __tablename__ = 'changeset_comments'
3386 __table_args__ = (
3386 __table_args__ = (
3387 Index('cc_revision_idx', 'revision'),
3387 Index('cc_revision_idx', 'revision'),
3388 base_table_args,
3388 base_table_args,
3389 )
3389 )
3390
3390
3391 COMMENT_OUTDATED = u'comment_outdated'
3391 COMMENT_OUTDATED = u'comment_outdated'
3392 COMMENT_TYPE_NOTE = u'note'
3392 COMMENT_TYPE_NOTE = u'note'
3393 COMMENT_TYPE_TODO = u'todo'
3393 COMMENT_TYPE_TODO = u'todo'
3394 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3394 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3395
3395
3396 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3396 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3397 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3397 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3398 revision = Column('revision', String(40), nullable=True)
3398 revision = Column('revision', String(40), nullable=True)
3399 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3399 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3400 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3400 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3401 line_no = Column('line_no', Unicode(10), nullable=True)
3401 line_no = Column('line_no', Unicode(10), nullable=True)
3402 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3402 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3403 f_path = Column('f_path', Unicode(1000), nullable=True)
3403 f_path = Column('f_path', Unicode(1000), nullable=True)
3404 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3404 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3405 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3405 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3406 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3406 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3407 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3407 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3408 renderer = Column('renderer', Unicode(64), nullable=True)
3408 renderer = Column('renderer', Unicode(64), nullable=True)
3409 display_state = Column('display_state', Unicode(128), nullable=True)
3409 display_state = Column('display_state', Unicode(128), nullable=True)
3410
3410
3411 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3411 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3412 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3412 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3413
3413
3414 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3414 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3415 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3415 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3416
3416
3417 author = relationship('User', lazy='joined')
3417 author = relationship('User', lazy='joined')
3418 repo = relationship('Repository')
3418 repo = relationship('Repository')
3419 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3419 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3420 pull_request = relationship('PullRequest', lazy='joined')
3420 pull_request = relationship('PullRequest', lazy='joined')
3421 pull_request_version = relationship('PullRequestVersion')
3421 pull_request_version = relationship('PullRequestVersion')
3422
3422
3423 @classmethod
3423 @classmethod
3424 def get_users(cls, revision=None, pull_request_id=None):
3424 def get_users(cls, revision=None, pull_request_id=None):
3425 """
3425 """
3426 Returns user associated with this ChangesetComment. ie those
3426 Returns user associated with this ChangesetComment. ie those
3427 who actually commented
3427 who actually commented
3428
3428
3429 :param cls:
3429 :param cls:
3430 :param revision:
3430 :param revision:
3431 """
3431 """
3432 q = Session().query(User)\
3432 q = Session().query(User)\
3433 .join(ChangesetComment.author)
3433 .join(ChangesetComment.author)
3434 if revision:
3434 if revision:
3435 q = q.filter(cls.revision == revision)
3435 q = q.filter(cls.revision == revision)
3436 elif pull_request_id:
3436 elif pull_request_id:
3437 q = q.filter(cls.pull_request_id == pull_request_id)
3437 q = q.filter(cls.pull_request_id == pull_request_id)
3438 return q.all()
3438 return q.all()
3439
3439
3440 @classmethod
3440 @classmethod
3441 def get_index_from_version(cls, pr_version, versions):
3441 def get_index_from_version(cls, pr_version, versions):
3442 num_versions = [x.pull_request_version_id for x in versions]
3442 num_versions = [x.pull_request_version_id for x in versions]
3443 try:
3443 try:
3444 return num_versions.index(pr_version) +1
3444 return num_versions.index(pr_version) +1
3445 except (IndexError, ValueError):
3445 except (IndexError, ValueError):
3446 return
3446 return
3447
3447
3448 @property
3448 @property
3449 def outdated(self):
3449 def outdated(self):
3450 return self.display_state == self.COMMENT_OUTDATED
3450 return self.display_state == self.COMMENT_OUTDATED
3451
3451
3452 def outdated_at_version(self, version):
3452 def outdated_at_version(self, version):
3453 """
3453 """
3454 Checks if comment is outdated for given pull request version
3454 Checks if comment is outdated for given pull request version
3455 """
3455 """
3456 return self.outdated and self.pull_request_version_id != version
3456 return self.outdated and self.pull_request_version_id != version
3457
3457
3458 def older_than_version(self, version):
3458 def older_than_version(self, version):
3459 """
3459 """
3460 Checks if comment is made from previous version than given
3460 Checks if comment is made from previous version than given
3461 """
3461 """
3462 if version is None:
3462 if version is None:
3463 return self.pull_request_version_id is not None
3463 return self.pull_request_version_id is not None
3464
3464
3465 return self.pull_request_version_id < version
3465 return self.pull_request_version_id < version
3466
3466
3467 @property
3467 @property
3468 def resolved(self):
3468 def resolved(self):
3469 return self.resolved_by[0] if self.resolved_by else None
3469 return self.resolved_by[0] if self.resolved_by else None
3470
3470
3471 @property
3471 @property
3472 def is_todo(self):
3472 def is_todo(self):
3473 return self.comment_type == self.COMMENT_TYPE_TODO
3473 return self.comment_type == self.COMMENT_TYPE_TODO
3474
3474
3475 @property
3475 @property
3476 def is_inline(self):
3476 def is_inline(self):
3477 return self.line_no and self.f_path
3477 return self.line_no and self.f_path
3478
3478
3479 def get_index_version(self, versions):
3479 def get_index_version(self, versions):
3480 return self.get_index_from_version(
3480 return self.get_index_from_version(
3481 self.pull_request_version_id, versions)
3481 self.pull_request_version_id, versions)
3482
3482
3483 def __repr__(self):
3483 def __repr__(self):
3484 if self.comment_id:
3484 if self.comment_id:
3485 return '<DB:Comment #%s>' % self.comment_id
3485 return '<DB:Comment #%s>' % self.comment_id
3486 else:
3486 else:
3487 return '<DB:Comment at %#x>' % id(self)
3487 return '<DB:Comment at %#x>' % id(self)
3488
3488
3489 def get_api_data(self):
3489 def get_api_data(self):
3490 comment = self
3490 comment = self
3491 data = {
3491 data = {
3492 'comment_id': comment.comment_id,
3492 'comment_id': comment.comment_id,
3493 'comment_type': comment.comment_type,
3493 'comment_type': comment.comment_type,
3494 'comment_text': comment.text,
3494 'comment_text': comment.text,
3495 'comment_status': comment.status_change,
3495 'comment_status': comment.status_change,
3496 'comment_f_path': comment.f_path,
3496 'comment_f_path': comment.f_path,
3497 'comment_lineno': comment.line_no,
3497 'comment_lineno': comment.line_no,
3498 'comment_author': comment.author,
3498 'comment_author': comment.author,
3499 'comment_created_on': comment.created_on
3499 'comment_created_on': comment.created_on
3500 }
3500 }
3501 return data
3501 return data
3502
3502
3503 def __json__(self):
3503 def __json__(self):
3504 data = dict()
3504 data = dict()
3505 data.update(self.get_api_data())
3505 data.update(self.get_api_data())
3506 return data
3506 return data
3507
3507
3508
3508
3509 class ChangesetStatus(Base, BaseModel):
3509 class ChangesetStatus(Base, BaseModel):
3510 __tablename__ = 'changeset_statuses'
3510 __tablename__ = 'changeset_statuses'
3511 __table_args__ = (
3511 __table_args__ = (
3512 Index('cs_revision_idx', 'revision'),
3512 Index('cs_revision_idx', 'revision'),
3513 Index('cs_version_idx', 'version'),
3513 Index('cs_version_idx', 'version'),
3514 UniqueConstraint('repo_id', 'revision', 'version'),
3514 UniqueConstraint('repo_id', 'revision', 'version'),
3515 base_table_args
3515 base_table_args
3516 )
3516 )
3517
3517
3518 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3518 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3519 STATUS_APPROVED = 'approved'
3519 STATUS_APPROVED = 'approved'
3520 STATUS_REJECTED = 'rejected'
3520 STATUS_REJECTED = 'rejected'
3521 STATUS_UNDER_REVIEW = 'under_review'
3521 STATUS_UNDER_REVIEW = 'under_review'
3522
3522
3523 STATUSES = [
3523 STATUSES = [
3524 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3524 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3525 (STATUS_APPROVED, _("Approved")),
3525 (STATUS_APPROVED, _("Approved")),
3526 (STATUS_REJECTED, _("Rejected")),
3526 (STATUS_REJECTED, _("Rejected")),
3527 (STATUS_UNDER_REVIEW, _("Under Review")),
3527 (STATUS_UNDER_REVIEW, _("Under Review")),
3528 ]
3528 ]
3529
3529
3530 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3530 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3531 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3531 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3532 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3532 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3533 revision = Column('revision', String(40), nullable=False)
3533 revision = Column('revision', String(40), nullable=False)
3534 status = Column('status', String(128), nullable=False, default=DEFAULT)
3534 status = Column('status', String(128), nullable=False, default=DEFAULT)
3535 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3535 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3536 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3536 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3537 version = Column('version', Integer(), nullable=False, default=0)
3537 version = Column('version', Integer(), nullable=False, default=0)
3538 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3538 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3539
3539
3540 author = relationship('User', lazy='joined')
3540 author = relationship('User', lazy='joined')
3541 repo = relationship('Repository')
3541 repo = relationship('Repository')
3542 comment = relationship('ChangesetComment', lazy='joined')
3542 comment = relationship('ChangesetComment', lazy='joined')
3543 pull_request = relationship('PullRequest', lazy='joined')
3543 pull_request = relationship('PullRequest', lazy='joined')
3544
3544
3545 def __unicode__(self):
3545 def __unicode__(self):
3546 return u"<%s('%s[v%s]:%s')>" % (
3546 return u"<%s('%s[v%s]:%s')>" % (
3547 self.__class__.__name__,
3547 self.__class__.__name__,
3548 self.status, self.version, self.author
3548 self.status, self.version, self.author
3549 )
3549 )
3550
3550
3551 @classmethod
3551 @classmethod
3552 def get_status_lbl(cls, value):
3552 def get_status_lbl(cls, value):
3553 return dict(cls.STATUSES).get(value)
3553 return dict(cls.STATUSES).get(value)
3554
3554
3555 @property
3555 @property
3556 def status_lbl(self):
3556 def status_lbl(self):
3557 return ChangesetStatus.get_status_lbl(self.status)
3557 return ChangesetStatus.get_status_lbl(self.status)
3558
3558
3559 def get_api_data(self):
3559 def get_api_data(self):
3560 status = self
3560 status = self
3561 data = {
3561 data = {
3562 'status_id': status.changeset_status_id,
3562 'status_id': status.changeset_status_id,
3563 'status': status.status,
3563 'status': status.status,
3564 }
3564 }
3565 return data
3565 return data
3566
3566
3567 def __json__(self):
3567 def __json__(self):
3568 data = dict()
3568 data = dict()
3569 data.update(self.get_api_data())
3569 data.update(self.get_api_data())
3570 return data
3570 return data
3571
3571
3572
3572
3573 class _SetState(object):
3573 class _SetState(object):
3574 """
3574 """
3575 Context processor allowing changing state for sensitive operation such as
3575 Context processor allowing changing state for sensitive operation such as
3576 pull request update or merge
3576 pull request update or merge
3577 """
3577 """
3578
3578
3579 def __init__(self, pull_request, pr_state, back_state=None):
3579 def __init__(self, pull_request, pr_state, back_state=None):
3580 self._pr = pull_request
3580 self._pr = pull_request
3581 self._org_state = back_state or pull_request.pull_request_state
3581 self._org_state = back_state or pull_request.pull_request_state
3582 self._pr_state = pr_state
3582 self._pr_state = pr_state
3583
3583
3584 def __enter__(self):
3584 def __enter__(self):
3585 log.debug('StateLock: entering set state context, setting state to: `%s`',
3585 log.debug('StateLock: entering set state context, setting state to: `%s`',
3586 self._pr_state)
3586 self._pr_state)
3587 self._pr.pull_request_state = self._pr_state
3587 self._pr.pull_request_state = self._pr_state
3588 Session().add(self._pr)
3588 Session().add(self._pr)
3589 Session().commit()
3589 Session().commit()
3590
3590
3591 def __exit__(self, exc_type, exc_val, exc_tb):
3591 def __exit__(self, exc_type, exc_val, exc_tb):
3592 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3592 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3593 self._org_state)
3593 self._org_state)
3594 self._pr.pull_request_state = self._org_state
3594 self._pr.pull_request_state = self._org_state
3595 Session().add(self._pr)
3595 Session().add(self._pr)
3596 Session().commit()
3596 Session().commit()
3597
3597
3598
3598
3599 class _PullRequestBase(BaseModel):
3599 class _PullRequestBase(BaseModel):
3600 """
3600 """
3601 Common attributes of pull request and version entries.
3601 Common attributes of pull request and version entries.
3602 """
3602 """
3603
3603
3604 # .status values
3604 # .status values
3605 STATUS_NEW = u'new'
3605 STATUS_NEW = u'new'
3606 STATUS_OPEN = u'open'
3606 STATUS_OPEN = u'open'
3607 STATUS_CLOSED = u'closed'
3607 STATUS_CLOSED = u'closed'
3608
3608
3609 # available states
3609 # available states
3610 STATE_CREATING = u'creating'
3610 STATE_CREATING = u'creating'
3611 STATE_UPDATING = u'updating'
3611 STATE_UPDATING = u'updating'
3612 STATE_MERGING = u'merging'
3612 STATE_MERGING = u'merging'
3613 STATE_CREATED = u'created'
3613 STATE_CREATED = u'created'
3614
3614
3615 title = Column('title', Unicode(255), nullable=True)
3615 title = Column('title', Unicode(255), nullable=True)
3616 description = Column(
3616 description = Column(
3617 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3617 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3618 nullable=True)
3618 nullable=True)
3619 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3619 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3620
3620
3621 # new/open/closed status of pull request (not approve/reject/etc)
3621 # new/open/closed status of pull request (not approve/reject/etc)
3622 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3622 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3623 created_on = Column(
3623 created_on = Column(
3624 'created_on', DateTime(timezone=False), nullable=False,
3624 'created_on', DateTime(timezone=False), nullable=False,
3625 default=datetime.datetime.now)
3625 default=datetime.datetime.now)
3626 updated_on = Column(
3626 updated_on = Column(
3627 'updated_on', DateTime(timezone=False), nullable=False,
3627 'updated_on', DateTime(timezone=False), nullable=False,
3628 default=datetime.datetime.now)
3628 default=datetime.datetime.now)
3629
3629
3630 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3630 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3631
3631
3632 @declared_attr
3632 @declared_attr
3633 def user_id(cls):
3633 def user_id(cls):
3634 return Column(
3634 return Column(
3635 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3635 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3636 unique=None)
3636 unique=None)
3637
3637
3638 # 500 revisions max
3638 # 500 revisions max
3639 _revisions = Column(
3639 _revisions = Column(
3640 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3640 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3641
3641
3642 @declared_attr
3642 @declared_attr
3643 def source_repo_id(cls):
3643 def source_repo_id(cls):
3644 # TODO: dan: rename column to source_repo_id
3644 # TODO: dan: rename column to source_repo_id
3645 return Column(
3645 return Column(
3646 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3646 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3647 nullable=False)
3647 nullable=False)
3648
3648
3649 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3649 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3650
3650
3651 @hybrid_property
3651 @hybrid_property
3652 def source_ref(self):
3652 def source_ref(self):
3653 return self._source_ref
3653 return self._source_ref
3654
3654
3655 @source_ref.setter
3655 @source_ref.setter
3656 def source_ref(self, val):
3656 def source_ref(self, val):
3657 parts = (val or '').split(':')
3657 parts = (val or '').split(':')
3658 if len(parts) != 3:
3658 if len(parts) != 3:
3659 raise ValueError(
3659 raise ValueError(
3660 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3660 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3661 self._source_ref = safe_unicode(val)
3661 self._source_ref = safe_unicode(val)
3662
3662
3663 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3663 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3664
3664
3665 @hybrid_property
3665 @hybrid_property
3666 def target_ref(self):
3666 def target_ref(self):
3667 return self._target_ref
3667 return self._target_ref
3668
3668
3669 @target_ref.setter
3669 @target_ref.setter
3670 def target_ref(self, val):
3670 def target_ref(self, val):
3671 parts = (val or '').split(':')
3671 parts = (val or '').split(':')
3672 if len(parts) != 3:
3672 if len(parts) != 3:
3673 raise ValueError(
3673 raise ValueError(
3674 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3674 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3675 self._target_ref = safe_unicode(val)
3675 self._target_ref = safe_unicode(val)
3676
3676
3677 @declared_attr
3677 @declared_attr
3678 def target_repo_id(cls):
3678 def target_repo_id(cls):
3679 # TODO: dan: rename column to target_repo_id
3679 # TODO: dan: rename column to target_repo_id
3680 return Column(
3680 return Column(
3681 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3681 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3682 nullable=False)
3682 nullable=False)
3683
3683
3684 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3684 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3685
3685
3686 # TODO: dan: rename column to last_merge_source_rev
3686 # TODO: dan: rename column to last_merge_source_rev
3687 _last_merge_source_rev = Column(
3687 _last_merge_source_rev = Column(
3688 'last_merge_org_rev', String(40), nullable=True)
3688 'last_merge_org_rev', String(40), nullable=True)
3689 # TODO: dan: rename column to last_merge_target_rev
3689 # TODO: dan: rename column to last_merge_target_rev
3690 _last_merge_target_rev = Column(
3690 _last_merge_target_rev = Column(
3691 'last_merge_other_rev', String(40), nullable=True)
3691 'last_merge_other_rev', String(40), nullable=True)
3692 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3692 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3693 merge_rev = Column('merge_rev', String(40), nullable=True)
3693 merge_rev = Column('merge_rev', String(40), nullable=True)
3694
3694
3695 reviewer_data = Column(
3695 reviewer_data = Column(
3696 'reviewer_data_json', MutationObj.as_mutable(
3696 'reviewer_data_json', MutationObj.as_mutable(
3697 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3697 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3698
3698
3699 @property
3699 @property
3700 def reviewer_data_json(self):
3700 def reviewer_data_json(self):
3701 return json.dumps(self.reviewer_data)
3701 return json.dumps(self.reviewer_data)
3702
3702
3703 @hybrid_property
3703 @hybrid_property
3704 def description_safe(self):
3704 def description_safe(self):
3705 from rhodecode.lib import helpers as h
3705 from rhodecode.lib import helpers as h
3706 return h.escape(self.description)
3706 return h.escape(self.description)
3707
3707
3708 @hybrid_property
3708 @hybrid_property
3709 def revisions(self):
3709 def revisions(self):
3710 return self._revisions.split(':') if self._revisions else []
3710 return self._revisions.split(':') if self._revisions else []
3711
3711
3712 @revisions.setter
3712 @revisions.setter
3713 def revisions(self, val):
3713 def revisions(self, val):
3714 self._revisions = ':'.join(val)
3714 self._revisions = ':'.join(val)
3715
3715
3716 @hybrid_property
3716 @hybrid_property
3717 def last_merge_status(self):
3717 def last_merge_status(self):
3718 return safe_int(self._last_merge_status)
3718 return safe_int(self._last_merge_status)
3719
3719
3720 @last_merge_status.setter
3720 @last_merge_status.setter
3721 def last_merge_status(self, val):
3721 def last_merge_status(self, val):
3722 self._last_merge_status = val
3722 self._last_merge_status = val
3723
3723
3724 @declared_attr
3724 @declared_attr
3725 def author(cls):
3725 def author(cls):
3726 return relationship('User', lazy='joined')
3726 return relationship('User', lazy='joined')
3727
3727
3728 @declared_attr
3728 @declared_attr
3729 def source_repo(cls):
3729 def source_repo(cls):
3730 return relationship(
3730 return relationship(
3731 'Repository',
3731 'Repository',
3732 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3732 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3733
3733
3734 @property
3734 @property
3735 def source_ref_parts(self):
3735 def source_ref_parts(self):
3736 return self.unicode_to_reference(self.source_ref)
3736 return self.unicode_to_reference(self.source_ref)
3737
3737
3738 @declared_attr
3738 @declared_attr
3739 def target_repo(cls):
3739 def target_repo(cls):
3740 return relationship(
3740 return relationship(
3741 'Repository',
3741 'Repository',
3742 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3742 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3743
3743
3744 @property
3744 @property
3745 def target_ref_parts(self):
3745 def target_ref_parts(self):
3746 return self.unicode_to_reference(self.target_ref)
3746 return self.unicode_to_reference(self.target_ref)
3747
3747
3748 @property
3748 @property
3749 def shadow_merge_ref(self):
3749 def shadow_merge_ref(self):
3750 return self.unicode_to_reference(self._shadow_merge_ref)
3750 return self.unicode_to_reference(self._shadow_merge_ref)
3751
3751
3752 @shadow_merge_ref.setter
3752 @shadow_merge_ref.setter
3753 def shadow_merge_ref(self, ref):
3753 def shadow_merge_ref(self, ref):
3754 self._shadow_merge_ref = self.reference_to_unicode(ref)
3754 self._shadow_merge_ref = self.reference_to_unicode(ref)
3755
3755
3756 @staticmethod
3756 @staticmethod
3757 def unicode_to_reference(raw):
3757 def unicode_to_reference(raw):
3758 """
3758 """
3759 Convert a unicode (or string) to a reference object.
3759 Convert a unicode (or string) to a reference object.
3760 If unicode evaluates to False it returns None.
3760 If unicode evaluates to False it returns None.
3761 """
3761 """
3762 if raw:
3762 if raw:
3763 refs = raw.split(':')
3763 refs = raw.split(':')
3764 return Reference(*refs)
3764 return Reference(*refs)
3765 else:
3765 else:
3766 return None
3766 return None
3767
3767
3768 @staticmethod
3768 @staticmethod
3769 def reference_to_unicode(ref):
3769 def reference_to_unicode(ref):
3770 """
3770 """
3771 Convert a reference object to unicode.
3771 Convert a reference object to unicode.
3772 If reference is None it returns None.
3772 If reference is None it returns None.
3773 """
3773 """
3774 if ref:
3774 if ref:
3775 return u':'.join(ref)
3775 return u':'.join(ref)
3776 else:
3776 else:
3777 return None
3777 return None
3778
3778
3779 def get_api_data(self, with_merge_state=True):
3779 def get_api_data(self, with_merge_state=True):
3780 from rhodecode.model.pull_request import PullRequestModel
3780 from rhodecode.model.pull_request import PullRequestModel
3781
3781
3782 pull_request = self
3782 pull_request = self
3783 if with_merge_state:
3783 if with_merge_state:
3784 merge_status = PullRequestModel().merge_status(pull_request)
3784 merge_status = PullRequestModel().merge_status(pull_request)
3785 merge_state = {
3785 merge_state = {
3786 'status': merge_status[0],
3786 'status': merge_status[0],
3787 'message': safe_unicode(merge_status[1]),
3787 'message': safe_unicode(merge_status[1]),
3788 }
3788 }
3789 else:
3789 else:
3790 merge_state = {'status': 'not_available',
3790 merge_state = {'status': 'not_available',
3791 'message': 'not_available'}
3791 'message': 'not_available'}
3792
3792
3793 merge_data = {
3793 merge_data = {
3794 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3794 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3795 'reference': (
3795 'reference': (
3796 pull_request.shadow_merge_ref._asdict()
3796 pull_request.shadow_merge_ref._asdict()
3797 if pull_request.shadow_merge_ref else None),
3797 if pull_request.shadow_merge_ref else None),
3798 }
3798 }
3799
3799
3800 data = {
3800 data = {
3801 'pull_request_id': pull_request.pull_request_id,
3801 'pull_request_id': pull_request.pull_request_id,
3802 'url': PullRequestModel().get_url(pull_request),
3802 'url': PullRequestModel().get_url(pull_request),
3803 'title': pull_request.title,
3803 'title': pull_request.title,
3804 'description': pull_request.description,
3804 'description': pull_request.description,
3805 'status': pull_request.status,
3805 'status': pull_request.status,
3806 'state': pull_request.pull_request_state,
3806 'state': pull_request.pull_request_state,
3807 'created_on': pull_request.created_on,
3807 'created_on': pull_request.created_on,
3808 'updated_on': pull_request.updated_on,
3808 'updated_on': pull_request.updated_on,
3809 'commit_ids': pull_request.revisions,
3809 'commit_ids': pull_request.revisions,
3810 'review_status': pull_request.calculated_review_status(),
3810 'review_status': pull_request.calculated_review_status(),
3811 'mergeable': merge_state,
3811 'mergeable': merge_state,
3812 'source': {
3812 'source': {
3813 'clone_url': pull_request.source_repo.clone_url(),
3813 'clone_url': pull_request.source_repo.clone_url(),
3814 'repository': pull_request.source_repo.repo_name,
3814 'repository': pull_request.source_repo.repo_name,
3815 'reference': {
3815 'reference': {
3816 'name': pull_request.source_ref_parts.name,
3816 'name': pull_request.source_ref_parts.name,
3817 'type': pull_request.source_ref_parts.type,
3817 'type': pull_request.source_ref_parts.type,
3818 'commit_id': pull_request.source_ref_parts.commit_id,
3818 'commit_id': pull_request.source_ref_parts.commit_id,
3819 },
3819 },
3820 },
3820 },
3821 'target': {
3821 'target': {
3822 'clone_url': pull_request.target_repo.clone_url(),
3822 'clone_url': pull_request.target_repo.clone_url(),
3823 'repository': pull_request.target_repo.repo_name,
3823 'repository': pull_request.target_repo.repo_name,
3824 'reference': {
3824 'reference': {
3825 'name': pull_request.target_ref_parts.name,
3825 'name': pull_request.target_ref_parts.name,
3826 'type': pull_request.target_ref_parts.type,
3826 'type': pull_request.target_ref_parts.type,
3827 'commit_id': pull_request.target_ref_parts.commit_id,
3827 'commit_id': pull_request.target_ref_parts.commit_id,
3828 },
3828 },
3829 },
3829 },
3830 'merge': merge_data,
3830 'merge': merge_data,
3831 'author': pull_request.author.get_api_data(include_secrets=False,
3831 'author': pull_request.author.get_api_data(include_secrets=False,
3832 details='basic'),
3832 details='basic'),
3833 'reviewers': [
3833 'reviewers': [
3834 {
3834 {
3835 'user': reviewer.get_api_data(include_secrets=False,
3835 'user': reviewer.get_api_data(include_secrets=False,
3836 details='basic'),
3836 details='basic'),
3837 'reasons': reasons,
3837 'reasons': reasons,
3838 'review_status': st[0][1].status if st else 'not_reviewed',
3838 'review_status': st[0][1].status if st else 'not_reviewed',
3839 }
3839 }
3840 for obj, reviewer, reasons, mandatory, st in
3840 for obj, reviewer, reasons, mandatory, st in
3841 pull_request.reviewers_statuses()
3841 pull_request.reviewers_statuses()
3842 ]
3842 ]
3843 }
3843 }
3844
3844
3845 return data
3845 return data
3846
3846
3847 def set_state(self, pull_request_state, final_state=None):
3847 def set_state(self, pull_request_state, final_state=None):
3848 """
3848 """
3849 # goes from initial state to updating to initial state.
3849 # goes from initial state to updating to initial state.
3850 # initial state can be changed by specifying back_state=
3850 # initial state can be changed by specifying back_state=
3851 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
3851 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
3852 pull_request.merge()
3852 pull_request.merge()
3853
3853
3854 :param pull_request_state:
3854 :param pull_request_state:
3855 :param final_state:
3855 :param final_state:
3856
3856
3857 """
3857 """
3858
3858
3859 return _SetState(self, pull_request_state, back_state=final_state)
3859 return _SetState(self, pull_request_state, back_state=final_state)
3860
3860
3861
3861
3862 class PullRequest(Base, _PullRequestBase):
3862 class PullRequest(Base, _PullRequestBase):
3863 __tablename__ = 'pull_requests'
3863 __tablename__ = 'pull_requests'
3864 __table_args__ = (
3864 __table_args__ = (
3865 base_table_args,
3865 base_table_args,
3866 )
3866 )
3867
3867
3868 pull_request_id = Column(
3868 pull_request_id = Column(
3869 'pull_request_id', Integer(), nullable=False, primary_key=True)
3869 'pull_request_id', Integer(), nullable=False, primary_key=True)
3870
3870
3871 def __repr__(self):
3871 def __repr__(self):
3872 if self.pull_request_id:
3872 if self.pull_request_id:
3873 return '<DB:PullRequest #%s>' % self.pull_request_id
3873 return '<DB:PullRequest #%s>' % self.pull_request_id
3874 else:
3874 else:
3875 return '<DB:PullRequest at %#x>' % id(self)
3875 return '<DB:PullRequest at %#x>' % id(self)
3876
3876
3877 reviewers = relationship('PullRequestReviewers',
3877 reviewers = relationship('PullRequestReviewers',
3878 cascade="all, delete, delete-orphan")
3878 cascade="all, delete, delete-orphan")
3879 statuses = relationship('ChangesetStatus',
3879 statuses = relationship('ChangesetStatus',
3880 cascade="all, delete, delete-orphan")
3880 cascade="all, delete, delete-orphan")
3881 comments = relationship('ChangesetComment',
3881 comments = relationship('ChangesetComment',
3882 cascade="all, delete, delete-orphan")
3882 cascade="all, delete, delete-orphan")
3883 versions = relationship('PullRequestVersion',
3883 versions = relationship('PullRequestVersion',
3884 cascade="all, delete, delete-orphan",
3884 cascade="all, delete, delete-orphan",
3885 lazy='dynamic')
3885 lazy='dynamic')
3886
3886
3887 @classmethod
3887 @classmethod
3888 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3888 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3889 internal_methods=None):
3889 internal_methods=None):
3890
3890
3891 class PullRequestDisplay(object):
3891 class PullRequestDisplay(object):
3892 """
3892 """
3893 Special object wrapper for showing PullRequest data via Versions
3893 Special object wrapper for showing PullRequest data via Versions
3894 It mimics PR object as close as possible. This is read only object
3894 It mimics PR object as close as possible. This is read only object
3895 just for display
3895 just for display
3896 """
3896 """
3897
3897
3898 def __init__(self, attrs, internal=None):
3898 def __init__(self, attrs, internal=None):
3899 self.attrs = attrs
3899 self.attrs = attrs
3900 # internal have priority over the given ones via attrs
3900 # internal have priority over the given ones via attrs
3901 self.internal = internal or ['versions']
3901 self.internal = internal or ['versions']
3902
3902
3903 def __getattr__(self, item):
3903 def __getattr__(self, item):
3904 if item in self.internal:
3904 if item in self.internal:
3905 return getattr(self, item)
3905 return getattr(self, item)
3906 try:
3906 try:
3907 return self.attrs[item]
3907 return self.attrs[item]
3908 except KeyError:
3908 except KeyError:
3909 raise AttributeError(
3909 raise AttributeError(
3910 '%s object has no attribute %s' % (self, item))
3910 '%s object has no attribute %s' % (self, item))
3911
3911
3912 def __repr__(self):
3912 def __repr__(self):
3913 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3913 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3914
3914
3915 def versions(self):
3915 def versions(self):
3916 return pull_request_obj.versions.order_by(
3916 return pull_request_obj.versions.order_by(
3917 PullRequestVersion.pull_request_version_id).all()
3917 PullRequestVersion.pull_request_version_id).all()
3918
3918
3919 def is_closed(self):
3919 def is_closed(self):
3920 return pull_request_obj.is_closed()
3920 return pull_request_obj.is_closed()
3921
3921
3922 @property
3922 @property
3923 def pull_request_version_id(self):
3923 def pull_request_version_id(self):
3924 return getattr(pull_request_obj, 'pull_request_version_id', None)
3924 return getattr(pull_request_obj, 'pull_request_version_id', None)
3925
3925
3926 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3926 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3927
3927
3928 attrs.author = StrictAttributeDict(
3928 attrs.author = StrictAttributeDict(
3929 pull_request_obj.author.get_api_data())
3929 pull_request_obj.author.get_api_data())
3930 if pull_request_obj.target_repo:
3930 if pull_request_obj.target_repo:
3931 attrs.target_repo = StrictAttributeDict(
3931 attrs.target_repo = StrictAttributeDict(
3932 pull_request_obj.target_repo.get_api_data())
3932 pull_request_obj.target_repo.get_api_data())
3933 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3933 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3934
3934
3935 if pull_request_obj.source_repo:
3935 if pull_request_obj.source_repo:
3936 attrs.source_repo = StrictAttributeDict(
3936 attrs.source_repo = StrictAttributeDict(
3937 pull_request_obj.source_repo.get_api_data())
3937 pull_request_obj.source_repo.get_api_data())
3938 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3938 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3939
3939
3940 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3940 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3941 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3941 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3942 attrs.revisions = pull_request_obj.revisions
3942 attrs.revisions = pull_request_obj.revisions
3943
3943
3944 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3944 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3945 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3945 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3946 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3946 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3947
3947
3948 return PullRequestDisplay(attrs, internal=internal_methods)
3948 return PullRequestDisplay(attrs, internal=internal_methods)
3949
3949
3950 def is_closed(self):
3950 def is_closed(self):
3951 return self.status == self.STATUS_CLOSED
3951 return self.status == self.STATUS_CLOSED
3952
3952
3953 def __json__(self):
3953 def __json__(self):
3954 return {
3954 return {
3955 'revisions': self.revisions,
3955 'revisions': self.revisions,
3956 }
3956 }
3957
3957
3958 def calculated_review_status(self):
3958 def calculated_review_status(self):
3959 from rhodecode.model.changeset_status import ChangesetStatusModel
3959 from rhodecode.model.changeset_status import ChangesetStatusModel
3960 return ChangesetStatusModel().calculated_review_status(self)
3960 return ChangesetStatusModel().calculated_review_status(self)
3961
3961
3962 def reviewers_statuses(self):
3962 def reviewers_statuses(self):
3963 from rhodecode.model.changeset_status import ChangesetStatusModel
3963 from rhodecode.model.changeset_status import ChangesetStatusModel
3964 return ChangesetStatusModel().reviewers_statuses(self)
3964 return ChangesetStatusModel().reviewers_statuses(self)
3965
3965
3966 @property
3966 @property
3967 def workspace_id(self):
3967 def workspace_id(self):
3968 from rhodecode.model.pull_request import PullRequestModel
3968 from rhodecode.model.pull_request import PullRequestModel
3969 return PullRequestModel()._workspace_id(self)
3969 return PullRequestModel()._workspace_id(self)
3970
3970
3971 def get_shadow_repo(self):
3971 def get_shadow_repo(self):
3972 workspace_id = self.workspace_id
3972 workspace_id = self.workspace_id
3973 vcs_obj = self.target_repo.scm_instance()
3973 vcs_obj = self.target_repo.scm_instance()
3974 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3974 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3975 self.target_repo.repo_id, workspace_id)
3975 self.target_repo.repo_id, workspace_id)
3976 if os.path.isdir(shadow_repository_path):
3976 if os.path.isdir(shadow_repository_path):
3977 return vcs_obj.get_shadow_instance(shadow_repository_path)
3977 return vcs_obj.get_shadow_instance(shadow_repository_path)
3978
3978
3979
3979
3980 class PullRequestVersion(Base, _PullRequestBase):
3980 class PullRequestVersion(Base, _PullRequestBase):
3981 __tablename__ = 'pull_request_versions'
3981 __tablename__ = 'pull_request_versions'
3982 __table_args__ = (
3982 __table_args__ = (
3983 base_table_args,
3983 base_table_args,
3984 )
3984 )
3985
3985
3986 pull_request_version_id = Column(
3986 pull_request_version_id = Column(
3987 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3987 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3988 pull_request_id = Column(
3988 pull_request_id = Column(
3989 'pull_request_id', Integer(),
3989 'pull_request_id', Integer(),
3990 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3990 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3991 pull_request = relationship('PullRequest')
3991 pull_request = relationship('PullRequest')
3992
3992
3993 def __repr__(self):
3993 def __repr__(self):
3994 if self.pull_request_version_id:
3994 if self.pull_request_version_id:
3995 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3995 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3996 else:
3996 else:
3997 return '<DB:PullRequestVersion at %#x>' % id(self)
3997 return '<DB:PullRequestVersion at %#x>' % id(self)
3998
3998
3999 @property
3999 @property
4000 def reviewers(self):
4000 def reviewers(self):
4001 return self.pull_request.reviewers
4001 return self.pull_request.reviewers
4002
4002
4003 @property
4003 @property
4004 def versions(self):
4004 def versions(self):
4005 return self.pull_request.versions
4005 return self.pull_request.versions
4006
4006
4007 def is_closed(self):
4007 def is_closed(self):
4008 # calculate from original
4008 # calculate from original
4009 return self.pull_request.status == self.STATUS_CLOSED
4009 return self.pull_request.status == self.STATUS_CLOSED
4010
4010
4011 def calculated_review_status(self):
4011 def calculated_review_status(self):
4012 return self.pull_request.calculated_review_status()
4012 return self.pull_request.calculated_review_status()
4013
4013
4014 def reviewers_statuses(self):
4014 def reviewers_statuses(self):
4015 return self.pull_request.reviewers_statuses()
4015 return self.pull_request.reviewers_statuses()
4016
4016
4017
4017
4018 class PullRequestReviewers(Base, BaseModel):
4018 class PullRequestReviewers(Base, BaseModel):
4019 __tablename__ = 'pull_request_reviewers'
4019 __tablename__ = 'pull_request_reviewers'
4020 __table_args__ = (
4020 __table_args__ = (
4021 base_table_args,
4021 base_table_args,
4022 )
4022 )
4023
4023
4024 @hybrid_property
4024 @hybrid_property
4025 def reasons(self):
4025 def reasons(self):
4026 if not self._reasons:
4026 if not self._reasons:
4027 return []
4027 return []
4028 return self._reasons
4028 return self._reasons
4029
4029
4030 @reasons.setter
4030 @reasons.setter
4031 def reasons(self, val):
4031 def reasons(self, val):
4032 val = val or []
4032 val = val or []
4033 if any(not isinstance(x, compat.string_types) for x in val):
4033 if any(not isinstance(x, compat.string_types) for x in val):
4034 raise Exception('invalid reasons type, must be list of strings')
4034 raise Exception('invalid reasons type, must be list of strings')
4035 self._reasons = val
4035 self._reasons = val
4036
4036
4037 pull_requests_reviewers_id = Column(
4037 pull_requests_reviewers_id = Column(
4038 'pull_requests_reviewers_id', Integer(), nullable=False,
4038 'pull_requests_reviewers_id', Integer(), nullable=False,
4039 primary_key=True)
4039 primary_key=True)
4040 pull_request_id = Column(
4040 pull_request_id = Column(
4041 "pull_request_id", Integer(),
4041 "pull_request_id", Integer(),
4042 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4042 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4043 user_id = Column(
4043 user_id = Column(
4044 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4044 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4045 _reasons = Column(
4045 _reasons = Column(
4046 'reason', MutationList.as_mutable(
4046 'reason', MutationList.as_mutable(
4047 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4047 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4048
4048
4049 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4049 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4050 user = relationship('User')
4050 user = relationship('User')
4051 pull_request = relationship('PullRequest')
4051 pull_request = relationship('PullRequest')
4052
4052
4053 rule_data = Column(
4053 rule_data = Column(
4054 'rule_data_json',
4054 'rule_data_json',
4055 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4055 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4056
4056
4057 def rule_user_group_data(self):
4057 def rule_user_group_data(self):
4058 """
4058 """
4059 Returns the voting user group rule data for this reviewer
4059 Returns the voting user group rule data for this reviewer
4060 """
4060 """
4061
4061
4062 if self.rule_data and 'vote_rule' in self.rule_data:
4062 if self.rule_data and 'vote_rule' in self.rule_data:
4063 user_group_data = {}
4063 user_group_data = {}
4064 if 'rule_user_group_entry_id' in self.rule_data:
4064 if 'rule_user_group_entry_id' in self.rule_data:
4065 # means a group with voting rules !
4065 # means a group with voting rules !
4066 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4066 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4067 user_group_data['name'] = self.rule_data['rule_name']
4067 user_group_data['name'] = self.rule_data['rule_name']
4068 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4068 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4069
4069
4070 return user_group_data
4070 return user_group_data
4071
4071
4072 def __unicode__(self):
4072 def __unicode__(self):
4073 return u"<%s('id:%s')>" % (self.__class__.__name__,
4073 return u"<%s('id:%s')>" % (self.__class__.__name__,
4074 self.pull_requests_reviewers_id)
4074 self.pull_requests_reviewers_id)
4075
4075
4076
4076
4077 class Notification(Base, BaseModel):
4077 class Notification(Base, BaseModel):
4078 __tablename__ = 'notifications'
4078 __tablename__ = 'notifications'
4079 __table_args__ = (
4079 __table_args__ = (
4080 Index('notification_type_idx', 'type'),
4080 Index('notification_type_idx', 'type'),
4081 base_table_args,
4081 base_table_args,
4082 )
4082 )
4083
4083
4084 TYPE_CHANGESET_COMMENT = u'cs_comment'
4084 TYPE_CHANGESET_COMMENT = u'cs_comment'
4085 TYPE_MESSAGE = u'message'
4085 TYPE_MESSAGE = u'message'
4086 TYPE_MENTION = u'mention'
4086 TYPE_MENTION = u'mention'
4087 TYPE_REGISTRATION = u'registration'
4087 TYPE_REGISTRATION = u'registration'
4088 TYPE_PULL_REQUEST = u'pull_request'
4088 TYPE_PULL_REQUEST = u'pull_request'
4089 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4089 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4090
4090
4091 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4091 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4092 subject = Column('subject', Unicode(512), nullable=True)
4092 subject = Column('subject', Unicode(512), nullable=True)
4093 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4093 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4094 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4094 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4095 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4095 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4096 type_ = Column('type', Unicode(255))
4096 type_ = Column('type', Unicode(255))
4097
4097
4098 created_by_user = relationship('User')
4098 created_by_user = relationship('User')
4099 notifications_to_users = relationship('UserNotification', lazy='joined',
4099 notifications_to_users = relationship('UserNotification', lazy='joined',
4100 cascade="all, delete, delete-orphan")
4100 cascade="all, delete, delete-orphan")
4101
4101
4102 @property
4102 @property
4103 def recipients(self):
4103 def recipients(self):
4104 return [x.user for x in UserNotification.query()\
4104 return [x.user for x in UserNotification.query()\
4105 .filter(UserNotification.notification == self)\
4105 .filter(UserNotification.notification == self)\
4106 .order_by(UserNotification.user_id.asc()).all()]
4106 .order_by(UserNotification.user_id.asc()).all()]
4107
4107
4108 @classmethod
4108 @classmethod
4109 def create(cls, created_by, subject, body, recipients, type_=None):
4109 def create(cls, created_by, subject, body, recipients, type_=None):
4110 if type_ is None:
4110 if type_ is None:
4111 type_ = Notification.TYPE_MESSAGE
4111 type_ = Notification.TYPE_MESSAGE
4112
4112
4113 notification = cls()
4113 notification = cls()
4114 notification.created_by_user = created_by
4114 notification.created_by_user = created_by
4115 notification.subject = subject
4115 notification.subject = subject
4116 notification.body = body
4116 notification.body = body
4117 notification.type_ = type_
4117 notification.type_ = type_
4118 notification.created_on = datetime.datetime.now()
4118 notification.created_on = datetime.datetime.now()
4119
4119
4120 # For each recipient link the created notification to his account
4120 # For each recipient link the created notification to his account
4121 for u in recipients:
4121 for u in recipients:
4122 assoc = UserNotification()
4122 assoc = UserNotification()
4123 assoc.user_id = u.user_id
4123 assoc.user_id = u.user_id
4124 assoc.notification = notification
4124 assoc.notification = notification
4125
4125
4126 # if created_by is inside recipients mark his notification
4126 # if created_by is inside recipients mark his notification
4127 # as read
4127 # as read
4128 if u.user_id == created_by.user_id:
4128 if u.user_id == created_by.user_id:
4129 assoc.read = True
4129 assoc.read = True
4130 Session().add(assoc)
4130 Session().add(assoc)
4131
4131
4132 Session().add(notification)
4132 Session().add(notification)
4133
4133
4134 return notification
4134 return notification
4135
4135
4136
4136
4137 class UserNotification(Base, BaseModel):
4137 class UserNotification(Base, BaseModel):
4138 __tablename__ = 'user_to_notification'
4138 __tablename__ = 'user_to_notification'
4139 __table_args__ = (
4139 __table_args__ = (
4140 UniqueConstraint('user_id', 'notification_id'),
4140 UniqueConstraint('user_id', 'notification_id'),
4141 base_table_args
4141 base_table_args
4142 )
4142 )
4143
4143
4144 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4144 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4145 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4145 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4146 read = Column('read', Boolean, default=False)
4146 read = Column('read', Boolean, default=False)
4147 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4147 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4148
4148
4149 user = relationship('User', lazy="joined")
4149 user = relationship('User', lazy="joined")
4150 notification = relationship('Notification', lazy="joined",
4150 notification = relationship('Notification', lazy="joined",
4151 order_by=lambda: Notification.created_on.desc(),)
4151 order_by=lambda: Notification.created_on.desc(),)
4152
4152
4153 def mark_as_read(self):
4153 def mark_as_read(self):
4154 self.read = True
4154 self.read = True
4155 Session().add(self)
4155 Session().add(self)
4156
4156
4157
4157
4158 class Gist(Base, BaseModel):
4158 class Gist(Base, BaseModel):
4159 __tablename__ = 'gists'
4159 __tablename__ = 'gists'
4160 __table_args__ = (
4160 __table_args__ = (
4161 Index('g_gist_access_id_idx', 'gist_access_id'),
4161 Index('g_gist_access_id_idx', 'gist_access_id'),
4162 Index('g_created_on_idx', 'created_on'),
4162 Index('g_created_on_idx', 'created_on'),
4163 base_table_args
4163 base_table_args
4164 )
4164 )
4165
4165
4166 GIST_PUBLIC = u'public'
4166 GIST_PUBLIC = u'public'
4167 GIST_PRIVATE = u'private'
4167 GIST_PRIVATE = u'private'
4168 DEFAULT_FILENAME = u'gistfile1.txt'
4168 DEFAULT_FILENAME = u'gistfile1.txt'
4169
4169
4170 ACL_LEVEL_PUBLIC = u'acl_public'
4170 ACL_LEVEL_PUBLIC = u'acl_public'
4171 ACL_LEVEL_PRIVATE = u'acl_private'
4171 ACL_LEVEL_PRIVATE = u'acl_private'
4172
4172
4173 gist_id = Column('gist_id', Integer(), primary_key=True)
4173 gist_id = Column('gist_id', Integer(), primary_key=True)
4174 gist_access_id = Column('gist_access_id', Unicode(250))
4174 gist_access_id = Column('gist_access_id', Unicode(250))
4175 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4175 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4176 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4176 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4177 gist_expires = Column('gist_expires', Float(53), nullable=False)
4177 gist_expires = Column('gist_expires', Float(53), nullable=False)
4178 gist_type = Column('gist_type', Unicode(128), nullable=False)
4178 gist_type = Column('gist_type', Unicode(128), nullable=False)
4179 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4179 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4180 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4180 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4181 acl_level = Column('acl_level', Unicode(128), nullable=True)
4181 acl_level = Column('acl_level', Unicode(128), nullable=True)
4182
4182
4183 owner = relationship('User')
4183 owner = relationship('User')
4184
4184
4185 def __repr__(self):
4185 def __repr__(self):
4186 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4186 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4187
4187
4188 @hybrid_property
4188 @hybrid_property
4189 def description_safe(self):
4189 def description_safe(self):
4190 from rhodecode.lib import helpers as h
4190 from rhodecode.lib import helpers as h
4191 return h.escape(self.gist_description)
4191 return h.escape(self.gist_description)
4192
4192
4193 @classmethod
4193 @classmethod
4194 def get_or_404(cls, id_):
4194 def get_or_404(cls, id_):
4195 from pyramid.httpexceptions import HTTPNotFound
4195 from pyramid.httpexceptions import HTTPNotFound
4196
4196
4197 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4197 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4198 if not res:
4198 if not res:
4199 raise HTTPNotFound()
4199 raise HTTPNotFound()
4200 return res
4200 return res
4201
4201
4202 @classmethod
4202 @classmethod
4203 def get_by_access_id(cls, gist_access_id):
4203 def get_by_access_id(cls, gist_access_id):
4204 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4204 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4205
4205
4206 def gist_url(self):
4206 def gist_url(self):
4207 from rhodecode.model.gist import GistModel
4207 from rhodecode.model.gist import GistModel
4208 return GistModel().get_url(self)
4208 return GistModel().get_url(self)
4209
4209
4210 @classmethod
4210 @classmethod
4211 def base_path(cls):
4211 def base_path(cls):
4212 """
4212 """
4213 Returns base path when all gists are stored
4213 Returns base path when all gists are stored
4214
4214
4215 :param cls:
4215 :param cls:
4216 """
4216 """
4217 from rhodecode.model.gist import GIST_STORE_LOC
4217 from rhodecode.model.gist import GIST_STORE_LOC
4218 q = Session().query(RhodeCodeUi)\
4218 q = Session().query(RhodeCodeUi)\
4219 .filter(RhodeCodeUi.ui_key == URL_SEP)
4219 .filter(RhodeCodeUi.ui_key == URL_SEP)
4220 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4220 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4221 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4221 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4222
4222
4223 def get_api_data(self):
4223 def get_api_data(self):
4224 """
4224 """
4225 Common function for generating gist related data for API
4225 Common function for generating gist related data for API
4226 """
4226 """
4227 gist = self
4227 gist = self
4228 data = {
4228 data = {
4229 'gist_id': gist.gist_id,
4229 'gist_id': gist.gist_id,
4230 'type': gist.gist_type,
4230 'type': gist.gist_type,
4231 'access_id': gist.gist_access_id,
4231 'access_id': gist.gist_access_id,
4232 'description': gist.gist_description,
4232 'description': gist.gist_description,
4233 'url': gist.gist_url(),
4233 'url': gist.gist_url(),
4234 'expires': gist.gist_expires,
4234 'expires': gist.gist_expires,
4235 'created_on': gist.created_on,
4235 'created_on': gist.created_on,
4236 'modified_at': gist.modified_at,
4236 'modified_at': gist.modified_at,
4237 'content': None,
4237 'content': None,
4238 'acl_level': gist.acl_level,
4238 'acl_level': gist.acl_level,
4239 }
4239 }
4240 return data
4240 return data
4241
4241
4242 def __json__(self):
4242 def __json__(self):
4243 data = dict(
4243 data = dict(
4244 )
4244 )
4245 data.update(self.get_api_data())
4245 data.update(self.get_api_data())
4246 return data
4246 return data
4247 # SCM functions
4247 # SCM functions
4248
4248
4249 def scm_instance(self, **kwargs):
4249 def scm_instance(self, **kwargs):
4250 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4250 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4251 return get_vcs_instance(
4251 return get_vcs_instance(
4252 repo_path=safe_str(full_repo_path), create=False)
4252 repo_path=safe_str(full_repo_path), create=False)
4253
4253
4254
4254
4255 class ExternalIdentity(Base, BaseModel):
4255 class ExternalIdentity(Base, BaseModel):
4256 __tablename__ = 'external_identities'
4256 __tablename__ = 'external_identities'
4257 __table_args__ = (
4257 __table_args__ = (
4258 Index('local_user_id_idx', 'local_user_id'),
4258 Index('local_user_id_idx', 'local_user_id'),
4259 Index('external_id_idx', 'external_id'),
4259 Index('external_id_idx', 'external_id'),
4260 base_table_args
4260 base_table_args
4261 )
4261 )
4262
4262
4263 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4263 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4264 external_username = Column('external_username', Unicode(1024), default=u'')
4264 external_username = Column('external_username', Unicode(1024), default=u'')
4265 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4265 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4266 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4266 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4267 access_token = Column('access_token', String(1024), default=u'')
4267 access_token = Column('access_token', String(1024), default=u'')
4268 alt_token = Column('alt_token', String(1024), default=u'')
4268 alt_token = Column('alt_token', String(1024), default=u'')
4269 token_secret = Column('token_secret', String(1024), default=u'')
4269 token_secret = Column('token_secret', String(1024), default=u'')
4270
4270
4271 @classmethod
4271 @classmethod
4272 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4272 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4273 """
4273 """
4274 Returns ExternalIdentity instance based on search params
4274 Returns ExternalIdentity instance based on search params
4275
4275
4276 :param external_id:
4276 :param external_id:
4277 :param provider_name:
4277 :param provider_name:
4278 :return: ExternalIdentity
4278 :return: ExternalIdentity
4279 """
4279 """
4280 query = cls.query()
4280 query = cls.query()
4281 query = query.filter(cls.external_id == external_id)
4281 query = query.filter(cls.external_id == external_id)
4282 query = query.filter(cls.provider_name == provider_name)
4282 query = query.filter(cls.provider_name == provider_name)
4283 if local_user_id:
4283 if local_user_id:
4284 query = query.filter(cls.local_user_id == local_user_id)
4284 query = query.filter(cls.local_user_id == local_user_id)
4285 return query.first()
4285 return query.first()
4286
4286
4287 @classmethod
4287 @classmethod
4288 def user_by_external_id_and_provider(cls, external_id, provider_name):
4288 def user_by_external_id_and_provider(cls, external_id, provider_name):
4289 """
4289 """
4290 Returns User instance based on search params
4290 Returns User instance based on search params
4291
4291
4292 :param external_id:
4292 :param external_id:
4293 :param provider_name:
4293 :param provider_name:
4294 :return: User
4294 :return: User
4295 """
4295 """
4296 query = User.query()
4296 query = User.query()
4297 query = query.filter(cls.external_id == external_id)
4297 query = query.filter(cls.external_id == external_id)
4298 query = query.filter(cls.provider_name == provider_name)
4298 query = query.filter(cls.provider_name == provider_name)
4299 query = query.filter(User.user_id == cls.local_user_id)
4299 query = query.filter(User.user_id == cls.local_user_id)
4300 return query.first()
4300 return query.first()
4301
4301
4302 @classmethod
4302 @classmethod
4303 def by_local_user_id(cls, local_user_id):
4303 def by_local_user_id(cls, local_user_id):
4304 """
4304 """
4305 Returns all tokens for user
4305 Returns all tokens for user
4306
4306
4307 :param local_user_id:
4307 :param local_user_id:
4308 :return: ExternalIdentity
4308 :return: ExternalIdentity
4309 """
4309 """
4310 query = cls.query()
4310 query = cls.query()
4311 query = query.filter(cls.local_user_id == local_user_id)
4311 query = query.filter(cls.local_user_id == local_user_id)
4312 return query
4312 return query
4313
4313
4314 @classmethod
4314 @classmethod
4315 def load_provider_plugin(cls, plugin_id):
4315 def load_provider_plugin(cls, plugin_id):
4316 from rhodecode.authentication.base import loadplugin
4316 from rhodecode.authentication.base import loadplugin
4317 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4317 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4318 auth_plugin = loadplugin(_plugin_id)
4318 auth_plugin = loadplugin(_plugin_id)
4319 return auth_plugin
4319 return auth_plugin
4320
4320
4321
4321
4322 class Integration(Base, BaseModel):
4322 class Integration(Base, BaseModel):
4323 __tablename__ = 'integrations'
4323 __tablename__ = 'integrations'
4324 __table_args__ = (
4324 __table_args__ = (
4325 base_table_args
4325 base_table_args
4326 )
4326 )
4327
4327
4328 integration_id = Column('integration_id', Integer(), primary_key=True)
4328 integration_id = Column('integration_id', Integer(), primary_key=True)
4329 integration_type = Column('integration_type', String(255))
4329 integration_type = Column('integration_type', String(255))
4330 enabled = Column('enabled', Boolean(), nullable=False)
4330 enabled = Column('enabled', Boolean(), nullable=False)
4331 name = Column('name', String(255), nullable=False)
4331 name = Column('name', String(255), nullable=False)
4332 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4332 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4333 default=False)
4333 default=False)
4334
4334
4335 settings = Column(
4335 settings = Column(
4336 'settings_json', MutationObj.as_mutable(
4336 'settings_json', MutationObj.as_mutable(
4337 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4337 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4338 repo_id = Column(
4338 repo_id = Column(
4339 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4339 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4340 nullable=True, unique=None, default=None)
4340 nullable=True, unique=None, default=None)
4341 repo = relationship('Repository', lazy='joined')
4341 repo = relationship('Repository', lazy='joined')
4342
4342
4343 repo_group_id = Column(
4343 repo_group_id = Column(
4344 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4344 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4345 nullable=True, unique=None, default=None)
4345 nullable=True, unique=None, default=None)
4346 repo_group = relationship('RepoGroup', lazy='joined')
4346 repo_group = relationship('RepoGroup', lazy='joined')
4347
4347
4348 @property
4348 @property
4349 def scope(self):
4349 def scope(self):
4350 if self.repo:
4350 if self.repo:
4351 return repr(self.repo)
4351 return repr(self.repo)
4352 if self.repo_group:
4352 if self.repo_group:
4353 if self.child_repos_only:
4353 if self.child_repos_only:
4354 return repr(self.repo_group) + ' (child repos only)'
4354 return repr(self.repo_group) + ' (child repos only)'
4355 else:
4355 else:
4356 return repr(self.repo_group) + ' (recursive)'
4356 return repr(self.repo_group) + ' (recursive)'
4357 if self.child_repos_only:
4357 if self.child_repos_only:
4358 return 'root_repos'
4358 return 'root_repos'
4359 return 'global'
4359 return 'global'
4360
4360
4361 def __repr__(self):
4361 def __repr__(self):
4362 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4362 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4363
4363
4364
4364
4365 class RepoReviewRuleUser(Base, BaseModel):
4365 class RepoReviewRuleUser(Base, BaseModel):
4366 __tablename__ = 'repo_review_rules_users'
4366 __tablename__ = 'repo_review_rules_users'
4367 __table_args__ = (
4367 __table_args__ = (
4368 base_table_args
4368 base_table_args
4369 )
4369 )
4370
4370
4371 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4371 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4372 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4372 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4373 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4373 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4374 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4374 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4375 user = relationship('User')
4375 user = relationship('User')
4376
4376
4377 def rule_data(self):
4377 def rule_data(self):
4378 return {
4378 return {
4379 'mandatory': self.mandatory
4379 'mandatory': self.mandatory
4380 }
4380 }
4381
4381
4382
4382
4383 class RepoReviewRuleUserGroup(Base, BaseModel):
4383 class RepoReviewRuleUserGroup(Base, BaseModel):
4384 __tablename__ = 'repo_review_rules_users_groups'
4384 __tablename__ = 'repo_review_rules_users_groups'
4385 __table_args__ = (
4385 __table_args__ = (
4386 base_table_args
4386 base_table_args
4387 )
4387 )
4388
4388
4389 VOTE_RULE_ALL = -1
4389 VOTE_RULE_ALL = -1
4390
4390
4391 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4391 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4392 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4392 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4393 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4393 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4394 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4394 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4395 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4395 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4396 users_group = relationship('UserGroup')
4396 users_group = relationship('UserGroup')
4397
4397
4398 def rule_data(self):
4398 def rule_data(self):
4399 return {
4399 return {
4400 'mandatory': self.mandatory,
4400 'mandatory': self.mandatory,
4401 'vote_rule': self.vote_rule
4401 'vote_rule': self.vote_rule
4402 }
4402 }
4403
4403
4404 @property
4404 @property
4405 def vote_rule_label(self):
4405 def vote_rule_label(self):
4406 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4406 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4407 return 'all must vote'
4407 return 'all must vote'
4408 else:
4408 else:
4409 return 'min. vote {}'.format(self.vote_rule)
4409 return 'min. vote {}'.format(self.vote_rule)
4410
4410
4411
4411
4412 class RepoReviewRule(Base, BaseModel):
4412 class RepoReviewRule(Base, BaseModel):
4413 __tablename__ = 'repo_review_rules'
4413 __tablename__ = 'repo_review_rules'
4414 __table_args__ = (
4414 __table_args__ = (
4415 base_table_args
4415 base_table_args
4416 )
4416 )
4417
4417
4418 repo_review_rule_id = Column(
4418 repo_review_rule_id = Column(
4419 'repo_review_rule_id', Integer(), primary_key=True)
4419 'repo_review_rule_id', Integer(), primary_key=True)
4420 repo_id = Column(
4420 repo_id = Column(
4421 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4421 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4422 repo = relationship('Repository', backref='review_rules')
4422 repo = relationship('Repository', backref='review_rules')
4423
4423
4424 review_rule_name = Column('review_rule_name', String(255))
4424 review_rule_name = Column('review_rule_name', String(255))
4425 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4425 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4426 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4426 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4427 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4427 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4428
4428
4429 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4429 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4430 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4430 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4431 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4431 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4432 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4432 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4433
4433
4434 rule_users = relationship('RepoReviewRuleUser')
4434 rule_users = relationship('RepoReviewRuleUser')
4435 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4435 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4436
4436
4437 def _validate_pattern(self, value):
4437 def _validate_pattern(self, value):
4438 re.compile('^' + glob2re(value) + '$')
4438 re.compile('^' + glob2re(value) + '$')
4439
4439
4440 @hybrid_property
4440 @hybrid_property
4441 def source_branch_pattern(self):
4441 def source_branch_pattern(self):
4442 return self._branch_pattern or '*'
4442 return self._branch_pattern or '*'
4443
4443
4444 @source_branch_pattern.setter
4444 @source_branch_pattern.setter
4445 def source_branch_pattern(self, value):
4445 def source_branch_pattern(self, value):
4446 self._validate_pattern(value)
4446 self._validate_pattern(value)
4447 self._branch_pattern = value or '*'
4447 self._branch_pattern = value or '*'
4448
4448
4449 @hybrid_property
4449 @hybrid_property
4450 def target_branch_pattern(self):
4450 def target_branch_pattern(self):
4451 return self._target_branch_pattern or '*'
4451 return self._target_branch_pattern or '*'
4452
4452
4453 @target_branch_pattern.setter
4453 @target_branch_pattern.setter
4454 def target_branch_pattern(self, value):
4454 def target_branch_pattern(self, value):
4455 self._validate_pattern(value)
4455 self._validate_pattern(value)
4456 self._target_branch_pattern = value or '*'
4456 self._target_branch_pattern = value or '*'
4457
4457
4458 @hybrid_property
4458 @hybrid_property
4459 def file_pattern(self):
4459 def file_pattern(self):
4460 return self._file_pattern or '*'
4460 return self._file_pattern or '*'
4461
4461
4462 @file_pattern.setter
4462 @file_pattern.setter
4463 def file_pattern(self, value):
4463 def file_pattern(self, value):
4464 self._validate_pattern(value)
4464 self._validate_pattern(value)
4465 self._file_pattern = value or '*'
4465 self._file_pattern = value or '*'
4466
4466
4467 def matches(self, source_branch, target_branch, files_changed):
4467 def matches(self, source_branch, target_branch, files_changed):
4468 """
4468 """
4469 Check if this review rule matches a branch/files in a pull request
4469 Check if this review rule matches a branch/files in a pull request
4470
4470
4471 :param source_branch: source branch name for the commit
4471 :param source_branch: source branch name for the commit
4472 :param target_branch: target branch name for the commit
4472 :param target_branch: target branch name for the commit
4473 :param files_changed: list of file paths changed in the pull request
4473 :param files_changed: list of file paths changed in the pull request
4474 """
4474 """
4475
4475
4476 source_branch = source_branch or ''
4476 source_branch = source_branch or ''
4477 target_branch = target_branch or ''
4477 target_branch = target_branch or ''
4478 files_changed = files_changed or []
4478 files_changed = files_changed or []
4479
4479
4480 branch_matches = True
4480 branch_matches = True
4481 if source_branch or target_branch:
4481 if source_branch or target_branch:
4482 if self.source_branch_pattern == '*':
4482 if self.source_branch_pattern == '*':
4483 source_branch_match = True
4483 source_branch_match = True
4484 else:
4484 else:
4485 if self.source_branch_pattern.startswith('re:'):
4485 if self.source_branch_pattern.startswith('re:'):
4486 source_pattern = self.source_branch_pattern[3:]
4486 source_pattern = self.source_branch_pattern[3:]
4487 else:
4487 else:
4488 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4488 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4489 source_branch_regex = re.compile(source_pattern)
4489 source_branch_regex = re.compile(source_pattern)
4490 source_branch_match = bool(source_branch_regex.search(source_branch))
4490 source_branch_match = bool(source_branch_regex.search(source_branch))
4491 if self.target_branch_pattern == '*':
4491 if self.target_branch_pattern == '*':
4492 target_branch_match = True
4492 target_branch_match = True
4493 else:
4493 else:
4494 if self.target_branch_pattern.startswith('re:'):
4494 if self.target_branch_pattern.startswith('re:'):
4495 target_pattern = self.target_branch_pattern[3:]
4495 target_pattern = self.target_branch_pattern[3:]
4496 else:
4496 else:
4497 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4497 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4498 target_branch_regex = re.compile(target_pattern)
4498 target_branch_regex = re.compile(target_pattern)
4499 target_branch_match = bool(target_branch_regex.search(target_branch))
4499 target_branch_match = bool(target_branch_regex.search(target_branch))
4500
4500
4501 branch_matches = source_branch_match and target_branch_match
4501 branch_matches = source_branch_match and target_branch_match
4502
4502
4503 files_matches = True
4503 files_matches = True
4504 if self.file_pattern != '*':
4504 if self.file_pattern != '*':
4505 files_matches = False
4505 files_matches = False
4506 if self.file_pattern.startswith('re:'):
4506 if self.file_pattern.startswith('re:'):
4507 file_pattern = self.file_pattern[3:]
4507 file_pattern = self.file_pattern[3:]
4508 else:
4508 else:
4509 file_pattern = glob2re(self.file_pattern)
4509 file_pattern = glob2re(self.file_pattern)
4510 file_regex = re.compile(file_pattern)
4510 file_regex = re.compile(file_pattern)
4511 for filename in files_changed:
4511 for filename in files_changed:
4512 if file_regex.search(filename):
4512 if file_regex.search(filename):
4513 files_matches = True
4513 files_matches = True
4514 break
4514 break
4515
4515
4516 return branch_matches and files_matches
4516 return branch_matches and files_matches
4517
4517
4518 @property
4518 @property
4519 def review_users(self):
4519 def review_users(self):
4520 """ Returns the users which this rule applies to """
4520 """ Returns the users which this rule applies to """
4521
4521
4522 users = collections.OrderedDict()
4522 users = collections.OrderedDict()
4523
4523
4524 for rule_user in self.rule_users:
4524 for rule_user in self.rule_users:
4525 if rule_user.user.active:
4525 if rule_user.user.active:
4526 if rule_user.user not in users:
4526 if rule_user.user not in users:
4527 users[rule_user.user.username] = {
4527 users[rule_user.user.username] = {
4528 'user': rule_user.user,
4528 'user': rule_user.user,
4529 'source': 'user',
4529 'source': 'user',
4530 'source_data': {},
4530 'source_data': {},
4531 'data': rule_user.rule_data()
4531 'data': rule_user.rule_data()
4532 }
4532 }
4533
4533
4534 for rule_user_group in self.rule_user_groups:
4534 for rule_user_group in self.rule_user_groups:
4535 source_data = {
4535 source_data = {
4536 'user_group_id': rule_user_group.users_group.users_group_id,
4536 'user_group_id': rule_user_group.users_group.users_group_id,
4537 'name': rule_user_group.users_group.users_group_name,
4537 'name': rule_user_group.users_group.users_group_name,
4538 'members': len(rule_user_group.users_group.members)
4538 'members': len(rule_user_group.users_group.members)
4539 }
4539 }
4540 for member in rule_user_group.users_group.members:
4540 for member in rule_user_group.users_group.members:
4541 if member.user.active:
4541 if member.user.active:
4542 key = member.user.username
4542 key = member.user.username
4543 if key in users:
4543 if key in users:
4544 # skip this member as we have him already
4544 # skip this member as we have him already
4545 # this prevents from override the "first" matched
4545 # this prevents from override the "first" matched
4546 # users with duplicates in multiple groups
4546 # users with duplicates in multiple groups
4547 continue
4547 continue
4548
4548
4549 users[key] = {
4549 users[key] = {
4550 'user': member.user,
4550 'user': member.user,
4551 'source': 'user_group',
4551 'source': 'user_group',
4552 'source_data': source_data,
4552 'source_data': source_data,
4553 'data': rule_user_group.rule_data()
4553 'data': rule_user_group.rule_data()
4554 }
4554 }
4555
4555
4556 return users
4556 return users
4557
4557
4558 def user_group_vote_rule(self, user_id):
4558 def user_group_vote_rule(self, user_id):
4559
4559
4560 rules = []
4560 rules = []
4561 if not self.rule_user_groups:
4561 if not self.rule_user_groups:
4562 return rules
4562 return rules
4563
4563
4564 for user_group in self.rule_user_groups:
4564 for user_group in self.rule_user_groups:
4565 user_group_members = [x.user_id for x in user_group.users_group.members]
4565 user_group_members = [x.user_id for x in user_group.users_group.members]
4566 if user_id in user_group_members:
4566 if user_id in user_group_members:
4567 rules.append(user_group)
4567 rules.append(user_group)
4568 return rules
4568 return rules
4569
4569
4570 def __repr__(self):
4570 def __repr__(self):
4571 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4571 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4572 self.repo_review_rule_id, self.repo)
4572 self.repo_review_rule_id, self.repo)
4573
4573
4574
4574
4575 class ScheduleEntry(Base, BaseModel):
4575 class ScheduleEntry(Base, BaseModel):
4576 __tablename__ = 'schedule_entries'
4576 __tablename__ = 'schedule_entries'
4577 __table_args__ = (
4577 __table_args__ = (
4578 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4578 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4579 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4579 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4580 base_table_args,
4580 base_table_args,
4581 )
4581 )
4582
4582
4583 schedule_types = ['crontab', 'timedelta', 'integer']
4583 schedule_types = ['crontab', 'timedelta', 'integer']
4584 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4584 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4585
4585
4586 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4586 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4587 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4587 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4588 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4588 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4589
4589
4590 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4590 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4591 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4591 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4592
4592
4593 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4593 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4594 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4594 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4595
4595
4596 # task
4596 # task
4597 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4597 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4598 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4598 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4599 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4599 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4600 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4600 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4601
4601
4602 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4602 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4603 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4603 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4604
4604
4605 @hybrid_property
4605 @hybrid_property
4606 def schedule_type(self):
4606 def schedule_type(self):
4607 return self._schedule_type
4607 return self._schedule_type
4608
4608
4609 @schedule_type.setter
4609 @schedule_type.setter
4610 def schedule_type(self, val):
4610 def schedule_type(self, val):
4611 if val not in self.schedule_types:
4611 if val not in self.schedule_types:
4612 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4612 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4613 val, self.schedule_type))
4613 val, self.schedule_type))
4614
4614
4615 self._schedule_type = val
4615 self._schedule_type = val
4616
4616
4617 @classmethod
4617 @classmethod
4618 def get_uid(cls, obj):
4618 def get_uid(cls, obj):
4619 args = obj.task_args
4619 args = obj.task_args
4620 kwargs = obj.task_kwargs
4620 kwargs = obj.task_kwargs
4621 if isinstance(args, JsonRaw):
4621 if isinstance(args, JsonRaw):
4622 try:
4622 try:
4623 args = json.loads(args)
4623 args = json.loads(args)
4624 except ValueError:
4624 except ValueError:
4625 args = tuple()
4625 args = tuple()
4626
4626
4627 if isinstance(kwargs, JsonRaw):
4627 if isinstance(kwargs, JsonRaw):
4628 try:
4628 try:
4629 kwargs = json.loads(kwargs)
4629 kwargs = json.loads(kwargs)
4630 except ValueError:
4630 except ValueError:
4631 kwargs = dict()
4631 kwargs = dict()
4632
4632
4633 dot_notation = obj.task_dot_notation
4633 dot_notation = obj.task_dot_notation
4634 val = '.'.join(map(safe_str, [
4634 val = '.'.join(map(safe_str, [
4635 sorted(dot_notation), args, sorted(kwargs.items())]))
4635 sorted(dot_notation), args, sorted(kwargs.items())]))
4636 return hashlib.sha1(val).hexdigest()
4636 return hashlib.sha1(val).hexdigest()
4637
4637
4638 @classmethod
4638 @classmethod
4639 def get_by_schedule_name(cls, schedule_name):
4639 def get_by_schedule_name(cls, schedule_name):
4640 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4640 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4641
4641
4642 @classmethod
4642 @classmethod
4643 def get_by_schedule_id(cls, schedule_id):
4643 def get_by_schedule_id(cls, schedule_id):
4644 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4644 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4645
4645
4646 @property
4646 @property
4647 def task(self):
4647 def task(self):
4648 return self.task_dot_notation
4648 return self.task_dot_notation
4649
4649
4650 @property
4650 @property
4651 def schedule(self):
4651 def schedule(self):
4652 from rhodecode.lib.celerylib.utils import raw_2_schedule
4652 from rhodecode.lib.celerylib.utils import raw_2_schedule
4653 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4653 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4654 return schedule
4654 return schedule
4655
4655
4656 @property
4656 @property
4657 def args(self):
4657 def args(self):
4658 try:
4658 try:
4659 return list(self.task_args or [])
4659 return list(self.task_args or [])
4660 except ValueError:
4660 except ValueError:
4661 return list()
4661 return list()
4662
4662
4663 @property
4663 @property
4664 def kwargs(self):
4664 def kwargs(self):
4665 try:
4665 try:
4666 return dict(self.task_kwargs or {})
4666 return dict(self.task_kwargs or {})
4667 except ValueError:
4667 except ValueError:
4668 return dict()
4668 return dict()
4669
4669
4670 def _as_raw(self, val):
4670 def _as_raw(self, val):
4671 if hasattr(val, 'de_coerce'):
4671 if hasattr(val, 'de_coerce'):
4672 val = val.de_coerce()
4672 val = val.de_coerce()
4673 if val:
4673 if val:
4674 val = json.dumps(val)
4674 val = json.dumps(val)
4675
4675
4676 return val
4676 return val
4677
4677
4678 @property
4678 @property
4679 def schedule_definition_raw(self):
4679 def schedule_definition_raw(self):
4680 return self._as_raw(self.schedule_definition)
4680 return self._as_raw(self.schedule_definition)
4681
4681
4682 @property
4682 @property
4683 def args_raw(self):
4683 def args_raw(self):
4684 return self._as_raw(self.task_args)
4684 return self._as_raw(self.task_args)
4685
4685
4686 @property
4686 @property
4687 def kwargs_raw(self):
4687 def kwargs_raw(self):
4688 return self._as_raw(self.task_kwargs)
4688 return self._as_raw(self.task_kwargs)
4689
4689
4690 def __repr__(self):
4690 def __repr__(self):
4691 return '<DB:ScheduleEntry({}:{})>'.format(
4691 return '<DB:ScheduleEntry({}:{})>'.format(
4692 self.schedule_entry_id, self.schedule_name)
4692 self.schedule_entry_id, self.schedule_name)
4693
4693
4694
4694
4695 @event.listens_for(ScheduleEntry, 'before_update')
4695 @event.listens_for(ScheduleEntry, 'before_update')
4696 def update_task_uid(mapper, connection, target):
4696 def update_task_uid(mapper, connection, target):
4697 target.task_uid = ScheduleEntry.get_uid(target)
4697 target.task_uid = ScheduleEntry.get_uid(target)
4698
4698
4699
4699
4700 @event.listens_for(ScheduleEntry, 'before_insert')
4700 @event.listens_for(ScheduleEntry, 'before_insert')
4701 def set_task_uid(mapper, connection, target):
4701 def set_task_uid(mapper, connection, target):
4702 target.task_uid = ScheduleEntry.get_uid(target)
4702 target.task_uid = ScheduleEntry.get_uid(target)
4703
4703
4704
4704
4705 class _BaseBranchPerms(BaseModel):
4705 class _BaseBranchPerms(BaseModel):
4706 @classmethod
4706 @classmethod
4707 def compute_hash(cls, value):
4707 def compute_hash(cls, value):
4708 return sha1_safe(value)
4708 return sha1_safe(value)
4709
4709
4710 @hybrid_property
4710 @hybrid_property
4711 def branch_pattern(self):
4711 def branch_pattern(self):
4712 return self._branch_pattern or '*'
4712 return self._branch_pattern or '*'
4713
4713
4714 @hybrid_property
4714 @hybrid_property
4715 def branch_hash(self):
4715 def branch_hash(self):
4716 return self._branch_hash
4716 return self._branch_hash
4717
4717
4718 def _validate_glob(self, value):
4718 def _validate_glob(self, value):
4719 re.compile('^' + glob2re(value) + '$')
4719 re.compile('^' + glob2re(value) + '$')
4720
4720
4721 @branch_pattern.setter
4721 @branch_pattern.setter
4722 def branch_pattern(self, value):
4722 def branch_pattern(self, value):
4723 self._validate_glob(value)
4723 self._validate_glob(value)
4724 self._branch_pattern = value or '*'
4724 self._branch_pattern = value or '*'
4725 # set the Hash when setting the branch pattern
4725 # set the Hash when setting the branch pattern
4726 self._branch_hash = self.compute_hash(self._branch_pattern)
4726 self._branch_hash = self.compute_hash(self._branch_pattern)
4727
4727
4728 def matches(self, branch):
4728 def matches(self, branch):
4729 """
4729 """
4730 Check if this the branch matches entry
4730 Check if this the branch matches entry
4731
4731
4732 :param branch: branch name for the commit
4732 :param branch: branch name for the commit
4733 """
4733 """
4734
4734
4735 branch = branch or ''
4735 branch = branch or ''
4736
4736
4737 branch_matches = True
4737 branch_matches = True
4738 if branch:
4738 if branch:
4739 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4739 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4740 branch_matches = bool(branch_regex.search(branch))
4740 branch_matches = bool(branch_regex.search(branch))
4741
4741
4742 return branch_matches
4742 return branch_matches
4743
4743
4744
4744
4745 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4745 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4746 __tablename__ = 'user_to_repo_branch_permissions'
4746 __tablename__ = 'user_to_repo_branch_permissions'
4747 __table_args__ = (
4747 __table_args__ = (
4748 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4748 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4749 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4749 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4750 )
4750 )
4751
4751
4752 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4752 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4753
4753
4754 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4754 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4755 repo = relationship('Repository', backref='user_branch_perms')
4755 repo = relationship('Repository', backref='user_branch_perms')
4756
4756
4757 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4757 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4758 permission = relationship('Permission')
4758 permission = relationship('Permission')
4759
4759
4760 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4760 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4761 user_repo_to_perm = relationship('UserRepoToPerm')
4761 user_repo_to_perm = relationship('UserRepoToPerm')
4762
4762
4763 rule_order = Column('rule_order', Integer(), nullable=False)
4763 rule_order = Column('rule_order', Integer(), nullable=False)
4764 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4764 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4765 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4765 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4766
4766
4767 def __unicode__(self):
4767 def __unicode__(self):
4768 return u'<UserBranchPermission(%s => %r)>' % (
4768 return u'<UserBranchPermission(%s => %r)>' % (
4769 self.user_repo_to_perm, self.branch_pattern)
4769 self.user_repo_to_perm, self.branch_pattern)
4770
4770
4771
4771
4772 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4772 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4773 __tablename__ = 'user_group_to_repo_branch_permissions'
4773 __tablename__ = 'user_group_to_repo_branch_permissions'
4774 __table_args__ = (
4774 __table_args__ = (
4775 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4775 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4776 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4776 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4777 )
4777 )
4778
4778
4779 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4779 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4780
4780
4781 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4781 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4782 repo = relationship('Repository', backref='user_group_branch_perms')
4782 repo = relationship('Repository', backref='user_group_branch_perms')
4783
4783
4784 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4784 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4785 permission = relationship('Permission')
4785 permission = relationship('Permission')
4786
4786
4787 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)
4787 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
4788 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4788 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4789
4789
4790 rule_order = Column('rule_order', Integer(), nullable=False)
4790 rule_order = Column('rule_order', Integer(), nullable=False)
4791 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4791 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4792 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4792 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4793
4793
4794 def __unicode__(self):
4794 def __unicode__(self):
4795 return u'<UserBranchPermission(%s => %r)>' % (
4795 return u'<UserBranchPermission(%s => %r)>' % (
4796 self.user_group_repo_to_perm, self.branch_pattern)
4796 self.user_group_repo_to_perm, self.branch_pattern)
4797
4797
4798
4798
4799 class UserBookmark(Base, BaseModel):
4799 class UserBookmark(Base, BaseModel):
4800 __tablename__ = 'user_bookmarks'
4800 __tablename__ = 'user_bookmarks'
4801 __table_args__ = (
4801 __table_args__ = (
4802 UniqueConstraint('user_id', 'bookmark_repo_id'),
4802 UniqueConstraint('user_id', 'bookmark_repo_id'),
4803 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
4803 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
4804 UniqueConstraint('user_id', 'bookmark_position'),
4804 UniqueConstraint('user_id', 'bookmark_position'),
4805 base_table_args
4805 base_table_args
4806 )
4806 )
4807
4807
4808 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
4808 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
4809 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
4809 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
4810 position = Column("bookmark_position", Integer(), nullable=False)
4810 position = Column("bookmark_position", Integer(), nullable=False)
4811 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
4811 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
4812 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
4812 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
4813 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4813 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4814
4814
4815 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
4815 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
4816 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
4816 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
4817
4817
4818 user = relationship("User")
4818 user = relationship("User")
4819
4819
4820 repository = relationship("Repository")
4820 repository = relationship("Repository")
4821 repository_group = relationship("RepoGroup")
4821 repository_group = relationship("RepoGroup")
4822
4822
4823
4823
4824 class DbMigrateVersion(Base, BaseModel):
4824 class DbMigrateVersion(Base, BaseModel):
4825 __tablename__ = 'db_migrate_version'
4825 __tablename__ = 'db_migrate_version'
4826 __table_args__ = (
4826 __table_args__ = (
4827 base_table_args,
4827 base_table_args,
4828 )
4828 )
4829
4829
4830 repository_id = Column('repository_id', String(250), primary_key=True)
4830 repository_id = Column('repository_id', String(250), primary_key=True)
4831 repository_path = Column('repository_path', Text)
4831 repository_path = Column('repository_path', Text)
4832 version = Column('version', Integer)
4832 version = Column('version', Integer)
4833
4833
4834 @classmethod
4834 @classmethod
4835 def set_version(cls, version):
4835 def set_version(cls, version):
4836 """
4836 """
4837 Helper for forcing a different version, usually for debugging purposes via ishell.
4837 Helper for forcing a different version, usually for debugging purposes via ishell.
4838 """
4838 """
4839 ver = DbMigrateVersion.query().first()
4839 ver = DbMigrateVersion.query().first()
4840 ver.version = version
4840 ver.version = version
4841 Session().commit()
4841 Session().commit()
4842
4842
4843
4843
4844 class DbSession(Base, BaseModel):
4844 class DbSession(Base, BaseModel):
4845 __tablename__ = 'db_session'
4845 __tablename__ = 'db_session'
4846 __table_args__ = (
4846 __table_args__ = (
4847 base_table_args,
4847 base_table_args,
4848 )
4848 )
4849
4849
4850 def __repr__(self):
4850 def __repr__(self):
4851 return '<DB:DbSession({})>'.format(self.id)
4851 return '<DB:DbSession({})>'.format(self.id)
4852
4852
4853 id = Column('id', Integer())
4853 id = Column('id', Integer())
4854 namespace = Column('namespace', String(255), primary_key=True)
4854 namespace = Column('namespace', String(255), primary_key=True)
4855 accessed = Column('accessed', DateTime, nullable=False)
4855 accessed = Column('accessed', DateTime, nullable=False)
4856 created = Column('created', DateTime, nullable=False)
4856 created = Column('created', DateTime, nullable=False)
4857 data = Column('data', PickleType, nullable=False)
4857 data = Column('data', PickleType, nullable=False)
@@ -1,4932 +1,4932 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import hashlib
28 import hashlib
29 import logging
29 import logging
30 import datetime
30 import datetime
31 import warnings
31 import warnings
32 import ipaddress
32 import ipaddress
33 import functools
33 import functools
34 import traceback
34 import traceback
35 import collections
35 import collections
36
36
37 from sqlalchemy import (
37 from sqlalchemy import (
38 or_, and_, not_, func, TypeDecorator, event,
38 or_, and_, not_, func, TypeDecorator, event,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 Text, Float, PickleType)
41 Text, Float, PickleType)
42 from sqlalchemy.sql.expression import true, false
42 from sqlalchemy.sql.expression import true, false
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
43 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
44 from sqlalchemy.orm import (
44 from sqlalchemy.orm import (
45 relationship, joinedload, class_mapper, validates, aliased)
45 relationship, joinedload, class_mapper, validates, aliased)
46 from sqlalchemy.ext.declarative import declared_attr
46 from sqlalchemy.ext.declarative import declared_attr
47 from sqlalchemy.ext.hybrid import hybrid_property
47 from sqlalchemy.ext.hybrid import hybrid_property
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
48 from sqlalchemy.exc import IntegrityError # pragma: no cover
49 from sqlalchemy.dialects.mysql import LONGTEXT
49 from sqlalchemy.dialects.mysql import LONGTEXT
50 from zope.cachedescriptors.property import Lazy as LazyProperty
50 from zope.cachedescriptors.property import Lazy as LazyProperty
51 from pyramid import compat
51 from pyramid import compat
52 from pyramid.threadlocal import get_current_request
52 from pyramid.threadlocal import get_current_request
53
53
54 from rhodecode.translation import _
54 from rhodecode.translation import _
55 from rhodecode.lib.vcs import get_vcs_instance
55 from rhodecode.lib.vcs import get_vcs_instance
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
56 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
57 from rhodecode.lib.utils2 import (
57 from rhodecode.lib.utils2 import (
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
58 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
59 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
60 glob2re, StrictAttributeDict, cleaned_uri)
60 glob2re, StrictAttributeDict, cleaned_uri)
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
61 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
62 JsonRaw
62 JsonRaw
63 from rhodecode.lib.ext_json import json
63 from rhodecode.lib.ext_json import json
64 from rhodecode.lib.caching_query import FromCache
64 from rhodecode.lib.caching_query import FromCache
65 from rhodecode.lib.encrypt import AESCipher
65 from rhodecode.lib.encrypt import AESCipher
66
66
67 from rhodecode.model.meta import Base, Session
67 from rhodecode.model.meta import Base, Session
68
68
69 URL_SEP = '/'
69 URL_SEP = '/'
70 log = logging.getLogger(__name__)
70 log = logging.getLogger(__name__)
71
71
72 # =============================================================================
72 # =============================================================================
73 # BASE CLASSES
73 # BASE CLASSES
74 # =============================================================================
74 # =============================================================================
75
75
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
76 # this is propagated from .ini file rhodecode.encrypted_values.secret or
77 # beaker.session.secret if first is not set.
77 # beaker.session.secret if first is not set.
78 # and initialized at environment.py
78 # and initialized at environment.py
79 ENCRYPTION_KEY = None
79 ENCRYPTION_KEY = None
80
80
81 # used to sort permissions by types, '#' used here is not allowed to be in
81 # used to sort permissions by types, '#' used here is not allowed to be in
82 # usernames, and it's very early in sorted string.printable table.
82 # usernames, and it's very early in sorted string.printable table.
83 PERMISSION_TYPE_SORT = {
83 PERMISSION_TYPE_SORT = {
84 'admin': '####',
84 'admin': '####',
85 'write': '###',
85 'write': '###',
86 'read': '##',
86 'read': '##',
87 'none': '#',
87 'none': '#',
88 }
88 }
89
89
90
90
91 def display_user_sort(obj):
91 def display_user_sort(obj):
92 """
92 """
93 Sort function used to sort permissions in .permissions() function of
93 Sort function used to sort permissions in .permissions() function of
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
94 Repository, RepoGroup, UserGroup. Also it put the default user in front
95 of all other resources
95 of all other resources
96 """
96 """
97
97
98 if obj.username == User.DEFAULT_USER:
98 if obj.username == User.DEFAULT_USER:
99 return '#####'
99 return '#####'
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
100 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
101 return prefix + obj.username
101 return prefix + obj.username
102
102
103
103
104 def display_user_group_sort(obj):
104 def display_user_group_sort(obj):
105 """
105 """
106 Sort function used to sort permissions in .permissions() function of
106 Sort function used to sort permissions in .permissions() function of
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
107 Repository, RepoGroup, UserGroup. Also it put the default user in front
108 of all other resources
108 of all other resources
109 """
109 """
110
110
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
111 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
112 return prefix + obj.users_group_name
112 return prefix + obj.users_group_name
113
113
114
114
115 def _hash_key(k):
115 def _hash_key(k):
116 return sha1_safe(k)
116 return sha1_safe(k)
117
117
118
118
119 def in_filter_generator(qry, items, limit=500):
119 def in_filter_generator(qry, items, limit=500):
120 """
120 """
121 Splits IN() into multiple with OR
121 Splits IN() into multiple with OR
122 e.g.::
122 e.g.::
123 cnt = Repository.query().filter(
123 cnt = Repository.query().filter(
124 or_(
124 or_(
125 *in_filter_generator(Repository.repo_id, range(100000))
125 *in_filter_generator(Repository.repo_id, range(100000))
126 )).count()
126 )).count()
127 """
127 """
128 if not items:
128 if not items:
129 # empty list will cause empty query which might cause security issues
129 # empty list will cause empty query which might cause security issues
130 # this can lead to hidden unpleasant results
130 # this can lead to hidden unpleasant results
131 items = [-1]
131 items = [-1]
132
132
133 parts = []
133 parts = []
134 for chunk in xrange(0, len(items), limit):
134 for chunk in xrange(0, len(items), limit):
135 parts.append(
135 parts.append(
136 qry.in_(items[chunk: chunk + limit])
136 qry.in_(items[chunk: chunk + limit])
137 )
137 )
138
138
139 return parts
139 return parts
140
140
141
141
142 base_table_args = {
142 base_table_args = {
143 'extend_existing': True,
143 'extend_existing': True,
144 'mysql_engine': 'InnoDB',
144 'mysql_engine': 'InnoDB',
145 'mysql_charset': 'utf8',
145 'mysql_charset': 'utf8',
146 'sqlite_autoincrement': True
146 'sqlite_autoincrement': True
147 }
147 }
148
148
149
149
150 class EncryptedTextValue(TypeDecorator):
150 class EncryptedTextValue(TypeDecorator):
151 """
151 """
152 Special column for encrypted long text data, use like::
152 Special column for encrypted long text data, use like::
153
153
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
154 value = Column("encrypted_value", EncryptedValue(), nullable=False)
155
155
156 This column is intelligent so if value is in unencrypted form it return
156 This column is intelligent so if value is in unencrypted form it return
157 unencrypted form, but on save it always encrypts
157 unencrypted form, but on save it always encrypts
158 """
158 """
159 impl = Text
159 impl = Text
160
160
161 def process_bind_param(self, value, dialect):
161 def process_bind_param(self, value, dialect):
162 if not value:
162 if not value:
163 return value
163 return value
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
164 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
165 # protect against double encrypting if someone manually starts
165 # protect against double encrypting if someone manually starts
166 # doing
166 # doing
167 raise ValueError('value needs to be in unencrypted format, ie. '
167 raise ValueError('value needs to be in unencrypted format, ie. '
168 'not starting with enc$aes')
168 'not starting with enc$aes')
169 return 'enc$aes_hmac$%s' % AESCipher(
169 return 'enc$aes_hmac$%s' % AESCipher(
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
170 ENCRYPTION_KEY, hmac=True).encrypt(value)
171
171
172 def process_result_value(self, value, dialect):
172 def process_result_value(self, value, dialect):
173 import rhodecode
173 import rhodecode
174
174
175 if not value:
175 if not value:
176 return value
176 return value
177
177
178 parts = value.split('$', 3)
178 parts = value.split('$', 3)
179 if not len(parts) == 3:
179 if not len(parts) == 3:
180 # probably not encrypted values
180 # probably not encrypted values
181 return value
181 return value
182 else:
182 else:
183 if parts[0] != 'enc':
183 if parts[0] != 'enc':
184 # parts ok but without our header ?
184 # parts ok but without our header ?
185 return value
185 return value
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
186 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
187 'rhodecode.encrypted_values.strict') or True)
187 'rhodecode.encrypted_values.strict') or True)
188 # at that stage we know it's our encryption
188 # at that stage we know it's our encryption
189 if parts[1] == 'aes':
189 if parts[1] == 'aes':
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
190 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
191 elif parts[1] == 'aes_hmac':
191 elif parts[1] == 'aes_hmac':
192 decrypted_data = AESCipher(
192 decrypted_data = AESCipher(
193 ENCRYPTION_KEY, hmac=True,
193 ENCRYPTION_KEY, hmac=True,
194 strict_verification=enc_strict_mode).decrypt(parts[2])
194 strict_verification=enc_strict_mode).decrypt(parts[2])
195 else:
195 else:
196 raise ValueError(
196 raise ValueError(
197 'Encryption type part is wrong, must be `aes` '
197 'Encryption type part is wrong, must be `aes` '
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
198 'or `aes_hmac`, got `%s` instead' % (parts[1]))
199 return decrypted_data
199 return decrypted_data
200
200
201
201
202 class BaseModel(object):
202 class BaseModel(object):
203 """
203 """
204 Base Model for all classes
204 Base Model for all classes
205 """
205 """
206
206
207 @classmethod
207 @classmethod
208 def _get_keys(cls):
208 def _get_keys(cls):
209 """return column names for this model """
209 """return column names for this model """
210 return class_mapper(cls).c.keys()
210 return class_mapper(cls).c.keys()
211
211
212 def get_dict(self):
212 def get_dict(self):
213 """
213 """
214 return dict with keys and values corresponding
214 return dict with keys and values corresponding
215 to this model data """
215 to this model data """
216
216
217 d = {}
217 d = {}
218 for k in self._get_keys():
218 for k in self._get_keys():
219 d[k] = getattr(self, k)
219 d[k] = getattr(self, k)
220
220
221 # also use __json__() if present to get additional fields
221 # also use __json__() if present to get additional fields
222 _json_attr = getattr(self, '__json__', None)
222 _json_attr = getattr(self, '__json__', None)
223 if _json_attr:
223 if _json_attr:
224 # update with attributes from __json__
224 # update with attributes from __json__
225 if callable(_json_attr):
225 if callable(_json_attr):
226 _json_attr = _json_attr()
226 _json_attr = _json_attr()
227 for k, val in _json_attr.iteritems():
227 for k, val in _json_attr.iteritems():
228 d[k] = val
228 d[k] = val
229 return d
229 return d
230
230
231 def get_appstruct(self):
231 def get_appstruct(self):
232 """return list with keys and values tuples corresponding
232 """return list with keys and values tuples corresponding
233 to this model data """
233 to this model data """
234
234
235 lst = []
235 lst = []
236 for k in self._get_keys():
236 for k in self._get_keys():
237 lst.append((k, getattr(self, k),))
237 lst.append((k, getattr(self, k),))
238 return lst
238 return lst
239
239
240 def populate_obj(self, populate_dict):
240 def populate_obj(self, populate_dict):
241 """populate model with data from given populate_dict"""
241 """populate model with data from given populate_dict"""
242
242
243 for k in self._get_keys():
243 for k in self._get_keys():
244 if k in populate_dict:
244 if k in populate_dict:
245 setattr(self, k, populate_dict[k])
245 setattr(self, k, populate_dict[k])
246
246
247 @classmethod
247 @classmethod
248 def query(cls):
248 def query(cls):
249 return Session().query(cls)
249 return Session().query(cls)
250
250
251 @classmethod
251 @classmethod
252 def get(cls, id_):
252 def get(cls, id_):
253 if id_:
253 if id_:
254 return cls.query().get(id_)
254 return cls.query().get(id_)
255
255
256 @classmethod
256 @classmethod
257 def get_or_404(cls, id_):
257 def get_or_404(cls, id_):
258 from pyramid.httpexceptions import HTTPNotFound
258 from pyramid.httpexceptions import HTTPNotFound
259
259
260 try:
260 try:
261 id_ = int(id_)
261 id_ = int(id_)
262 except (TypeError, ValueError):
262 except (TypeError, ValueError):
263 raise HTTPNotFound()
263 raise HTTPNotFound()
264
264
265 res = cls.query().get(id_)
265 res = cls.query().get(id_)
266 if not res:
266 if not res:
267 raise HTTPNotFound()
267 raise HTTPNotFound()
268 return res
268 return res
269
269
270 @classmethod
270 @classmethod
271 def getAll(cls):
271 def getAll(cls):
272 # deprecated and left for backward compatibility
272 # deprecated and left for backward compatibility
273 return cls.get_all()
273 return cls.get_all()
274
274
275 @classmethod
275 @classmethod
276 def get_all(cls):
276 def get_all(cls):
277 return cls.query().all()
277 return cls.query().all()
278
278
279 @classmethod
279 @classmethod
280 def delete(cls, id_):
280 def delete(cls, id_):
281 obj = cls.query().get(id_)
281 obj = cls.query().get(id_)
282 Session().delete(obj)
282 Session().delete(obj)
283
283
284 @classmethod
284 @classmethod
285 def identity_cache(cls, session, attr_name, value):
285 def identity_cache(cls, session, attr_name, value):
286 exist_in_session = []
286 exist_in_session = []
287 for (item_cls, pkey), instance in session.identity_map.items():
287 for (item_cls, pkey), instance in session.identity_map.items():
288 if cls == item_cls and getattr(instance, attr_name) == value:
288 if cls == item_cls and getattr(instance, attr_name) == value:
289 exist_in_session.append(instance)
289 exist_in_session.append(instance)
290 if exist_in_session:
290 if exist_in_session:
291 if len(exist_in_session) == 1:
291 if len(exist_in_session) == 1:
292 return exist_in_session[0]
292 return exist_in_session[0]
293 log.exception(
293 log.exception(
294 'multiple objects with attr %s and '
294 'multiple objects with attr %s and '
295 'value %s found with same name: %r',
295 'value %s found with same name: %r',
296 attr_name, value, exist_in_session)
296 attr_name, value, exist_in_session)
297
297
298 def __repr__(self):
298 def __repr__(self):
299 if hasattr(self, '__unicode__'):
299 if hasattr(self, '__unicode__'):
300 # python repr needs to return str
300 # python repr needs to return str
301 try:
301 try:
302 return safe_str(self.__unicode__())
302 return safe_str(self.__unicode__())
303 except UnicodeDecodeError:
303 except UnicodeDecodeError:
304 pass
304 pass
305 return '<DB:%s>' % (self.__class__.__name__)
305 return '<DB:%s>' % (self.__class__.__name__)
306
306
307
307
308 class RhodeCodeSetting(Base, BaseModel):
308 class RhodeCodeSetting(Base, BaseModel):
309 __tablename__ = 'rhodecode_settings'
309 __tablename__ = 'rhodecode_settings'
310 __table_args__ = (
310 __table_args__ = (
311 UniqueConstraint('app_settings_name'),
311 UniqueConstraint('app_settings_name'),
312 base_table_args
312 base_table_args
313 )
313 )
314
314
315 SETTINGS_TYPES = {
315 SETTINGS_TYPES = {
316 'str': safe_str,
316 'str': safe_str,
317 'int': safe_int,
317 'int': safe_int,
318 'unicode': safe_unicode,
318 'unicode': safe_unicode,
319 'bool': str2bool,
319 'bool': str2bool,
320 'list': functools.partial(aslist, sep=',')
320 'list': functools.partial(aslist, sep=',')
321 }
321 }
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
322 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
323 GLOBAL_CONF_KEY = 'app_settings'
323 GLOBAL_CONF_KEY = 'app_settings'
324
324
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
325 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
326 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
327 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
328 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
329
329
330 def __init__(self, key='', val='', type='unicode'):
330 def __init__(self, key='', val='', type='unicode'):
331 self.app_settings_name = key
331 self.app_settings_name = key
332 self.app_settings_type = type
332 self.app_settings_type = type
333 self.app_settings_value = val
333 self.app_settings_value = val
334
334
335 @validates('_app_settings_value')
335 @validates('_app_settings_value')
336 def validate_settings_value(self, key, val):
336 def validate_settings_value(self, key, val):
337 assert type(val) == unicode
337 assert type(val) == unicode
338 return val
338 return val
339
339
340 @hybrid_property
340 @hybrid_property
341 def app_settings_value(self):
341 def app_settings_value(self):
342 v = self._app_settings_value
342 v = self._app_settings_value
343 _type = self.app_settings_type
343 _type = self.app_settings_type
344 if _type:
344 if _type:
345 _type = self.app_settings_type.split('.')[0]
345 _type = self.app_settings_type.split('.')[0]
346 # decode the encrypted value
346 # decode the encrypted value
347 if 'encrypted' in self.app_settings_type:
347 if 'encrypted' in self.app_settings_type:
348 cipher = EncryptedTextValue()
348 cipher = EncryptedTextValue()
349 v = safe_unicode(cipher.process_result_value(v, None))
349 v = safe_unicode(cipher.process_result_value(v, None))
350
350
351 converter = self.SETTINGS_TYPES.get(_type) or \
351 converter = self.SETTINGS_TYPES.get(_type) or \
352 self.SETTINGS_TYPES['unicode']
352 self.SETTINGS_TYPES['unicode']
353 return converter(v)
353 return converter(v)
354
354
355 @app_settings_value.setter
355 @app_settings_value.setter
356 def app_settings_value(self, val):
356 def app_settings_value(self, val):
357 """
357 """
358 Setter that will always make sure we use unicode in app_settings_value
358 Setter that will always make sure we use unicode in app_settings_value
359
359
360 :param val:
360 :param val:
361 """
361 """
362 val = safe_unicode(val)
362 val = safe_unicode(val)
363 # encode the encrypted value
363 # encode the encrypted value
364 if 'encrypted' in self.app_settings_type:
364 if 'encrypted' in self.app_settings_type:
365 cipher = EncryptedTextValue()
365 cipher = EncryptedTextValue()
366 val = safe_unicode(cipher.process_bind_param(val, None))
366 val = safe_unicode(cipher.process_bind_param(val, None))
367 self._app_settings_value = val
367 self._app_settings_value = val
368
368
369 @hybrid_property
369 @hybrid_property
370 def app_settings_type(self):
370 def app_settings_type(self):
371 return self._app_settings_type
371 return self._app_settings_type
372
372
373 @app_settings_type.setter
373 @app_settings_type.setter
374 def app_settings_type(self, val):
374 def app_settings_type(self, val):
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
375 if val.split('.')[0] not in self.SETTINGS_TYPES:
376 raise Exception('type must be one of %s got %s'
376 raise Exception('type must be one of %s got %s'
377 % (self.SETTINGS_TYPES.keys(), val))
377 % (self.SETTINGS_TYPES.keys(), val))
378 self._app_settings_type = val
378 self._app_settings_type = val
379
379
380 @classmethod
380 @classmethod
381 def get_by_prefix(cls, prefix):
381 def get_by_prefix(cls, prefix):
382 return RhodeCodeSetting.query()\
382 return RhodeCodeSetting.query()\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
383 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
384 .all()
384 .all()
385
385
386 def __unicode__(self):
386 def __unicode__(self):
387 return u"<%s('%s:%s[%s]')>" % (
387 return u"<%s('%s:%s[%s]')>" % (
388 self.__class__.__name__,
388 self.__class__.__name__,
389 self.app_settings_name, self.app_settings_value,
389 self.app_settings_name, self.app_settings_value,
390 self.app_settings_type
390 self.app_settings_type
391 )
391 )
392
392
393
393
394 class RhodeCodeUi(Base, BaseModel):
394 class RhodeCodeUi(Base, BaseModel):
395 __tablename__ = 'rhodecode_ui'
395 __tablename__ = 'rhodecode_ui'
396 __table_args__ = (
396 __table_args__ = (
397 UniqueConstraint('ui_key'),
397 UniqueConstraint('ui_key'),
398 base_table_args
398 base_table_args
399 )
399 )
400
400
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
401 HOOK_REPO_SIZE = 'changegroup.repo_size'
402 # HG
402 # HG
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
403 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
404 HOOK_PULL = 'outgoing.pull_logger'
404 HOOK_PULL = 'outgoing.pull_logger'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
405 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
406 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
407 HOOK_PUSH = 'changegroup.push_logger'
407 HOOK_PUSH = 'changegroup.push_logger'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
408 HOOK_PUSH_KEY = 'pushkey.key_push'
409
409
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
410 # TODO: johbo: Unify way how hooks are configured for git and hg,
411 # git part is currently hardcoded.
411 # git part is currently hardcoded.
412
412
413 # SVN PATTERNS
413 # SVN PATTERNS
414 SVN_BRANCH_ID = 'vcs_svn_branch'
414 SVN_BRANCH_ID = 'vcs_svn_branch'
415 SVN_TAG_ID = 'vcs_svn_tag'
415 SVN_TAG_ID = 'vcs_svn_tag'
416
416
417 ui_id = Column(
417 ui_id = Column(
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
418 "ui_id", Integer(), nullable=False, unique=True, default=None,
419 primary_key=True)
419 primary_key=True)
420 ui_section = Column(
420 ui_section = Column(
421 "ui_section", String(255), nullable=True, unique=None, default=None)
421 "ui_section", String(255), nullable=True, unique=None, default=None)
422 ui_key = Column(
422 ui_key = Column(
423 "ui_key", String(255), nullable=True, unique=None, default=None)
423 "ui_key", String(255), nullable=True, unique=None, default=None)
424 ui_value = Column(
424 ui_value = Column(
425 "ui_value", String(255), nullable=True, unique=None, default=None)
425 "ui_value", String(255), nullable=True, unique=None, default=None)
426 ui_active = Column(
426 ui_active = Column(
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
427 "ui_active", Boolean(), nullable=True, unique=None, default=True)
428
428
429 def __repr__(self):
429 def __repr__(self):
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
430 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
431 self.ui_key, self.ui_value)
431 self.ui_key, self.ui_value)
432
432
433
433
434 class RepoRhodeCodeSetting(Base, BaseModel):
434 class RepoRhodeCodeSetting(Base, BaseModel):
435 __tablename__ = 'repo_rhodecode_settings'
435 __tablename__ = 'repo_rhodecode_settings'
436 __table_args__ = (
436 __table_args__ = (
437 UniqueConstraint(
437 UniqueConstraint(
438 'app_settings_name', 'repository_id',
438 'app_settings_name', 'repository_id',
439 name='uq_repo_rhodecode_setting_name_repo_id'),
439 name='uq_repo_rhodecode_setting_name_repo_id'),
440 base_table_args
440 base_table_args
441 )
441 )
442
442
443 repository_id = Column(
443 repository_id = Column(
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
444 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
445 nullable=False)
445 nullable=False)
446 app_settings_id = Column(
446 app_settings_id = Column(
447 "app_settings_id", Integer(), nullable=False, unique=True,
447 "app_settings_id", Integer(), nullable=False, unique=True,
448 default=None, primary_key=True)
448 default=None, primary_key=True)
449 app_settings_name = Column(
449 app_settings_name = Column(
450 "app_settings_name", String(255), nullable=True, unique=None,
450 "app_settings_name", String(255), nullable=True, unique=None,
451 default=None)
451 default=None)
452 _app_settings_value = Column(
452 _app_settings_value = Column(
453 "app_settings_value", String(4096), nullable=True, unique=None,
453 "app_settings_value", String(4096), nullable=True, unique=None,
454 default=None)
454 default=None)
455 _app_settings_type = Column(
455 _app_settings_type = Column(
456 "app_settings_type", String(255), nullable=True, unique=None,
456 "app_settings_type", String(255), nullable=True, unique=None,
457 default=None)
457 default=None)
458
458
459 repository = relationship('Repository')
459 repository = relationship('Repository')
460
460
461 def __init__(self, repository_id, key='', val='', type='unicode'):
461 def __init__(self, repository_id, key='', val='', type='unicode'):
462 self.repository_id = repository_id
462 self.repository_id = repository_id
463 self.app_settings_name = key
463 self.app_settings_name = key
464 self.app_settings_type = type
464 self.app_settings_type = type
465 self.app_settings_value = val
465 self.app_settings_value = val
466
466
467 @validates('_app_settings_value')
467 @validates('_app_settings_value')
468 def validate_settings_value(self, key, val):
468 def validate_settings_value(self, key, val):
469 assert type(val) == unicode
469 assert type(val) == unicode
470 return val
470 return val
471
471
472 @hybrid_property
472 @hybrid_property
473 def app_settings_value(self):
473 def app_settings_value(self):
474 v = self._app_settings_value
474 v = self._app_settings_value
475 type_ = self.app_settings_type
475 type_ = self.app_settings_type
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
476 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
477 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
478 return converter(v)
478 return converter(v)
479
479
480 @app_settings_value.setter
480 @app_settings_value.setter
481 def app_settings_value(self, val):
481 def app_settings_value(self, val):
482 """
482 """
483 Setter that will always make sure we use unicode in app_settings_value
483 Setter that will always make sure we use unicode in app_settings_value
484
484
485 :param val:
485 :param val:
486 """
486 """
487 self._app_settings_value = safe_unicode(val)
487 self._app_settings_value = safe_unicode(val)
488
488
489 @hybrid_property
489 @hybrid_property
490 def app_settings_type(self):
490 def app_settings_type(self):
491 return self._app_settings_type
491 return self._app_settings_type
492
492
493 @app_settings_type.setter
493 @app_settings_type.setter
494 def app_settings_type(self, val):
494 def app_settings_type(self, val):
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
495 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
496 if val not in SETTINGS_TYPES:
496 if val not in SETTINGS_TYPES:
497 raise Exception('type must be one of %s got %s'
497 raise Exception('type must be one of %s got %s'
498 % (SETTINGS_TYPES.keys(), val))
498 % (SETTINGS_TYPES.keys(), val))
499 self._app_settings_type = val
499 self._app_settings_type = val
500
500
501 def __unicode__(self):
501 def __unicode__(self):
502 return u"<%s('%s:%s:%s[%s]')>" % (
502 return u"<%s('%s:%s:%s[%s]')>" % (
503 self.__class__.__name__, self.repository.repo_name,
503 self.__class__.__name__, self.repository.repo_name,
504 self.app_settings_name, self.app_settings_value,
504 self.app_settings_name, self.app_settings_value,
505 self.app_settings_type
505 self.app_settings_type
506 )
506 )
507
507
508
508
509 class RepoRhodeCodeUi(Base, BaseModel):
509 class RepoRhodeCodeUi(Base, BaseModel):
510 __tablename__ = 'repo_rhodecode_ui'
510 __tablename__ = 'repo_rhodecode_ui'
511 __table_args__ = (
511 __table_args__ = (
512 UniqueConstraint(
512 UniqueConstraint(
513 'repository_id', 'ui_section', 'ui_key',
513 'repository_id', 'ui_section', 'ui_key',
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
514 name='uq_repo_rhodecode_ui_repository_id_section_key'),
515 base_table_args
515 base_table_args
516 )
516 )
517
517
518 repository_id = Column(
518 repository_id = Column(
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
519 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
520 nullable=False)
520 nullable=False)
521 ui_id = Column(
521 ui_id = Column(
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
522 "ui_id", Integer(), nullable=False, unique=True, default=None,
523 primary_key=True)
523 primary_key=True)
524 ui_section = Column(
524 ui_section = Column(
525 "ui_section", String(255), nullable=True, unique=None, default=None)
525 "ui_section", String(255), nullable=True, unique=None, default=None)
526 ui_key = Column(
526 ui_key = Column(
527 "ui_key", String(255), nullable=True, unique=None, default=None)
527 "ui_key", String(255), nullable=True, unique=None, default=None)
528 ui_value = Column(
528 ui_value = Column(
529 "ui_value", String(255), nullable=True, unique=None, default=None)
529 "ui_value", String(255), nullable=True, unique=None, default=None)
530 ui_active = Column(
530 ui_active = Column(
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
531 "ui_active", Boolean(), nullable=True, unique=None, default=True)
532
532
533 repository = relationship('Repository')
533 repository = relationship('Repository')
534
534
535 def __repr__(self):
535 def __repr__(self):
536 return '<%s[%s:%s]%s=>%s]>' % (
536 return '<%s[%s:%s]%s=>%s]>' % (
537 self.__class__.__name__, self.repository.repo_name,
537 self.__class__.__name__, self.repository.repo_name,
538 self.ui_section, self.ui_key, self.ui_value)
538 self.ui_section, self.ui_key, self.ui_value)
539
539
540
540
541 class User(Base, BaseModel):
541 class User(Base, BaseModel):
542 __tablename__ = 'users'
542 __tablename__ = 'users'
543 __table_args__ = (
543 __table_args__ = (
544 UniqueConstraint('username'), UniqueConstraint('email'),
544 UniqueConstraint('username'), UniqueConstraint('email'),
545 Index('u_username_idx', 'username'),
545 Index('u_username_idx', 'username'),
546 Index('u_email_idx', 'email'),
546 Index('u_email_idx', 'email'),
547 base_table_args
547 base_table_args
548 )
548 )
549
549
550 DEFAULT_USER = 'default'
550 DEFAULT_USER = 'default'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
551 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
552 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
553
553
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
554 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
555 username = Column("username", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
556 password = Column("password", String(255), nullable=True, unique=None, default=None)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
557 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
558 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
559 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
560 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
561 _email = Column("email", String(255), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
562 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
563 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
564
564
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
565 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
566 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
567 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
568 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
569 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
570 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
571
571
572 user_log = relationship('UserLog')
572 user_log = relationship('UserLog')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
573 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
574
574
575 repositories = relationship('Repository')
575 repositories = relationship('Repository')
576 repository_groups = relationship('RepoGroup')
576 repository_groups = relationship('RepoGroup')
577 user_groups = relationship('UserGroup')
577 user_groups = relationship('UserGroup')
578
578
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
579 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
580 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
581
581
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
582 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
583 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
584 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
585
585
586 group_member = relationship('UserGroupMember', cascade='all')
586 group_member = relationship('UserGroupMember', cascade='all')
587
587
588 notifications = relationship('UserNotification', cascade='all')
588 notifications = relationship('UserNotification', cascade='all')
589 # notifications assigned to this user
589 # notifications assigned to this user
590 user_created_notifications = relationship('Notification', cascade='all')
590 user_created_notifications = relationship('Notification', cascade='all')
591 # comments created by this user
591 # comments created by this user
592 user_comments = relationship('ChangesetComment', cascade='all')
592 user_comments = relationship('ChangesetComment', cascade='all')
593 # user profile extra info
593 # user profile extra info
594 user_emails = relationship('UserEmailMap', cascade='all')
594 user_emails = relationship('UserEmailMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
595 user_ip_map = relationship('UserIpMap', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
596 user_auth_tokens = relationship('UserApiKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
597 user_ssh_keys = relationship('UserSshKeys', cascade='all')
598
598
599 # gists
599 # gists
600 user_gists = relationship('Gist', cascade='all')
600 user_gists = relationship('Gist', cascade='all')
601 # user pull requests
601 # user pull requests
602 user_pull_requests = relationship('PullRequest', cascade='all')
602 user_pull_requests = relationship('PullRequest', cascade='all')
603 # external identities
603 # external identities
604 extenal_identities = relationship(
604 extenal_identities = relationship(
605 'ExternalIdentity',
605 'ExternalIdentity',
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
606 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
607 cascade='all')
607 cascade='all')
608 # review rules
608 # review rules
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
609 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
610
610
611 def __unicode__(self):
611 def __unicode__(self):
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
612 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
613 self.user_id, self.username)
613 self.user_id, self.username)
614
614
615 @hybrid_property
615 @hybrid_property
616 def email(self):
616 def email(self):
617 return self._email
617 return self._email
618
618
619 @email.setter
619 @email.setter
620 def email(self, val):
620 def email(self, val):
621 self._email = val.lower() if val else None
621 self._email = val.lower() if val else None
622
622
623 @hybrid_property
623 @hybrid_property
624 def first_name(self):
624 def first_name(self):
625 from rhodecode.lib import helpers as h
625 from rhodecode.lib import helpers as h
626 if self.name:
626 if self.name:
627 return h.escape(self.name)
627 return h.escape(self.name)
628 return self.name
628 return self.name
629
629
630 @hybrid_property
630 @hybrid_property
631 def last_name(self):
631 def last_name(self):
632 from rhodecode.lib import helpers as h
632 from rhodecode.lib import helpers as h
633 if self.lastname:
633 if self.lastname:
634 return h.escape(self.lastname)
634 return h.escape(self.lastname)
635 return self.lastname
635 return self.lastname
636
636
637 @hybrid_property
637 @hybrid_property
638 def api_key(self):
638 def api_key(self):
639 """
639 """
640 Fetch if exist an auth-token with role ALL connected to this user
640 Fetch if exist an auth-token with role ALL connected to this user
641 """
641 """
642 user_auth_token = UserApiKeys.query()\
642 user_auth_token = UserApiKeys.query()\
643 .filter(UserApiKeys.user_id == self.user_id)\
643 .filter(UserApiKeys.user_id == self.user_id)\
644 .filter(or_(UserApiKeys.expires == -1,
644 .filter(or_(UserApiKeys.expires == -1,
645 UserApiKeys.expires >= time.time()))\
645 UserApiKeys.expires >= time.time()))\
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
646 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
647 if user_auth_token:
647 if user_auth_token:
648 user_auth_token = user_auth_token.api_key
648 user_auth_token = user_auth_token.api_key
649
649
650 return user_auth_token
650 return user_auth_token
651
651
652 @api_key.setter
652 @api_key.setter
653 def api_key(self, val):
653 def api_key(self, val):
654 # don't allow to set API key this is deprecated for now
654 # don't allow to set API key this is deprecated for now
655 self._api_key = None
655 self._api_key = None
656
656
657 @property
657 @property
658 def reviewer_pull_requests(self):
658 def reviewer_pull_requests(self):
659 return PullRequestReviewers.query() \
659 return PullRequestReviewers.query() \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
660 .options(joinedload(PullRequestReviewers.pull_request)) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
661 .filter(PullRequestReviewers.user_id == self.user_id) \
662 .all()
662 .all()
663
663
664 @property
664 @property
665 def firstname(self):
665 def firstname(self):
666 # alias for future
666 # alias for future
667 return self.name
667 return self.name
668
668
669 @property
669 @property
670 def emails(self):
670 def emails(self):
671 other = UserEmailMap.query()\
671 other = UserEmailMap.query()\
672 .filter(UserEmailMap.user == self) \
672 .filter(UserEmailMap.user == self) \
673 .order_by(UserEmailMap.email_id.asc()) \
673 .order_by(UserEmailMap.email_id.asc()) \
674 .all()
674 .all()
675 return [self.email] + [x.email for x in other]
675 return [self.email] + [x.email for x in other]
676
676
677 @property
677 @property
678 def auth_tokens(self):
678 def auth_tokens(self):
679 auth_tokens = self.get_auth_tokens()
679 auth_tokens = self.get_auth_tokens()
680 return [x.api_key for x in auth_tokens]
680 return [x.api_key for x in auth_tokens]
681
681
682 def get_auth_tokens(self):
682 def get_auth_tokens(self):
683 return UserApiKeys.query()\
683 return UserApiKeys.query()\
684 .filter(UserApiKeys.user == self)\
684 .filter(UserApiKeys.user == self)\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
685 .order_by(UserApiKeys.user_api_key_id.asc())\
686 .all()
686 .all()
687
687
688 @LazyProperty
688 @LazyProperty
689 def feed_token(self):
689 def feed_token(self):
690 return self.get_feed_token()
690 return self.get_feed_token()
691
691
692 def get_feed_token(self, cache=True):
692 def get_feed_token(self, cache=True):
693 feed_tokens = UserApiKeys.query()\
693 feed_tokens = UserApiKeys.query()\
694 .filter(UserApiKeys.user == self)\
694 .filter(UserApiKeys.user == self)\
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
695 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
696 if cache:
696 if cache:
697 feed_tokens = feed_tokens.options(
697 feed_tokens = feed_tokens.options(
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
698 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
699
699
700 feed_tokens = feed_tokens.all()
700 feed_tokens = feed_tokens.all()
701 if feed_tokens:
701 if feed_tokens:
702 return feed_tokens[0].api_key
702 return feed_tokens[0].api_key
703 return 'NO_FEED_TOKEN_AVAILABLE'
703 return 'NO_FEED_TOKEN_AVAILABLE'
704
704
705 @classmethod
705 @classmethod
706 def get(cls, user_id, cache=False):
706 def get(cls, user_id, cache=False):
707 if not user_id:
707 if not user_id:
708 return
708 return
709
709
710 user = cls.query()
710 user = cls.query()
711 if cache:
711 if cache:
712 user = user.options(
712 user = user.options(
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
713 FromCache("sql_cache_short", "get_users_%s" % user_id))
714 return user.get(user_id)
714 return user.get(user_id)
715
715
716 @classmethod
716 @classmethod
717 def extra_valid_auth_tokens(cls, user, role=None):
717 def extra_valid_auth_tokens(cls, user, role=None):
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
718 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
719 .filter(or_(UserApiKeys.expires == -1,
719 .filter(or_(UserApiKeys.expires == -1,
720 UserApiKeys.expires >= time.time()))
720 UserApiKeys.expires >= time.time()))
721 if role:
721 if role:
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
722 tokens = tokens.filter(or_(UserApiKeys.role == role,
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
723 UserApiKeys.role == UserApiKeys.ROLE_ALL))
724 return tokens.all()
724 return tokens.all()
725
725
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
726 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
727 from rhodecode.lib import auth
727 from rhodecode.lib import auth
728
728
729 log.debug('Trying to authenticate user: %s via auth-token, '
729 log.debug('Trying to authenticate user: %s via auth-token, '
730 'and roles: %s', self, roles)
730 'and roles: %s', self, roles)
731
731
732 if not auth_token:
732 if not auth_token:
733 return False
733 return False
734
734
735 crypto_backend = auth.crypto_backend()
735 crypto_backend = auth.crypto_backend()
736
736
737 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
737 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
738 tokens_q = UserApiKeys.query()\
738 tokens_q = UserApiKeys.query()\
739 .filter(UserApiKeys.user_id == self.user_id)\
739 .filter(UserApiKeys.user_id == self.user_id)\
740 .filter(or_(UserApiKeys.expires == -1,
740 .filter(or_(UserApiKeys.expires == -1,
741 UserApiKeys.expires >= time.time()))
741 UserApiKeys.expires >= time.time()))
742
742
743 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
743 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
744
744
745 plain_tokens = []
745 plain_tokens = []
746 hash_tokens = []
746 hash_tokens = []
747
747
748 user_tokens = tokens_q.all()
748 user_tokens = tokens_q.all()
749 log.debug('Found %s user tokens to check for authentication', len(user_tokens))
749 log.debug('Found %s user tokens to check for authentication', len(user_tokens))
750 for token in user_tokens:
750 for token in user_tokens:
751 log.debug('AUTH_TOKEN: checking if user token with id `%s` matches',
751 log.debug('AUTH_TOKEN: checking if user token with id `%s` matches',
752 token.user_api_key_id)
752 token.user_api_key_id)
753 # verify scope first, since it's way faster than hash calculation of
753 # verify scope first, since it's way faster than hash calculation of
754 # encrypted tokens
754 # encrypted tokens
755 if token.repo_id:
755 if token.repo_id:
756 # token has a scope, we need to verify it
756 # token has a scope, we need to verify it
757 if scope_repo_id != token.repo_id:
757 if scope_repo_id != token.repo_id:
758 log.debug(
758 log.debug(
759 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
759 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
760 'and calling scope is:%s, skipping further checks',
760 'and calling scope is:%s, skipping further checks',
761 token.repo, scope_repo_id)
761 token.repo, scope_repo_id)
762 # token has a scope, and it doesn't match, skip token
762 # token has a scope, and it doesn't match, skip token
763 continue
763 continue
764
764
765 if token.api_key.startswith(crypto_backend.ENC_PREF):
765 if token.api_key.startswith(crypto_backend.ENC_PREF):
766 hash_tokens.append(token.api_key)
766 hash_tokens.append(token.api_key)
767 else:
767 else:
768 plain_tokens.append(token.api_key)
768 plain_tokens.append(token.api_key)
769
769
770 is_plain_match = auth_token in plain_tokens
770 is_plain_match = auth_token in plain_tokens
771 if is_plain_match:
771 if is_plain_match:
772 return True
772 return True
773
773
774 for hashed in hash_tokens:
774 for hashed in hash_tokens:
775 # NOTE(marcink): this is expensive to calculate, but most secure
775 # NOTE(marcink): this is expensive to calculate, but most secure
776 match = crypto_backend.hash_check(auth_token, hashed)
776 match = crypto_backend.hash_check(auth_token, hashed)
777 if match:
777 if match:
778 return True
778 return True
779
779
780 return False
780 return False
781
781
782 @property
782 @property
783 def ip_addresses(self):
783 def ip_addresses(self):
784 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
784 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
785 return [x.ip_addr for x in ret]
785 return [x.ip_addr for x in ret]
786
786
787 @property
787 @property
788 def username_and_name(self):
788 def username_and_name(self):
789 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
789 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
790
790
791 @property
791 @property
792 def username_or_name_or_email(self):
792 def username_or_name_or_email(self):
793 full_name = self.full_name if self.full_name is not ' ' else None
793 full_name = self.full_name if self.full_name is not ' ' else None
794 return self.username or full_name or self.email
794 return self.username or full_name or self.email
795
795
796 @property
796 @property
797 def full_name(self):
797 def full_name(self):
798 return '%s %s' % (self.first_name, self.last_name)
798 return '%s %s' % (self.first_name, self.last_name)
799
799
800 @property
800 @property
801 def full_name_or_username(self):
801 def full_name_or_username(self):
802 return ('%s %s' % (self.first_name, self.last_name)
802 return ('%s %s' % (self.first_name, self.last_name)
803 if (self.first_name and self.last_name) else self.username)
803 if (self.first_name and self.last_name) else self.username)
804
804
805 @property
805 @property
806 def full_contact(self):
806 def full_contact(self):
807 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
807 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
808
808
809 @property
809 @property
810 def short_contact(self):
810 def short_contact(self):
811 return '%s %s' % (self.first_name, self.last_name)
811 return '%s %s' % (self.first_name, self.last_name)
812
812
813 @property
813 @property
814 def is_admin(self):
814 def is_admin(self):
815 return self.admin
815 return self.admin
816
816
817 def AuthUser(self, **kwargs):
817 def AuthUser(self, **kwargs):
818 """
818 """
819 Returns instance of AuthUser for this user
819 Returns instance of AuthUser for this user
820 """
820 """
821 from rhodecode.lib.auth import AuthUser
821 from rhodecode.lib.auth import AuthUser
822 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
822 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
823
823
824 @hybrid_property
824 @hybrid_property
825 def user_data(self):
825 def user_data(self):
826 if not self._user_data:
826 if not self._user_data:
827 return {}
827 return {}
828
828
829 try:
829 try:
830 return json.loads(self._user_data)
830 return json.loads(self._user_data)
831 except TypeError:
831 except TypeError:
832 return {}
832 return {}
833
833
834 @user_data.setter
834 @user_data.setter
835 def user_data(self, val):
835 def user_data(self, val):
836 if not isinstance(val, dict):
836 if not isinstance(val, dict):
837 raise Exception('user_data must be dict, got %s' % type(val))
837 raise Exception('user_data must be dict, got %s' % type(val))
838 try:
838 try:
839 self._user_data = json.dumps(val)
839 self._user_data = json.dumps(val)
840 except Exception:
840 except Exception:
841 log.error(traceback.format_exc())
841 log.error(traceback.format_exc())
842
842
843 @classmethod
843 @classmethod
844 def get_by_username(cls, username, case_insensitive=False,
844 def get_by_username(cls, username, case_insensitive=False,
845 cache=False, identity_cache=False):
845 cache=False, identity_cache=False):
846 session = Session()
846 session = Session()
847
847
848 if case_insensitive:
848 if case_insensitive:
849 q = cls.query().filter(
849 q = cls.query().filter(
850 func.lower(cls.username) == func.lower(username))
850 func.lower(cls.username) == func.lower(username))
851 else:
851 else:
852 q = cls.query().filter(cls.username == username)
852 q = cls.query().filter(cls.username == username)
853
853
854 if cache:
854 if cache:
855 if identity_cache:
855 if identity_cache:
856 val = cls.identity_cache(session, 'username', username)
856 val = cls.identity_cache(session, 'username', username)
857 if val:
857 if val:
858 return val
858 return val
859 else:
859 else:
860 cache_key = "get_user_by_name_%s" % _hash_key(username)
860 cache_key = "get_user_by_name_%s" % _hash_key(username)
861 q = q.options(
861 q = q.options(
862 FromCache("sql_cache_short", cache_key))
862 FromCache("sql_cache_short", cache_key))
863
863
864 return q.scalar()
864 return q.scalar()
865
865
866 @classmethod
866 @classmethod
867 def get_by_auth_token(cls, auth_token, cache=False):
867 def get_by_auth_token(cls, auth_token, cache=False):
868 q = UserApiKeys.query()\
868 q = UserApiKeys.query()\
869 .filter(UserApiKeys.api_key == auth_token)\
869 .filter(UserApiKeys.api_key == auth_token)\
870 .filter(or_(UserApiKeys.expires == -1,
870 .filter(or_(UserApiKeys.expires == -1,
871 UserApiKeys.expires >= time.time()))
871 UserApiKeys.expires >= time.time()))
872 if cache:
872 if cache:
873 q = q.options(
873 q = q.options(
874 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
874 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
875
875
876 match = q.first()
876 match = q.first()
877 if match:
877 if match:
878 return match.user
878 return match.user
879
879
880 @classmethod
880 @classmethod
881 def get_by_email(cls, email, case_insensitive=False, cache=False):
881 def get_by_email(cls, email, case_insensitive=False, cache=False):
882
882
883 if case_insensitive:
883 if case_insensitive:
884 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
884 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
885
885
886 else:
886 else:
887 q = cls.query().filter(cls.email == email)
887 q = cls.query().filter(cls.email == email)
888
888
889 email_key = _hash_key(email)
889 email_key = _hash_key(email)
890 if cache:
890 if cache:
891 q = q.options(
891 q = q.options(
892 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
892 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
893
893
894 ret = q.scalar()
894 ret = q.scalar()
895 if ret is None:
895 if ret is None:
896 q = UserEmailMap.query()
896 q = UserEmailMap.query()
897 # try fetching in alternate email map
897 # try fetching in alternate email map
898 if case_insensitive:
898 if case_insensitive:
899 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
899 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
900 else:
900 else:
901 q = q.filter(UserEmailMap.email == email)
901 q = q.filter(UserEmailMap.email == email)
902 q = q.options(joinedload(UserEmailMap.user))
902 q = q.options(joinedload(UserEmailMap.user))
903 if cache:
903 if cache:
904 q = q.options(
904 q = q.options(
905 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
905 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
906 ret = getattr(q.scalar(), 'user', None)
906 ret = getattr(q.scalar(), 'user', None)
907
907
908 return ret
908 return ret
909
909
910 @classmethod
910 @classmethod
911 def get_from_cs_author(cls, author):
911 def get_from_cs_author(cls, author):
912 """
912 """
913 Tries to get User objects out of commit author string
913 Tries to get User objects out of commit author string
914
914
915 :param author:
915 :param author:
916 """
916 """
917 from rhodecode.lib.helpers import email, author_name
917 from rhodecode.lib.helpers import email, author_name
918 # Valid email in the attribute passed, see if they're in the system
918 # Valid email in the attribute passed, see if they're in the system
919 _email = email(author)
919 _email = email(author)
920 if _email:
920 if _email:
921 user = cls.get_by_email(_email, case_insensitive=True)
921 user = cls.get_by_email(_email, case_insensitive=True)
922 if user:
922 if user:
923 return user
923 return user
924 # Maybe we can match by username?
924 # Maybe we can match by username?
925 _author = author_name(author)
925 _author = author_name(author)
926 user = cls.get_by_username(_author, case_insensitive=True)
926 user = cls.get_by_username(_author, case_insensitive=True)
927 if user:
927 if user:
928 return user
928 return user
929
929
930 def update_userdata(self, **kwargs):
930 def update_userdata(self, **kwargs):
931 usr = self
931 usr = self
932 old = usr.user_data
932 old = usr.user_data
933 old.update(**kwargs)
933 old.update(**kwargs)
934 usr.user_data = old
934 usr.user_data = old
935 Session().add(usr)
935 Session().add(usr)
936 log.debug('updated userdata with ', kwargs)
936 log.debug('updated userdata with ', kwargs)
937
937
938 def update_lastlogin(self):
938 def update_lastlogin(self):
939 """Update user lastlogin"""
939 """Update user lastlogin"""
940 self.last_login = datetime.datetime.now()
940 self.last_login = datetime.datetime.now()
941 Session().add(self)
941 Session().add(self)
942 log.debug('updated user %s lastlogin', self.username)
942 log.debug('updated user %s lastlogin', self.username)
943
943
944 def update_password(self, new_password):
944 def update_password(self, new_password):
945 from rhodecode.lib.auth import get_crypt_password
945 from rhodecode.lib.auth import get_crypt_password
946
946
947 self.password = get_crypt_password(new_password)
947 self.password = get_crypt_password(new_password)
948 Session().add(self)
948 Session().add(self)
949
949
950 @classmethod
950 @classmethod
951 def get_first_super_admin(cls):
951 def get_first_super_admin(cls):
952 user = User.query()\
952 user = User.query()\
953 .filter(User.admin == true()) \
953 .filter(User.admin == true()) \
954 .order_by(User.user_id.asc()) \
954 .order_by(User.user_id.asc()) \
955 .first()
955 .first()
956
956
957 if user is None:
957 if user is None:
958 raise Exception('FATAL: Missing administrative account!')
958 raise Exception('FATAL: Missing administrative account!')
959 return user
959 return user
960
960
961 @classmethod
961 @classmethod
962 def get_all_super_admins(cls, only_active=False):
962 def get_all_super_admins(cls, only_active=False):
963 """
963 """
964 Returns all admin accounts sorted by username
964 Returns all admin accounts sorted by username
965 """
965 """
966 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
966 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
967 if only_active:
967 if only_active:
968 qry = qry.filter(User.active == true())
968 qry = qry.filter(User.active == true())
969 return qry.all()
969 return qry.all()
970
970
971 @classmethod
971 @classmethod
972 def get_default_user(cls, cache=False, refresh=False):
972 def get_default_user(cls, cache=False, refresh=False):
973 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
973 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
974 if user is None:
974 if user is None:
975 raise Exception('FATAL: Missing default account!')
975 raise Exception('FATAL: Missing default account!')
976 if refresh:
976 if refresh:
977 # The default user might be based on outdated state which
977 # The default user might be based on outdated state which
978 # has been loaded from the cache.
978 # has been loaded from the cache.
979 # A call to refresh() ensures that the
979 # A call to refresh() ensures that the
980 # latest state from the database is used.
980 # latest state from the database is used.
981 Session().refresh(user)
981 Session().refresh(user)
982 return user
982 return user
983
983
984 def _get_default_perms(self, user, suffix=''):
984 def _get_default_perms(self, user, suffix=''):
985 from rhodecode.model.permission import PermissionModel
985 from rhodecode.model.permission import PermissionModel
986 return PermissionModel().get_default_perms(user.user_perms, suffix)
986 return PermissionModel().get_default_perms(user.user_perms, suffix)
987
987
988 def get_default_perms(self, suffix=''):
988 def get_default_perms(self, suffix=''):
989 return self._get_default_perms(self, suffix)
989 return self._get_default_perms(self, suffix)
990
990
991 def get_api_data(self, include_secrets=False, details='full'):
991 def get_api_data(self, include_secrets=False, details='full'):
992 """
992 """
993 Common function for generating user related data for API
993 Common function for generating user related data for API
994
994
995 :param include_secrets: By default secrets in the API data will be replaced
995 :param include_secrets: By default secrets in the API data will be replaced
996 by a placeholder value to prevent exposing this data by accident. In case
996 by a placeholder value to prevent exposing this data by accident. In case
997 this data shall be exposed, set this flag to ``True``.
997 this data shall be exposed, set this flag to ``True``.
998
998
999 :param details: details can be 'basic|full' basic gives only a subset of
999 :param details: details can be 'basic|full' basic gives only a subset of
1000 the available user information that includes user_id, name and emails.
1000 the available user information that includes user_id, name and emails.
1001 """
1001 """
1002 user = self
1002 user = self
1003 user_data = self.user_data
1003 user_data = self.user_data
1004 data = {
1004 data = {
1005 'user_id': user.user_id,
1005 'user_id': user.user_id,
1006 'username': user.username,
1006 'username': user.username,
1007 'firstname': user.name,
1007 'firstname': user.name,
1008 'lastname': user.lastname,
1008 'lastname': user.lastname,
1009 'email': user.email,
1009 'email': user.email,
1010 'emails': user.emails,
1010 'emails': user.emails,
1011 }
1011 }
1012 if details == 'basic':
1012 if details == 'basic':
1013 return data
1013 return data
1014
1014
1015 auth_token_length = 40
1015 auth_token_length = 40
1016 auth_token_replacement = '*' * auth_token_length
1016 auth_token_replacement = '*' * auth_token_length
1017
1017
1018 extras = {
1018 extras = {
1019 'auth_tokens': [auth_token_replacement],
1019 'auth_tokens': [auth_token_replacement],
1020 'active': user.active,
1020 'active': user.active,
1021 'admin': user.admin,
1021 'admin': user.admin,
1022 'extern_type': user.extern_type,
1022 'extern_type': user.extern_type,
1023 'extern_name': user.extern_name,
1023 'extern_name': user.extern_name,
1024 'last_login': user.last_login,
1024 'last_login': user.last_login,
1025 'last_activity': user.last_activity,
1025 'last_activity': user.last_activity,
1026 'ip_addresses': user.ip_addresses,
1026 'ip_addresses': user.ip_addresses,
1027 'language': user_data.get('language')
1027 'language': user_data.get('language')
1028 }
1028 }
1029 data.update(extras)
1029 data.update(extras)
1030
1030
1031 if include_secrets:
1031 if include_secrets:
1032 data['auth_tokens'] = user.auth_tokens
1032 data['auth_tokens'] = user.auth_tokens
1033 return data
1033 return data
1034
1034
1035 def __json__(self):
1035 def __json__(self):
1036 data = {
1036 data = {
1037 'full_name': self.full_name,
1037 'full_name': self.full_name,
1038 'full_name_or_username': self.full_name_or_username,
1038 'full_name_or_username': self.full_name_or_username,
1039 'short_contact': self.short_contact,
1039 'short_contact': self.short_contact,
1040 'full_contact': self.full_contact,
1040 'full_contact': self.full_contact,
1041 }
1041 }
1042 data.update(self.get_api_data())
1042 data.update(self.get_api_data())
1043 return data
1043 return data
1044
1044
1045
1045
1046 class UserApiKeys(Base, BaseModel):
1046 class UserApiKeys(Base, BaseModel):
1047 __tablename__ = 'user_api_keys'
1047 __tablename__ = 'user_api_keys'
1048 __table_args__ = (
1048 __table_args__ = (
1049 Index('uak_api_key_idx', 'api_key', unique=True),
1049 Index('uak_api_key_idx', 'api_key', unique=True),
1050 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1050 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1051 base_table_args
1051 base_table_args
1052 )
1052 )
1053 __mapper_args__ = {}
1053 __mapper_args__ = {}
1054
1054
1055 # ApiKey role
1055 # ApiKey role
1056 ROLE_ALL = 'token_role_all'
1056 ROLE_ALL = 'token_role_all'
1057 ROLE_HTTP = 'token_role_http'
1057 ROLE_HTTP = 'token_role_http'
1058 ROLE_VCS = 'token_role_vcs'
1058 ROLE_VCS = 'token_role_vcs'
1059 ROLE_API = 'token_role_api'
1059 ROLE_API = 'token_role_api'
1060 ROLE_FEED = 'token_role_feed'
1060 ROLE_FEED = 'token_role_feed'
1061 ROLE_PASSWORD_RESET = 'token_password_reset'
1061 ROLE_PASSWORD_RESET = 'token_password_reset'
1062
1062
1063 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1063 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1064
1064
1065 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1065 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1066 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1066 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1067 api_key = Column("api_key", String(255), nullable=False, unique=True)
1067 api_key = Column("api_key", String(255), nullable=False, unique=True)
1068 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1068 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1069 expires = Column('expires', Float(53), nullable=False)
1069 expires = Column('expires', Float(53), nullable=False)
1070 role = Column('role', String(255), nullable=True)
1070 role = Column('role', String(255), nullable=True)
1071 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1071 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1072
1072
1073 # scope columns
1073 # scope columns
1074 repo_id = Column(
1074 repo_id = Column(
1075 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1075 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1076 nullable=True, unique=None, default=None)
1076 nullable=True, unique=None, default=None)
1077 repo = relationship('Repository', lazy='joined')
1077 repo = relationship('Repository', lazy='joined')
1078
1078
1079 repo_group_id = Column(
1079 repo_group_id = Column(
1080 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1080 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1081 nullable=True, unique=None, default=None)
1081 nullable=True, unique=None, default=None)
1082 repo_group = relationship('RepoGroup', lazy='joined')
1082 repo_group = relationship('RepoGroup', lazy='joined')
1083
1083
1084 user = relationship('User', lazy='joined')
1084 user = relationship('User', lazy='joined')
1085
1085
1086 def __unicode__(self):
1086 def __unicode__(self):
1087 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1087 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1088
1088
1089 def __json__(self):
1089 def __json__(self):
1090 data = {
1090 data = {
1091 'auth_token': self.api_key,
1091 'auth_token': self.api_key,
1092 'role': self.role,
1092 'role': self.role,
1093 'scope': self.scope_humanized,
1093 'scope': self.scope_humanized,
1094 'expired': self.expired
1094 'expired': self.expired
1095 }
1095 }
1096 return data
1096 return data
1097
1097
1098 def get_api_data(self, include_secrets=False):
1098 def get_api_data(self, include_secrets=False):
1099 data = self.__json__()
1099 data = self.__json__()
1100 if include_secrets:
1100 if include_secrets:
1101 return data
1101 return data
1102 else:
1102 else:
1103 data['auth_token'] = self.token_obfuscated
1103 data['auth_token'] = self.token_obfuscated
1104 return data
1104 return data
1105
1105
1106 @hybrid_property
1106 @hybrid_property
1107 def description_safe(self):
1107 def description_safe(self):
1108 from rhodecode.lib import helpers as h
1108 from rhodecode.lib import helpers as h
1109 return h.escape(self.description)
1109 return h.escape(self.description)
1110
1110
1111 @property
1111 @property
1112 def expired(self):
1112 def expired(self):
1113 if self.expires == -1:
1113 if self.expires == -1:
1114 return False
1114 return False
1115 return time.time() > self.expires
1115 return time.time() > self.expires
1116
1116
1117 @classmethod
1117 @classmethod
1118 def _get_role_name(cls, role):
1118 def _get_role_name(cls, role):
1119 return {
1119 return {
1120 cls.ROLE_ALL: _('all'),
1120 cls.ROLE_ALL: _('all'),
1121 cls.ROLE_HTTP: _('http/web interface'),
1121 cls.ROLE_HTTP: _('http/web interface'),
1122 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1122 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1123 cls.ROLE_API: _('api calls'),
1123 cls.ROLE_API: _('api calls'),
1124 cls.ROLE_FEED: _('feed access'),
1124 cls.ROLE_FEED: _('feed access'),
1125 }.get(role, role)
1125 }.get(role, role)
1126
1126
1127 @property
1127 @property
1128 def role_humanized(self):
1128 def role_humanized(self):
1129 return self._get_role_name(self.role)
1129 return self._get_role_name(self.role)
1130
1130
1131 def _get_scope(self):
1131 def _get_scope(self):
1132 if self.repo:
1132 if self.repo:
1133 return 'Repository: {}'.format(self.repo.repo_name)
1133 return 'Repository: {}'.format(self.repo.repo_name)
1134 if self.repo_group:
1134 if self.repo_group:
1135 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1135 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1136 return 'Global'
1136 return 'Global'
1137
1137
1138 @property
1138 @property
1139 def scope_humanized(self):
1139 def scope_humanized(self):
1140 return self._get_scope()
1140 return self._get_scope()
1141
1141
1142 @property
1142 @property
1143 def token_obfuscated(self):
1143 def token_obfuscated(self):
1144 if self.api_key:
1144 if self.api_key:
1145 return self.api_key[:4] + "****"
1145 return self.api_key[:4] + "****"
1146
1146
1147
1147
1148 class UserEmailMap(Base, BaseModel):
1148 class UserEmailMap(Base, BaseModel):
1149 __tablename__ = 'user_email_map'
1149 __tablename__ = 'user_email_map'
1150 __table_args__ = (
1150 __table_args__ = (
1151 Index('uem_email_idx', 'email'),
1151 Index('uem_email_idx', 'email'),
1152 UniqueConstraint('email'),
1152 UniqueConstraint('email'),
1153 base_table_args
1153 base_table_args
1154 )
1154 )
1155 __mapper_args__ = {}
1155 __mapper_args__ = {}
1156
1156
1157 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1157 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1158 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1158 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1159 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1159 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1160 user = relationship('User', lazy='joined')
1160 user = relationship('User', lazy='joined')
1161
1161
1162 @validates('_email')
1162 @validates('_email')
1163 def validate_email(self, key, email):
1163 def validate_email(self, key, email):
1164 # check if this email is not main one
1164 # check if this email is not main one
1165 main_email = Session().query(User).filter(User.email == email).scalar()
1165 main_email = Session().query(User).filter(User.email == email).scalar()
1166 if main_email is not None:
1166 if main_email is not None:
1167 raise AttributeError('email %s is present is user table' % email)
1167 raise AttributeError('email %s is present is user table' % email)
1168 return email
1168 return email
1169
1169
1170 @hybrid_property
1170 @hybrid_property
1171 def email(self):
1171 def email(self):
1172 return self._email
1172 return self._email
1173
1173
1174 @email.setter
1174 @email.setter
1175 def email(self, val):
1175 def email(self, val):
1176 self._email = val.lower() if val else None
1176 self._email = val.lower() if val else None
1177
1177
1178
1178
1179 class UserIpMap(Base, BaseModel):
1179 class UserIpMap(Base, BaseModel):
1180 __tablename__ = 'user_ip_map'
1180 __tablename__ = 'user_ip_map'
1181 __table_args__ = (
1181 __table_args__ = (
1182 UniqueConstraint('user_id', 'ip_addr'),
1182 UniqueConstraint('user_id', 'ip_addr'),
1183 base_table_args
1183 base_table_args
1184 )
1184 )
1185 __mapper_args__ = {}
1185 __mapper_args__ = {}
1186
1186
1187 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1187 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1188 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1188 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1189 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1189 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1190 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1190 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1191 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1191 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1192 user = relationship('User', lazy='joined')
1192 user = relationship('User', lazy='joined')
1193
1193
1194 @hybrid_property
1194 @hybrid_property
1195 def description_safe(self):
1195 def description_safe(self):
1196 from rhodecode.lib import helpers as h
1196 from rhodecode.lib import helpers as h
1197 return h.escape(self.description)
1197 return h.escape(self.description)
1198
1198
1199 @classmethod
1199 @classmethod
1200 def _get_ip_range(cls, ip_addr):
1200 def _get_ip_range(cls, ip_addr):
1201 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1201 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1202 return [str(net.network_address), str(net.broadcast_address)]
1202 return [str(net.network_address), str(net.broadcast_address)]
1203
1203
1204 def __json__(self):
1204 def __json__(self):
1205 return {
1205 return {
1206 'ip_addr': self.ip_addr,
1206 'ip_addr': self.ip_addr,
1207 'ip_range': self._get_ip_range(self.ip_addr),
1207 'ip_range': self._get_ip_range(self.ip_addr),
1208 }
1208 }
1209
1209
1210 def __unicode__(self):
1210 def __unicode__(self):
1211 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1211 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1212 self.user_id, self.ip_addr)
1212 self.user_id, self.ip_addr)
1213
1213
1214
1214
1215 class UserSshKeys(Base, BaseModel):
1215 class UserSshKeys(Base, BaseModel):
1216 __tablename__ = 'user_ssh_keys'
1216 __tablename__ = 'user_ssh_keys'
1217 __table_args__ = (
1217 __table_args__ = (
1218 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1218 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1219
1219
1220 UniqueConstraint('ssh_key_fingerprint'),
1220 UniqueConstraint('ssh_key_fingerprint'),
1221
1221
1222 base_table_args
1222 base_table_args
1223 )
1223 )
1224 __mapper_args__ = {}
1224 __mapper_args__ = {}
1225
1225
1226 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1226 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1227 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1227 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1228 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1228 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1229
1229
1230 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1230 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1231
1231
1232 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1232 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1233 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1233 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1234 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1234 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1235
1235
1236 user = relationship('User', lazy='joined')
1236 user = relationship('User', lazy='joined')
1237
1237
1238 def __json__(self):
1238 def __json__(self):
1239 data = {
1239 data = {
1240 'ssh_fingerprint': self.ssh_key_fingerprint,
1240 'ssh_fingerprint': self.ssh_key_fingerprint,
1241 'description': self.description,
1241 'description': self.description,
1242 'created_on': self.created_on
1242 'created_on': self.created_on
1243 }
1243 }
1244 return data
1244 return data
1245
1245
1246 def get_api_data(self):
1246 def get_api_data(self):
1247 data = self.__json__()
1247 data = self.__json__()
1248 return data
1248 return data
1249
1249
1250
1250
1251 class UserLog(Base, BaseModel):
1251 class UserLog(Base, BaseModel):
1252 __tablename__ = 'user_logs'
1252 __tablename__ = 'user_logs'
1253 __table_args__ = (
1253 __table_args__ = (
1254 base_table_args,
1254 base_table_args,
1255 )
1255 )
1256
1256
1257 VERSION_1 = 'v1'
1257 VERSION_1 = 'v1'
1258 VERSION_2 = 'v2'
1258 VERSION_2 = 'v2'
1259 VERSIONS = [VERSION_1, VERSION_2]
1259 VERSIONS = [VERSION_1, VERSION_2]
1260
1260
1261 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1261 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1262 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1262 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1263 username = Column("username", String(255), nullable=True, unique=None, default=None)
1263 username = Column("username", String(255), nullable=True, unique=None, default=None)
1264 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1264 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1265 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1265 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1266 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1266 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1267 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1267 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1268 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1268 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1269
1269
1270 version = Column("version", String(255), nullable=True, default=VERSION_1)
1270 version = Column("version", String(255), nullable=True, default=VERSION_1)
1271 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1271 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1272 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1272 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1273
1273
1274 def __unicode__(self):
1274 def __unicode__(self):
1275 return u"<%s('id:%s:%s')>" % (
1275 return u"<%s('id:%s:%s')>" % (
1276 self.__class__.__name__, self.repository_name, self.action)
1276 self.__class__.__name__, self.repository_name, self.action)
1277
1277
1278 def __json__(self):
1278 def __json__(self):
1279 return {
1279 return {
1280 'user_id': self.user_id,
1280 'user_id': self.user_id,
1281 'username': self.username,
1281 'username': self.username,
1282 'repository_id': self.repository_id,
1282 'repository_id': self.repository_id,
1283 'repository_name': self.repository_name,
1283 'repository_name': self.repository_name,
1284 'user_ip': self.user_ip,
1284 'user_ip': self.user_ip,
1285 'action_date': self.action_date,
1285 'action_date': self.action_date,
1286 'action': self.action,
1286 'action': self.action,
1287 }
1287 }
1288
1288
1289 @hybrid_property
1289 @hybrid_property
1290 def entry_id(self):
1290 def entry_id(self):
1291 return self.user_log_id
1291 return self.user_log_id
1292
1292
1293 @property
1293 @property
1294 def action_as_day(self):
1294 def action_as_day(self):
1295 return datetime.date(*self.action_date.timetuple()[:3])
1295 return datetime.date(*self.action_date.timetuple()[:3])
1296
1296
1297 user = relationship('User')
1297 user = relationship('User')
1298 repository = relationship('Repository', cascade='')
1298 repository = relationship('Repository', cascade='')
1299
1299
1300
1300
1301 class UserGroup(Base, BaseModel):
1301 class UserGroup(Base, BaseModel):
1302 __tablename__ = 'users_groups'
1302 __tablename__ = 'users_groups'
1303 __table_args__ = (
1303 __table_args__ = (
1304 base_table_args,
1304 base_table_args,
1305 )
1305 )
1306
1306
1307 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1307 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1308 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1308 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1309 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1309 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1310 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1310 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1311 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1311 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1312 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1312 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1313 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1313 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1314 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1314 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1315
1315
1316 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1316 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1317 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1317 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1318 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1318 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1319 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1319 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1320 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1320 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1321 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1321 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1322
1322
1323 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1323 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1324 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1324 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1325
1325
1326 @classmethod
1326 @classmethod
1327 def _load_group_data(cls, column):
1327 def _load_group_data(cls, column):
1328 if not column:
1328 if not column:
1329 return {}
1329 return {}
1330
1330
1331 try:
1331 try:
1332 return json.loads(column) or {}
1332 return json.loads(column) or {}
1333 except TypeError:
1333 except TypeError:
1334 return {}
1334 return {}
1335
1335
1336 @hybrid_property
1336 @hybrid_property
1337 def description_safe(self):
1337 def description_safe(self):
1338 from rhodecode.lib import helpers as h
1338 from rhodecode.lib import helpers as h
1339 return h.escape(self.user_group_description)
1339 return h.escape(self.user_group_description)
1340
1340
1341 @hybrid_property
1341 @hybrid_property
1342 def group_data(self):
1342 def group_data(self):
1343 return self._load_group_data(self._group_data)
1343 return self._load_group_data(self._group_data)
1344
1344
1345 @group_data.expression
1345 @group_data.expression
1346 def group_data(self, **kwargs):
1346 def group_data(self, **kwargs):
1347 return self._group_data
1347 return self._group_data
1348
1348
1349 @group_data.setter
1349 @group_data.setter
1350 def group_data(self, val):
1350 def group_data(self, val):
1351 try:
1351 try:
1352 self._group_data = json.dumps(val)
1352 self._group_data = json.dumps(val)
1353 except Exception:
1353 except Exception:
1354 log.error(traceback.format_exc())
1354 log.error(traceback.format_exc())
1355
1355
1356 @classmethod
1356 @classmethod
1357 def _load_sync(cls, group_data):
1357 def _load_sync(cls, group_data):
1358 if group_data:
1358 if group_data:
1359 return group_data.get('extern_type')
1359 return group_data.get('extern_type')
1360
1360
1361 @property
1361 @property
1362 def sync(self):
1362 def sync(self):
1363 return self._load_sync(self.group_data)
1363 return self._load_sync(self.group_data)
1364
1364
1365 def __unicode__(self):
1365 def __unicode__(self):
1366 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1366 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1367 self.users_group_id,
1367 self.users_group_id,
1368 self.users_group_name)
1368 self.users_group_name)
1369
1369
1370 @classmethod
1370 @classmethod
1371 def get_by_group_name(cls, group_name, cache=False,
1371 def get_by_group_name(cls, group_name, cache=False,
1372 case_insensitive=False):
1372 case_insensitive=False):
1373 if case_insensitive:
1373 if case_insensitive:
1374 q = cls.query().filter(func.lower(cls.users_group_name) ==
1374 q = cls.query().filter(func.lower(cls.users_group_name) ==
1375 func.lower(group_name))
1375 func.lower(group_name))
1376
1376
1377 else:
1377 else:
1378 q = cls.query().filter(cls.users_group_name == group_name)
1378 q = cls.query().filter(cls.users_group_name == group_name)
1379 if cache:
1379 if cache:
1380 q = q.options(
1380 q = q.options(
1381 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1381 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1382 return q.scalar()
1382 return q.scalar()
1383
1383
1384 @classmethod
1384 @classmethod
1385 def get(cls, user_group_id, cache=False):
1385 def get(cls, user_group_id, cache=False):
1386 if not user_group_id:
1386 if not user_group_id:
1387 return
1387 return
1388
1388
1389 user_group = cls.query()
1389 user_group = cls.query()
1390 if cache:
1390 if cache:
1391 user_group = user_group.options(
1391 user_group = user_group.options(
1392 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1392 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1393 return user_group.get(user_group_id)
1393 return user_group.get(user_group_id)
1394
1394
1395 def permissions(self, with_admins=True, with_owner=True,
1395 def permissions(self, with_admins=True, with_owner=True,
1396 expand_from_user_groups=False):
1396 expand_from_user_groups=False):
1397 """
1397 """
1398 Permissions for user groups
1398 Permissions for user groups
1399 """
1399 """
1400 _admin_perm = 'usergroup.admin'
1400 _admin_perm = 'usergroup.admin'
1401
1401
1402 owner_row = []
1402 owner_row = []
1403 if with_owner:
1403 if with_owner:
1404 usr = AttributeDict(self.user.get_dict())
1404 usr = AttributeDict(self.user.get_dict())
1405 usr.owner_row = True
1405 usr.owner_row = True
1406 usr.permission = _admin_perm
1406 usr.permission = _admin_perm
1407 owner_row.append(usr)
1407 owner_row.append(usr)
1408
1408
1409 super_admin_ids = []
1409 super_admin_ids = []
1410 super_admin_rows = []
1410 super_admin_rows = []
1411 if with_admins:
1411 if with_admins:
1412 for usr in User.get_all_super_admins():
1412 for usr in User.get_all_super_admins():
1413 super_admin_ids.append(usr.user_id)
1413 super_admin_ids.append(usr.user_id)
1414 # if this admin is also owner, don't double the record
1414 # if this admin is also owner, don't double the record
1415 if usr.user_id == owner_row[0].user_id:
1415 if usr.user_id == owner_row[0].user_id:
1416 owner_row[0].admin_row = True
1416 owner_row[0].admin_row = True
1417 else:
1417 else:
1418 usr = AttributeDict(usr.get_dict())
1418 usr = AttributeDict(usr.get_dict())
1419 usr.admin_row = True
1419 usr.admin_row = True
1420 usr.permission = _admin_perm
1420 usr.permission = _admin_perm
1421 super_admin_rows.append(usr)
1421 super_admin_rows.append(usr)
1422
1422
1423 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1423 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1424 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1424 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1425 joinedload(UserUserGroupToPerm.user),
1425 joinedload(UserUserGroupToPerm.user),
1426 joinedload(UserUserGroupToPerm.permission),)
1426 joinedload(UserUserGroupToPerm.permission),)
1427
1427
1428 # get owners and admins and permissions. We do a trick of re-writing
1428 # get owners and admins and permissions. We do a trick of re-writing
1429 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1429 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1430 # has a global reference and changing one object propagates to all
1430 # has a global reference and changing one object propagates to all
1431 # others. This means if admin is also an owner admin_row that change
1431 # others. This means if admin is also an owner admin_row that change
1432 # would propagate to both objects
1432 # would propagate to both objects
1433 perm_rows = []
1433 perm_rows = []
1434 for _usr in q.all():
1434 for _usr in q.all():
1435 usr = AttributeDict(_usr.user.get_dict())
1435 usr = AttributeDict(_usr.user.get_dict())
1436 # if this user is also owner/admin, mark as duplicate record
1436 # if this user is also owner/admin, mark as duplicate record
1437 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1437 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1438 usr.duplicate_perm = True
1438 usr.duplicate_perm = True
1439 usr.permission = _usr.permission.permission_name
1439 usr.permission = _usr.permission.permission_name
1440 perm_rows.append(usr)
1440 perm_rows.append(usr)
1441
1441
1442 # filter the perm rows by 'default' first and then sort them by
1442 # filter the perm rows by 'default' first and then sort them by
1443 # admin,write,read,none permissions sorted again alphabetically in
1443 # admin,write,read,none permissions sorted again alphabetically in
1444 # each group
1444 # each group
1445 perm_rows = sorted(perm_rows, key=display_user_sort)
1445 perm_rows = sorted(perm_rows, key=display_user_sort)
1446
1446
1447 user_groups_rows = []
1447 user_groups_rows = []
1448 if expand_from_user_groups:
1448 if expand_from_user_groups:
1449 for ug in self.permission_user_groups(with_members=True):
1449 for ug in self.permission_user_groups(with_members=True):
1450 for user_data in ug.members:
1450 for user_data in ug.members:
1451 user_groups_rows.append(user_data)
1451 user_groups_rows.append(user_data)
1452
1452
1453 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1453 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1454
1454
1455 def permission_user_groups(self, with_members=False):
1455 def permission_user_groups(self, with_members=False):
1456 q = UserGroupUserGroupToPerm.query()\
1456 q = UserGroupUserGroupToPerm.query()\
1457 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1457 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1458 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1458 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1459 joinedload(UserGroupUserGroupToPerm.target_user_group),
1459 joinedload(UserGroupUserGroupToPerm.target_user_group),
1460 joinedload(UserGroupUserGroupToPerm.permission),)
1460 joinedload(UserGroupUserGroupToPerm.permission),)
1461
1461
1462 perm_rows = []
1462 perm_rows = []
1463 for _user_group in q.all():
1463 for _user_group in q.all():
1464 entry = AttributeDict(_user_group.user_group.get_dict())
1464 entry = AttributeDict(_user_group.user_group.get_dict())
1465 entry.permission = _user_group.permission.permission_name
1465 entry.permission = _user_group.permission.permission_name
1466 if with_members:
1466 if with_members:
1467 entry.members = [x.user.get_dict()
1467 entry.members = [x.user.get_dict()
1468 for x in _user_group.users_group.members]
1468 for x in _user_group.users_group.members]
1469 perm_rows.append(entry)
1469 perm_rows.append(entry)
1470
1470
1471 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1471 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1472 return perm_rows
1472 return perm_rows
1473
1473
1474 def _get_default_perms(self, user_group, suffix=''):
1474 def _get_default_perms(self, user_group, suffix=''):
1475 from rhodecode.model.permission import PermissionModel
1475 from rhodecode.model.permission import PermissionModel
1476 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1476 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1477
1477
1478 def get_default_perms(self, suffix=''):
1478 def get_default_perms(self, suffix=''):
1479 return self._get_default_perms(self, suffix)
1479 return self._get_default_perms(self, suffix)
1480
1480
1481 def get_api_data(self, with_group_members=True, include_secrets=False):
1481 def get_api_data(self, with_group_members=True, include_secrets=False):
1482 """
1482 """
1483 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1483 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1484 basically forwarded.
1484 basically forwarded.
1485
1485
1486 """
1486 """
1487 user_group = self
1487 user_group = self
1488 data = {
1488 data = {
1489 'users_group_id': user_group.users_group_id,
1489 'users_group_id': user_group.users_group_id,
1490 'group_name': user_group.users_group_name,
1490 'group_name': user_group.users_group_name,
1491 'group_description': user_group.user_group_description,
1491 'group_description': user_group.user_group_description,
1492 'active': user_group.users_group_active,
1492 'active': user_group.users_group_active,
1493 'owner': user_group.user.username,
1493 'owner': user_group.user.username,
1494 'sync': user_group.sync,
1494 'sync': user_group.sync,
1495 'owner_email': user_group.user.email,
1495 'owner_email': user_group.user.email,
1496 }
1496 }
1497
1497
1498 if with_group_members:
1498 if with_group_members:
1499 users = []
1499 users = []
1500 for user in user_group.members:
1500 for user in user_group.members:
1501 user = user.user
1501 user = user.user
1502 users.append(user.get_api_data(include_secrets=include_secrets))
1502 users.append(user.get_api_data(include_secrets=include_secrets))
1503 data['users'] = users
1503 data['users'] = users
1504
1504
1505 return data
1505 return data
1506
1506
1507
1507
1508 class UserGroupMember(Base, BaseModel):
1508 class UserGroupMember(Base, BaseModel):
1509 __tablename__ = 'users_groups_members'
1509 __tablename__ = 'users_groups_members'
1510 __table_args__ = (
1510 __table_args__ = (
1511 base_table_args,
1511 base_table_args,
1512 )
1512 )
1513
1513
1514 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1514 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1515 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1515 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1516 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1516 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1517
1517
1518 user = relationship('User', lazy='joined')
1518 user = relationship('User', lazy='joined')
1519 users_group = relationship('UserGroup')
1519 users_group = relationship('UserGroup')
1520
1520
1521 def __init__(self, gr_id='', u_id=''):
1521 def __init__(self, gr_id='', u_id=''):
1522 self.users_group_id = gr_id
1522 self.users_group_id = gr_id
1523 self.user_id = u_id
1523 self.user_id = u_id
1524
1524
1525
1525
1526 class RepositoryField(Base, BaseModel):
1526 class RepositoryField(Base, BaseModel):
1527 __tablename__ = 'repositories_fields'
1527 __tablename__ = 'repositories_fields'
1528 __table_args__ = (
1528 __table_args__ = (
1529 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1529 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1530 base_table_args,
1530 base_table_args,
1531 )
1531 )
1532
1532
1533 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1533 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1534
1534
1535 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1535 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1536 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1536 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1537 field_key = Column("field_key", String(250))
1537 field_key = Column("field_key", String(250))
1538 field_label = Column("field_label", String(1024), nullable=False)
1538 field_label = Column("field_label", String(1024), nullable=False)
1539 field_value = Column("field_value", String(10000), nullable=False)
1539 field_value = Column("field_value", String(10000), nullable=False)
1540 field_desc = Column("field_desc", String(1024), nullable=False)
1540 field_desc = Column("field_desc", String(1024), nullable=False)
1541 field_type = Column("field_type", String(255), nullable=False, unique=None)
1541 field_type = Column("field_type", String(255), nullable=False, unique=None)
1542 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1542 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1543
1543
1544 repository = relationship('Repository')
1544 repository = relationship('Repository')
1545
1545
1546 @property
1546 @property
1547 def field_key_prefixed(self):
1547 def field_key_prefixed(self):
1548 return 'ex_%s' % self.field_key
1548 return 'ex_%s' % self.field_key
1549
1549
1550 @classmethod
1550 @classmethod
1551 def un_prefix_key(cls, key):
1551 def un_prefix_key(cls, key):
1552 if key.startswith(cls.PREFIX):
1552 if key.startswith(cls.PREFIX):
1553 return key[len(cls.PREFIX):]
1553 return key[len(cls.PREFIX):]
1554 return key
1554 return key
1555
1555
1556 @classmethod
1556 @classmethod
1557 def get_by_key_name(cls, key, repo):
1557 def get_by_key_name(cls, key, repo):
1558 row = cls.query()\
1558 row = cls.query()\
1559 .filter(cls.repository == repo)\
1559 .filter(cls.repository == repo)\
1560 .filter(cls.field_key == key).scalar()
1560 .filter(cls.field_key == key).scalar()
1561 return row
1561 return row
1562
1562
1563
1563
1564 class Repository(Base, BaseModel):
1564 class Repository(Base, BaseModel):
1565 __tablename__ = 'repositories'
1565 __tablename__ = 'repositories'
1566 __table_args__ = (
1566 __table_args__ = (
1567 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1567 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1568 base_table_args,
1568 base_table_args,
1569 )
1569 )
1570 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1570 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1571 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1571 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1572 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1572 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1573
1573
1574 STATE_CREATED = 'repo_state_created'
1574 STATE_CREATED = 'repo_state_created'
1575 STATE_PENDING = 'repo_state_pending'
1575 STATE_PENDING = 'repo_state_pending'
1576 STATE_ERROR = 'repo_state_error'
1576 STATE_ERROR = 'repo_state_error'
1577
1577
1578 LOCK_AUTOMATIC = 'lock_auto'
1578 LOCK_AUTOMATIC = 'lock_auto'
1579 LOCK_API = 'lock_api'
1579 LOCK_API = 'lock_api'
1580 LOCK_WEB = 'lock_web'
1580 LOCK_WEB = 'lock_web'
1581 LOCK_PULL = 'lock_pull'
1581 LOCK_PULL = 'lock_pull'
1582
1582
1583 NAME_SEP = URL_SEP
1583 NAME_SEP = URL_SEP
1584
1584
1585 repo_id = Column(
1585 repo_id = Column(
1586 "repo_id", Integer(), nullable=False, unique=True, default=None,
1586 "repo_id", Integer(), nullable=False, unique=True, default=None,
1587 primary_key=True)
1587 primary_key=True)
1588 _repo_name = Column(
1588 _repo_name = Column(
1589 "repo_name", Text(), nullable=False, default=None)
1589 "repo_name", Text(), nullable=False, default=None)
1590 _repo_name_hash = Column(
1590 _repo_name_hash = Column(
1591 "repo_name_hash", String(255), nullable=False, unique=True)
1591 "repo_name_hash", String(255), nullable=False, unique=True)
1592 repo_state = Column("repo_state", String(255), nullable=True)
1592 repo_state = Column("repo_state", String(255), nullable=True)
1593
1593
1594 clone_uri = Column(
1594 clone_uri = Column(
1595 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1595 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1596 default=None)
1596 default=None)
1597 push_uri = Column(
1597 push_uri = Column(
1598 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1598 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1599 default=None)
1599 default=None)
1600 repo_type = Column(
1600 repo_type = Column(
1601 "repo_type", String(255), nullable=False, unique=False, default=None)
1601 "repo_type", String(255), nullable=False, unique=False, default=None)
1602 user_id = Column(
1602 user_id = Column(
1603 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1603 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1604 unique=False, default=None)
1604 unique=False, default=None)
1605 private = Column(
1605 private = Column(
1606 "private", Boolean(), nullable=True, unique=None, default=None)
1606 "private", Boolean(), nullable=True, unique=None, default=None)
1607 archived = Column(
1607 archived = Column(
1608 "archived", Boolean(), nullable=True, unique=None, default=None)
1608 "archived", Boolean(), nullable=True, unique=None, default=None)
1609 enable_statistics = Column(
1609 enable_statistics = Column(
1610 "statistics", Boolean(), nullable=True, unique=None, default=True)
1610 "statistics", Boolean(), nullable=True, unique=None, default=True)
1611 enable_downloads = Column(
1611 enable_downloads = Column(
1612 "downloads", Boolean(), nullable=True, unique=None, default=True)
1612 "downloads", Boolean(), nullable=True, unique=None, default=True)
1613 description = Column(
1613 description = Column(
1614 "description", String(10000), nullable=True, unique=None, default=None)
1614 "description", String(10000), nullable=True, unique=None, default=None)
1615 created_on = Column(
1615 created_on = Column(
1616 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1616 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1617 default=datetime.datetime.now)
1617 default=datetime.datetime.now)
1618 updated_on = Column(
1618 updated_on = Column(
1619 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1619 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1620 default=datetime.datetime.now)
1620 default=datetime.datetime.now)
1621 _landing_revision = Column(
1621 _landing_revision = Column(
1622 "landing_revision", String(255), nullable=False, unique=False,
1622 "landing_revision", String(255), nullable=False, unique=False,
1623 default=None)
1623 default=None)
1624 enable_locking = Column(
1624 enable_locking = Column(
1625 "enable_locking", Boolean(), nullable=False, unique=None,
1625 "enable_locking", Boolean(), nullable=False, unique=None,
1626 default=False)
1626 default=False)
1627 _locked = Column(
1627 _locked = Column(
1628 "locked", String(255), nullable=True, unique=False, default=None)
1628 "locked", String(255), nullable=True, unique=False, default=None)
1629 _changeset_cache = Column(
1629 _changeset_cache = Column(
1630 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1630 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1631
1631
1632 fork_id = Column(
1632 fork_id = Column(
1633 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1633 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1634 nullable=True, unique=False, default=None)
1634 nullable=True, unique=False, default=None)
1635 group_id = Column(
1635 group_id = Column(
1636 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1636 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1637 unique=False, default=None)
1637 unique=False, default=None)
1638
1638
1639 user = relationship('User', lazy='joined')
1639 user = relationship('User', lazy='joined')
1640 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1640 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1641 group = relationship('RepoGroup', lazy='joined')
1641 group = relationship('RepoGroup', lazy='joined')
1642 repo_to_perm = relationship(
1642 repo_to_perm = relationship(
1643 'UserRepoToPerm', cascade='all',
1643 'UserRepoToPerm', cascade='all',
1644 order_by='UserRepoToPerm.repo_to_perm_id')
1644 order_by='UserRepoToPerm.repo_to_perm_id')
1645 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1645 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1646 stats = relationship('Statistics', cascade='all', uselist=False)
1646 stats = relationship('Statistics', cascade='all', uselist=False)
1647
1647
1648 followers = relationship(
1648 followers = relationship(
1649 'UserFollowing',
1649 'UserFollowing',
1650 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1650 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1651 cascade='all')
1651 cascade='all')
1652 extra_fields = relationship(
1652 extra_fields = relationship(
1653 'RepositoryField', cascade="all, delete, delete-orphan")
1653 'RepositoryField', cascade="all, delete, delete-orphan")
1654 logs = relationship('UserLog')
1654 logs = relationship('UserLog')
1655 comments = relationship(
1655 comments = relationship(
1656 'ChangesetComment', cascade="all, delete, delete-orphan")
1656 'ChangesetComment', cascade="all, delete, delete-orphan")
1657 pull_requests_source = relationship(
1657 pull_requests_source = relationship(
1658 'PullRequest',
1658 'PullRequest',
1659 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1659 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1660 cascade="all, delete, delete-orphan")
1660 cascade="all, delete, delete-orphan")
1661 pull_requests_target = relationship(
1661 pull_requests_target = relationship(
1662 'PullRequest',
1662 'PullRequest',
1663 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1663 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1664 cascade="all, delete, delete-orphan")
1664 cascade="all, delete, delete-orphan")
1665 ui = relationship('RepoRhodeCodeUi', cascade="all")
1665 ui = relationship('RepoRhodeCodeUi', cascade="all")
1666 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1666 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1667 integrations = relationship('Integration',
1667 integrations = relationship('Integration',
1668 cascade="all, delete, delete-orphan")
1668 cascade="all, delete, delete-orphan")
1669
1669
1670 scoped_tokens = relationship('UserApiKeys', cascade="all")
1670 scoped_tokens = relationship('UserApiKeys', cascade="all")
1671
1671
1672 def __unicode__(self):
1672 def __unicode__(self):
1673 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1673 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1674 safe_unicode(self.repo_name))
1674 safe_unicode(self.repo_name))
1675
1675
1676 @hybrid_property
1676 @hybrid_property
1677 def description_safe(self):
1677 def description_safe(self):
1678 from rhodecode.lib import helpers as h
1678 from rhodecode.lib import helpers as h
1679 return h.escape(self.description)
1679 return h.escape(self.description)
1680
1680
1681 @hybrid_property
1681 @hybrid_property
1682 def landing_rev(self):
1682 def landing_rev(self):
1683 # always should return [rev_type, rev]
1683 # always should return [rev_type, rev]
1684 if self._landing_revision:
1684 if self._landing_revision:
1685 _rev_info = self._landing_revision.split(':')
1685 _rev_info = self._landing_revision.split(':')
1686 if len(_rev_info) < 2:
1686 if len(_rev_info) < 2:
1687 _rev_info.insert(0, 'rev')
1687 _rev_info.insert(0, 'rev')
1688 return [_rev_info[0], _rev_info[1]]
1688 return [_rev_info[0], _rev_info[1]]
1689 return [None, None]
1689 return [None, None]
1690
1690
1691 @landing_rev.setter
1691 @landing_rev.setter
1692 def landing_rev(self, val):
1692 def landing_rev(self, val):
1693 if ':' not in val:
1693 if ':' not in val:
1694 raise ValueError('value must be delimited with `:` and consist '
1694 raise ValueError('value must be delimited with `:` and consist '
1695 'of <rev_type>:<rev>, got %s instead' % val)
1695 'of <rev_type>:<rev>, got %s instead' % val)
1696 self._landing_revision = val
1696 self._landing_revision = val
1697
1697
1698 @hybrid_property
1698 @hybrid_property
1699 def locked(self):
1699 def locked(self):
1700 if self._locked:
1700 if self._locked:
1701 user_id, timelocked, reason = self._locked.split(':')
1701 user_id, timelocked, reason = self._locked.split(':')
1702 lock_values = int(user_id), timelocked, reason
1702 lock_values = int(user_id), timelocked, reason
1703 else:
1703 else:
1704 lock_values = [None, None, None]
1704 lock_values = [None, None, None]
1705 return lock_values
1705 return lock_values
1706
1706
1707 @locked.setter
1707 @locked.setter
1708 def locked(self, val):
1708 def locked(self, val):
1709 if val and isinstance(val, (list, tuple)):
1709 if val and isinstance(val, (list, tuple)):
1710 self._locked = ':'.join(map(str, val))
1710 self._locked = ':'.join(map(str, val))
1711 else:
1711 else:
1712 self._locked = None
1712 self._locked = None
1713
1713
1714 @hybrid_property
1714 @hybrid_property
1715 def changeset_cache(self):
1715 def changeset_cache(self):
1716 from rhodecode.lib.vcs.backends.base import EmptyCommit
1716 from rhodecode.lib.vcs.backends.base import EmptyCommit
1717 dummy = EmptyCommit().__json__()
1717 dummy = EmptyCommit().__json__()
1718 if not self._changeset_cache:
1718 if not self._changeset_cache:
1719 return dummy
1719 return dummy
1720 try:
1720 try:
1721 return json.loads(self._changeset_cache)
1721 return json.loads(self._changeset_cache)
1722 except TypeError:
1722 except TypeError:
1723 return dummy
1723 return dummy
1724 except Exception:
1724 except Exception:
1725 log.error(traceback.format_exc())
1725 log.error(traceback.format_exc())
1726 return dummy
1726 return dummy
1727
1727
1728 @changeset_cache.setter
1728 @changeset_cache.setter
1729 def changeset_cache(self, val):
1729 def changeset_cache(self, val):
1730 try:
1730 try:
1731 self._changeset_cache = json.dumps(val)
1731 self._changeset_cache = json.dumps(val)
1732 except Exception:
1732 except Exception:
1733 log.error(traceback.format_exc())
1733 log.error(traceback.format_exc())
1734
1734
1735 @hybrid_property
1735 @hybrid_property
1736 def repo_name(self):
1736 def repo_name(self):
1737 return self._repo_name
1737 return self._repo_name
1738
1738
1739 @repo_name.setter
1739 @repo_name.setter
1740 def repo_name(self, value):
1740 def repo_name(self, value):
1741 self._repo_name = value
1741 self._repo_name = value
1742 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1742 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1743
1743
1744 @classmethod
1744 @classmethod
1745 def normalize_repo_name(cls, repo_name):
1745 def normalize_repo_name(cls, repo_name):
1746 """
1746 """
1747 Normalizes os specific repo_name to the format internally stored inside
1747 Normalizes os specific repo_name to the format internally stored inside
1748 database using URL_SEP
1748 database using URL_SEP
1749
1749
1750 :param cls:
1750 :param cls:
1751 :param repo_name:
1751 :param repo_name:
1752 """
1752 """
1753 return cls.NAME_SEP.join(repo_name.split(os.sep))
1753 return cls.NAME_SEP.join(repo_name.split(os.sep))
1754
1754
1755 @classmethod
1755 @classmethod
1756 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1756 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1757 session = Session()
1757 session = Session()
1758 q = session.query(cls).filter(cls.repo_name == repo_name)
1758 q = session.query(cls).filter(cls.repo_name == repo_name)
1759
1759
1760 if cache:
1760 if cache:
1761 if identity_cache:
1761 if identity_cache:
1762 val = cls.identity_cache(session, 'repo_name', repo_name)
1762 val = cls.identity_cache(session, 'repo_name', repo_name)
1763 if val:
1763 if val:
1764 return val
1764 return val
1765 else:
1765 else:
1766 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1766 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1767 q = q.options(
1767 q = q.options(
1768 FromCache("sql_cache_short", cache_key))
1768 FromCache("sql_cache_short", cache_key))
1769
1769
1770 return q.scalar()
1770 return q.scalar()
1771
1771
1772 @classmethod
1772 @classmethod
1773 def get_by_id_or_repo_name(cls, repoid):
1773 def get_by_id_or_repo_name(cls, repoid):
1774 if isinstance(repoid, (int, long)):
1774 if isinstance(repoid, (int, long)):
1775 try:
1775 try:
1776 repo = cls.get(repoid)
1776 repo = cls.get(repoid)
1777 except ValueError:
1777 except ValueError:
1778 repo = None
1778 repo = None
1779 else:
1779 else:
1780 repo = cls.get_by_repo_name(repoid)
1780 repo = cls.get_by_repo_name(repoid)
1781 return repo
1781 return repo
1782
1782
1783 @classmethod
1783 @classmethod
1784 def get_by_full_path(cls, repo_full_path):
1784 def get_by_full_path(cls, repo_full_path):
1785 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1785 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1786 repo_name = cls.normalize_repo_name(repo_name)
1786 repo_name = cls.normalize_repo_name(repo_name)
1787 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1787 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1788
1788
1789 @classmethod
1789 @classmethod
1790 def get_repo_forks(cls, repo_id):
1790 def get_repo_forks(cls, repo_id):
1791 return cls.query().filter(Repository.fork_id == repo_id)
1791 return cls.query().filter(Repository.fork_id == repo_id)
1792
1792
1793 @classmethod
1793 @classmethod
1794 def base_path(cls):
1794 def base_path(cls):
1795 """
1795 """
1796 Returns base path when all repos are stored
1796 Returns base path when all repos are stored
1797
1797
1798 :param cls:
1798 :param cls:
1799 """
1799 """
1800 q = Session().query(RhodeCodeUi)\
1800 q = Session().query(RhodeCodeUi)\
1801 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1801 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1802 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1802 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1803 return q.one().ui_value
1803 return q.one().ui_value
1804
1804
1805 @classmethod
1805 @classmethod
1806 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1806 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1807 case_insensitive=True, archived=False):
1807 case_insensitive=True, archived=False):
1808 q = Repository.query()
1808 q = Repository.query()
1809
1809
1810 if not archived:
1810 if not archived:
1811 q = q.filter(Repository.archived.isnot(true()))
1811 q = q.filter(Repository.archived.isnot(true()))
1812
1812
1813 if not isinstance(user_id, Optional):
1813 if not isinstance(user_id, Optional):
1814 q = q.filter(Repository.user_id == user_id)
1814 q = q.filter(Repository.user_id == user_id)
1815
1815
1816 if not isinstance(group_id, Optional):
1816 if not isinstance(group_id, Optional):
1817 q = q.filter(Repository.group_id == group_id)
1817 q = q.filter(Repository.group_id == group_id)
1818
1818
1819 if case_insensitive:
1819 if case_insensitive:
1820 q = q.order_by(func.lower(Repository.repo_name))
1820 q = q.order_by(func.lower(Repository.repo_name))
1821 else:
1821 else:
1822 q = q.order_by(Repository.repo_name)
1822 q = q.order_by(Repository.repo_name)
1823
1823
1824 return q.all()
1824 return q.all()
1825
1825
1826 @property
1826 @property
1827 def forks(self):
1827 def forks(self):
1828 """
1828 """
1829 Return forks of this repo
1829 Return forks of this repo
1830 """
1830 """
1831 return Repository.get_repo_forks(self.repo_id)
1831 return Repository.get_repo_forks(self.repo_id)
1832
1832
1833 @property
1833 @property
1834 def parent(self):
1834 def parent(self):
1835 """
1835 """
1836 Returns fork parent
1836 Returns fork parent
1837 """
1837 """
1838 return self.fork
1838 return self.fork
1839
1839
1840 @property
1840 @property
1841 def just_name(self):
1841 def just_name(self):
1842 return self.repo_name.split(self.NAME_SEP)[-1]
1842 return self.repo_name.split(self.NAME_SEP)[-1]
1843
1843
1844 @property
1844 @property
1845 def groups_with_parents(self):
1845 def groups_with_parents(self):
1846 groups = []
1846 groups = []
1847 if self.group is None:
1847 if self.group is None:
1848 return groups
1848 return groups
1849
1849
1850 cur_gr = self.group
1850 cur_gr = self.group
1851 groups.insert(0, cur_gr)
1851 groups.insert(0, cur_gr)
1852 while 1:
1852 while 1:
1853 gr = getattr(cur_gr, 'parent_group', None)
1853 gr = getattr(cur_gr, 'parent_group', None)
1854 cur_gr = cur_gr.parent_group
1854 cur_gr = cur_gr.parent_group
1855 if gr is None:
1855 if gr is None:
1856 break
1856 break
1857 groups.insert(0, gr)
1857 groups.insert(0, gr)
1858
1858
1859 return groups
1859 return groups
1860
1860
1861 @property
1861 @property
1862 def groups_and_repo(self):
1862 def groups_and_repo(self):
1863 return self.groups_with_parents, self
1863 return self.groups_with_parents, self
1864
1864
1865 @LazyProperty
1865 @LazyProperty
1866 def repo_path(self):
1866 def repo_path(self):
1867 """
1867 """
1868 Returns base full path for that repository means where it actually
1868 Returns base full path for that repository means where it actually
1869 exists on a filesystem
1869 exists on a filesystem
1870 """
1870 """
1871 q = Session().query(RhodeCodeUi).filter(
1871 q = Session().query(RhodeCodeUi).filter(
1872 RhodeCodeUi.ui_key == self.NAME_SEP)
1872 RhodeCodeUi.ui_key == self.NAME_SEP)
1873 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1873 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1874 return q.one().ui_value
1874 return q.one().ui_value
1875
1875
1876 @property
1876 @property
1877 def repo_full_path(self):
1877 def repo_full_path(self):
1878 p = [self.repo_path]
1878 p = [self.repo_path]
1879 # we need to split the name by / since this is how we store the
1879 # we need to split the name by / since this is how we store the
1880 # names in the database, but that eventually needs to be converted
1880 # names in the database, but that eventually needs to be converted
1881 # into a valid system path
1881 # into a valid system path
1882 p += self.repo_name.split(self.NAME_SEP)
1882 p += self.repo_name.split(self.NAME_SEP)
1883 return os.path.join(*map(safe_unicode, p))
1883 return os.path.join(*map(safe_unicode, p))
1884
1884
1885 @property
1885 @property
1886 def cache_keys(self):
1886 def cache_keys(self):
1887 """
1887 """
1888 Returns associated cache keys for that repo
1888 Returns associated cache keys for that repo
1889 """
1889 """
1890 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1890 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1891 repo_id=self.repo_id)
1891 repo_id=self.repo_id)
1892 return CacheKey.query()\
1892 return CacheKey.query()\
1893 .filter(CacheKey.cache_args == invalidation_namespace)\
1893 .filter(CacheKey.cache_args == invalidation_namespace)\
1894 .order_by(CacheKey.cache_key)\
1894 .order_by(CacheKey.cache_key)\
1895 .all()
1895 .all()
1896
1896
1897 @property
1897 @property
1898 def cached_diffs_relative_dir(self):
1898 def cached_diffs_relative_dir(self):
1899 """
1899 """
1900 Return a relative to the repository store path of cached diffs
1900 Return a relative to the repository store path of cached diffs
1901 used for safe display for users, who shouldn't know the absolute store
1901 used for safe display for users, who shouldn't know the absolute store
1902 path
1902 path
1903 """
1903 """
1904 return os.path.join(
1904 return os.path.join(
1905 os.path.dirname(self.repo_name),
1905 os.path.dirname(self.repo_name),
1906 self.cached_diffs_dir.split(os.path.sep)[-1])
1906 self.cached_diffs_dir.split(os.path.sep)[-1])
1907
1907
1908 @property
1908 @property
1909 def cached_diffs_dir(self):
1909 def cached_diffs_dir(self):
1910 path = self.repo_full_path
1910 path = self.repo_full_path
1911 return os.path.join(
1911 return os.path.join(
1912 os.path.dirname(path),
1912 os.path.dirname(path),
1913 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1913 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1914
1914
1915 def cached_diffs(self):
1915 def cached_diffs(self):
1916 diff_cache_dir = self.cached_diffs_dir
1916 diff_cache_dir = self.cached_diffs_dir
1917 if os.path.isdir(diff_cache_dir):
1917 if os.path.isdir(diff_cache_dir):
1918 return os.listdir(diff_cache_dir)
1918 return os.listdir(diff_cache_dir)
1919 return []
1919 return []
1920
1920
1921 def shadow_repos(self):
1921 def shadow_repos(self):
1922 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1922 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1923 return [
1923 return [
1924 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1924 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1925 if x.startswith(shadow_repos_pattern)]
1925 if x.startswith(shadow_repos_pattern)]
1926
1926
1927 def get_new_name(self, repo_name):
1927 def get_new_name(self, repo_name):
1928 """
1928 """
1929 returns new full repository name based on assigned group and new new
1929 returns new full repository name based on assigned group and new new
1930
1930
1931 :param group_name:
1931 :param group_name:
1932 """
1932 """
1933 path_prefix = self.group.full_path_splitted if self.group else []
1933 path_prefix = self.group.full_path_splitted if self.group else []
1934 return self.NAME_SEP.join(path_prefix + [repo_name])
1934 return self.NAME_SEP.join(path_prefix + [repo_name])
1935
1935
1936 @property
1936 @property
1937 def _config(self):
1937 def _config(self):
1938 """
1938 """
1939 Returns db based config object.
1939 Returns db based config object.
1940 """
1940 """
1941 from rhodecode.lib.utils import make_db_config
1941 from rhodecode.lib.utils import make_db_config
1942 return make_db_config(clear_session=False, repo=self)
1942 return make_db_config(clear_session=False, repo=self)
1943
1943
1944 def permissions(self, with_admins=True, with_owner=True,
1944 def permissions(self, with_admins=True, with_owner=True,
1945 expand_from_user_groups=False):
1945 expand_from_user_groups=False):
1946 """
1946 """
1947 Permissions for repositories
1947 Permissions for repositories
1948 """
1948 """
1949 _admin_perm = 'repository.admin'
1949 _admin_perm = 'repository.admin'
1950
1950
1951 owner_row = []
1951 owner_row = []
1952 if with_owner:
1952 if with_owner:
1953 usr = AttributeDict(self.user.get_dict())
1953 usr = AttributeDict(self.user.get_dict())
1954 usr.owner_row = True
1954 usr.owner_row = True
1955 usr.permission = _admin_perm
1955 usr.permission = _admin_perm
1956 usr.permission_id = None
1956 usr.permission_id = None
1957 owner_row.append(usr)
1957 owner_row.append(usr)
1958
1958
1959 super_admin_ids = []
1959 super_admin_ids = []
1960 super_admin_rows = []
1960 super_admin_rows = []
1961 if with_admins:
1961 if with_admins:
1962 for usr in User.get_all_super_admins():
1962 for usr in User.get_all_super_admins():
1963 super_admin_ids.append(usr.user_id)
1963 super_admin_ids.append(usr.user_id)
1964 # if this admin is also owner, don't double the record
1964 # if this admin is also owner, don't double the record
1965 if usr.user_id == owner_row[0].user_id:
1965 if usr.user_id == owner_row[0].user_id:
1966 owner_row[0].admin_row = True
1966 owner_row[0].admin_row = True
1967 else:
1967 else:
1968 usr = AttributeDict(usr.get_dict())
1968 usr = AttributeDict(usr.get_dict())
1969 usr.admin_row = True
1969 usr.admin_row = True
1970 usr.permission = _admin_perm
1970 usr.permission = _admin_perm
1971 usr.permission_id = None
1971 usr.permission_id = None
1972 super_admin_rows.append(usr)
1972 super_admin_rows.append(usr)
1973
1973
1974 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1974 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1975 q = q.options(joinedload(UserRepoToPerm.repository),
1975 q = q.options(joinedload(UserRepoToPerm.repository),
1976 joinedload(UserRepoToPerm.user),
1976 joinedload(UserRepoToPerm.user),
1977 joinedload(UserRepoToPerm.permission),)
1977 joinedload(UserRepoToPerm.permission),)
1978
1978
1979 # get owners and admins and permissions. We do a trick of re-writing
1979 # get owners and admins and permissions. We do a trick of re-writing
1980 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1980 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1981 # has a global reference and changing one object propagates to all
1981 # has a global reference and changing one object propagates to all
1982 # others. This means if admin is also an owner admin_row that change
1982 # others. This means if admin is also an owner admin_row that change
1983 # would propagate to both objects
1983 # would propagate to both objects
1984 perm_rows = []
1984 perm_rows = []
1985 for _usr in q.all():
1985 for _usr in q.all():
1986 usr = AttributeDict(_usr.user.get_dict())
1986 usr = AttributeDict(_usr.user.get_dict())
1987 # if this user is also owner/admin, mark as duplicate record
1987 # if this user is also owner/admin, mark as duplicate record
1988 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1988 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1989 usr.duplicate_perm = True
1989 usr.duplicate_perm = True
1990 # also check if this permission is maybe used by branch_permissions
1990 # also check if this permission is maybe used by branch_permissions
1991 if _usr.branch_perm_entry:
1991 if _usr.branch_perm_entry:
1992 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1992 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
1993
1993
1994 usr.permission = _usr.permission.permission_name
1994 usr.permission = _usr.permission.permission_name
1995 usr.permission_id = _usr.repo_to_perm_id
1995 usr.permission_id = _usr.repo_to_perm_id
1996 perm_rows.append(usr)
1996 perm_rows.append(usr)
1997
1997
1998 # filter the perm rows by 'default' first and then sort them by
1998 # filter the perm rows by 'default' first and then sort them by
1999 # admin,write,read,none permissions sorted again alphabetically in
1999 # admin,write,read,none permissions sorted again alphabetically in
2000 # each group
2000 # each group
2001 perm_rows = sorted(perm_rows, key=display_user_sort)
2001 perm_rows = sorted(perm_rows, key=display_user_sort)
2002
2002
2003 user_groups_rows = []
2003 user_groups_rows = []
2004 if expand_from_user_groups:
2004 if expand_from_user_groups:
2005 for ug in self.permission_user_groups(with_members=True):
2005 for ug in self.permission_user_groups(with_members=True):
2006 for user_data in ug.members:
2006 for user_data in ug.members:
2007 user_groups_rows.append(user_data)
2007 user_groups_rows.append(user_data)
2008
2008
2009 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2009 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2010
2010
2011 def permission_user_groups(self, with_members=True):
2011 def permission_user_groups(self, with_members=True):
2012 q = UserGroupRepoToPerm.query()\
2012 q = UserGroupRepoToPerm.query()\
2013 .filter(UserGroupRepoToPerm.repository == self)
2013 .filter(UserGroupRepoToPerm.repository == self)
2014 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2014 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2015 joinedload(UserGroupRepoToPerm.users_group),
2015 joinedload(UserGroupRepoToPerm.users_group),
2016 joinedload(UserGroupRepoToPerm.permission),)
2016 joinedload(UserGroupRepoToPerm.permission),)
2017
2017
2018 perm_rows = []
2018 perm_rows = []
2019 for _user_group in q.all():
2019 for _user_group in q.all():
2020 entry = AttributeDict(_user_group.users_group.get_dict())
2020 entry = AttributeDict(_user_group.users_group.get_dict())
2021 entry.permission = _user_group.permission.permission_name
2021 entry.permission = _user_group.permission.permission_name
2022 if with_members:
2022 if with_members:
2023 entry.members = [x.user.get_dict()
2023 entry.members = [x.user.get_dict()
2024 for x in _user_group.users_group.members]
2024 for x in _user_group.users_group.members]
2025 perm_rows.append(entry)
2025 perm_rows.append(entry)
2026
2026
2027 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2027 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2028 return perm_rows
2028 return perm_rows
2029
2029
2030 def get_api_data(self, include_secrets=False):
2030 def get_api_data(self, include_secrets=False):
2031 """
2031 """
2032 Common function for generating repo api data
2032 Common function for generating repo api data
2033
2033
2034 :param include_secrets: See :meth:`User.get_api_data`.
2034 :param include_secrets: See :meth:`User.get_api_data`.
2035
2035
2036 """
2036 """
2037 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2037 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2038 # move this methods on models level.
2038 # move this methods on models level.
2039 from rhodecode.model.settings import SettingsModel
2039 from rhodecode.model.settings import SettingsModel
2040 from rhodecode.model.repo import RepoModel
2040 from rhodecode.model.repo import RepoModel
2041
2041
2042 repo = self
2042 repo = self
2043 _user_id, _time, _reason = self.locked
2043 _user_id, _time, _reason = self.locked
2044
2044
2045 data = {
2045 data = {
2046 'repo_id': repo.repo_id,
2046 'repo_id': repo.repo_id,
2047 'repo_name': repo.repo_name,
2047 'repo_name': repo.repo_name,
2048 'repo_type': repo.repo_type,
2048 'repo_type': repo.repo_type,
2049 'clone_uri': repo.clone_uri or '',
2049 'clone_uri': repo.clone_uri or '',
2050 'push_uri': repo.push_uri or '',
2050 'push_uri': repo.push_uri or '',
2051 'url': RepoModel().get_url(self),
2051 'url': RepoModel().get_url(self),
2052 'private': repo.private,
2052 'private': repo.private,
2053 'created_on': repo.created_on,
2053 'created_on': repo.created_on,
2054 'description': repo.description_safe,
2054 'description': repo.description_safe,
2055 'landing_rev': repo.landing_rev,
2055 'landing_rev': repo.landing_rev,
2056 'owner': repo.user.username,
2056 'owner': repo.user.username,
2057 'fork_of': repo.fork.repo_name if repo.fork else None,
2057 'fork_of': repo.fork.repo_name if repo.fork else None,
2058 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2058 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2059 'enable_statistics': repo.enable_statistics,
2059 'enable_statistics': repo.enable_statistics,
2060 'enable_locking': repo.enable_locking,
2060 'enable_locking': repo.enable_locking,
2061 'enable_downloads': repo.enable_downloads,
2061 'enable_downloads': repo.enable_downloads,
2062 'last_changeset': repo.changeset_cache,
2062 'last_changeset': repo.changeset_cache,
2063 'locked_by': User.get(_user_id).get_api_data(
2063 'locked_by': User.get(_user_id).get_api_data(
2064 include_secrets=include_secrets) if _user_id else None,
2064 include_secrets=include_secrets) if _user_id else None,
2065 'locked_date': time_to_datetime(_time) if _time else None,
2065 'locked_date': time_to_datetime(_time) if _time else None,
2066 'lock_reason': _reason if _reason else None,
2066 'lock_reason': _reason if _reason else None,
2067 }
2067 }
2068
2068
2069 # TODO: mikhail: should be per-repo settings here
2069 # TODO: mikhail: should be per-repo settings here
2070 rc_config = SettingsModel().get_all_settings()
2070 rc_config = SettingsModel().get_all_settings()
2071 repository_fields = str2bool(
2071 repository_fields = str2bool(
2072 rc_config.get('rhodecode_repository_fields'))
2072 rc_config.get('rhodecode_repository_fields'))
2073 if repository_fields:
2073 if repository_fields:
2074 for f in self.extra_fields:
2074 for f in self.extra_fields:
2075 data[f.field_key_prefixed] = f.field_value
2075 data[f.field_key_prefixed] = f.field_value
2076
2076
2077 return data
2077 return data
2078
2078
2079 @classmethod
2079 @classmethod
2080 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2080 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2081 if not lock_time:
2081 if not lock_time:
2082 lock_time = time.time()
2082 lock_time = time.time()
2083 if not lock_reason:
2083 if not lock_reason:
2084 lock_reason = cls.LOCK_AUTOMATIC
2084 lock_reason = cls.LOCK_AUTOMATIC
2085 repo.locked = [user_id, lock_time, lock_reason]
2085 repo.locked = [user_id, lock_time, lock_reason]
2086 Session().add(repo)
2086 Session().add(repo)
2087 Session().commit()
2087 Session().commit()
2088
2088
2089 @classmethod
2089 @classmethod
2090 def unlock(cls, repo):
2090 def unlock(cls, repo):
2091 repo.locked = None
2091 repo.locked = None
2092 Session().add(repo)
2092 Session().add(repo)
2093 Session().commit()
2093 Session().commit()
2094
2094
2095 @classmethod
2095 @classmethod
2096 def getlock(cls, repo):
2096 def getlock(cls, repo):
2097 return repo.locked
2097 return repo.locked
2098
2098
2099 def is_user_lock(self, user_id):
2099 def is_user_lock(self, user_id):
2100 if self.lock[0]:
2100 if self.lock[0]:
2101 lock_user_id = safe_int(self.lock[0])
2101 lock_user_id = safe_int(self.lock[0])
2102 user_id = safe_int(user_id)
2102 user_id = safe_int(user_id)
2103 # both are ints, and they are equal
2103 # both are ints, and they are equal
2104 return all([lock_user_id, user_id]) and lock_user_id == user_id
2104 return all([lock_user_id, user_id]) and lock_user_id == user_id
2105
2105
2106 return False
2106 return False
2107
2107
2108 def get_locking_state(self, action, user_id, only_when_enabled=True):
2108 def get_locking_state(self, action, user_id, only_when_enabled=True):
2109 """
2109 """
2110 Checks locking on this repository, if locking is enabled and lock is
2110 Checks locking on this repository, if locking is enabled and lock is
2111 present returns a tuple of make_lock, locked, locked_by.
2111 present returns a tuple of make_lock, locked, locked_by.
2112 make_lock can have 3 states None (do nothing) True, make lock
2112 make_lock can have 3 states None (do nothing) True, make lock
2113 False release lock, This value is later propagated to hooks, which
2113 False release lock, This value is later propagated to hooks, which
2114 do the locking. Think about this as signals passed to hooks what to do.
2114 do the locking. Think about this as signals passed to hooks what to do.
2115
2115
2116 """
2116 """
2117 # TODO: johbo: This is part of the business logic and should be moved
2117 # TODO: johbo: This is part of the business logic and should be moved
2118 # into the RepositoryModel.
2118 # into the RepositoryModel.
2119
2119
2120 if action not in ('push', 'pull'):
2120 if action not in ('push', 'pull'):
2121 raise ValueError("Invalid action value: %s" % repr(action))
2121 raise ValueError("Invalid action value: %s" % repr(action))
2122
2122
2123 # defines if locked error should be thrown to user
2123 # defines if locked error should be thrown to user
2124 currently_locked = False
2124 currently_locked = False
2125 # defines if new lock should be made, tri-state
2125 # defines if new lock should be made, tri-state
2126 make_lock = None
2126 make_lock = None
2127 repo = self
2127 repo = self
2128 user = User.get(user_id)
2128 user = User.get(user_id)
2129
2129
2130 lock_info = repo.locked
2130 lock_info = repo.locked
2131
2131
2132 if repo and (repo.enable_locking or not only_when_enabled):
2132 if repo and (repo.enable_locking or not only_when_enabled):
2133 if action == 'push':
2133 if action == 'push':
2134 # check if it's already locked !, if it is compare users
2134 # check if it's already locked !, if it is compare users
2135 locked_by_user_id = lock_info[0]
2135 locked_by_user_id = lock_info[0]
2136 if user.user_id == locked_by_user_id:
2136 if user.user_id == locked_by_user_id:
2137 log.debug(
2137 log.debug(
2138 'Got `push` action from user %s, now unlocking', user)
2138 'Got `push` action from user %s, now unlocking', user)
2139 # unlock if we have push from user who locked
2139 # unlock if we have push from user who locked
2140 make_lock = False
2140 make_lock = False
2141 else:
2141 else:
2142 # we're not the same user who locked, ban with
2142 # we're not the same user who locked, ban with
2143 # code defined in settings (default is 423 HTTP Locked) !
2143 # code defined in settings (default is 423 HTTP Locked) !
2144 log.debug('Repo %s is currently locked by %s', repo, user)
2144 log.debug('Repo %s is currently locked by %s', repo, user)
2145 currently_locked = True
2145 currently_locked = True
2146 elif action == 'pull':
2146 elif action == 'pull':
2147 # [0] user [1] date
2147 # [0] user [1] date
2148 if lock_info[0] and lock_info[1]:
2148 if lock_info[0] and lock_info[1]:
2149 log.debug('Repo %s is currently locked by %s', repo, user)
2149 log.debug('Repo %s is currently locked by %s', repo, user)
2150 currently_locked = True
2150 currently_locked = True
2151 else:
2151 else:
2152 log.debug('Setting lock on repo %s by %s', repo, user)
2152 log.debug('Setting lock on repo %s by %s', repo, user)
2153 make_lock = True
2153 make_lock = True
2154
2154
2155 else:
2155 else:
2156 log.debug('Repository %s do not have locking enabled', repo)
2156 log.debug('Repository %s do not have locking enabled', repo)
2157
2157
2158 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2158 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2159 make_lock, currently_locked, lock_info)
2159 make_lock, currently_locked, lock_info)
2160
2160
2161 from rhodecode.lib.auth import HasRepoPermissionAny
2161 from rhodecode.lib.auth import HasRepoPermissionAny
2162 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2162 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2163 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2163 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2164 # if we don't have at least write permission we cannot make a lock
2164 # if we don't have at least write permission we cannot make a lock
2165 log.debug('lock state reset back to FALSE due to lack '
2165 log.debug('lock state reset back to FALSE due to lack '
2166 'of at least read permission')
2166 'of at least read permission')
2167 make_lock = False
2167 make_lock = False
2168
2168
2169 return make_lock, currently_locked, lock_info
2169 return make_lock, currently_locked, lock_info
2170
2170
2171 @property
2171 @property
2172 def last_db_change(self):
2172 def last_db_change(self):
2173 return self.updated_on
2173 return self.updated_on
2174
2174
2175 @property
2175 @property
2176 def clone_uri_hidden(self):
2176 def clone_uri_hidden(self):
2177 clone_uri = self.clone_uri
2177 clone_uri = self.clone_uri
2178 if clone_uri:
2178 if clone_uri:
2179 import urlobject
2179 import urlobject
2180 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2180 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2181 if url_obj.password:
2181 if url_obj.password:
2182 clone_uri = url_obj.with_password('*****')
2182 clone_uri = url_obj.with_password('*****')
2183 return clone_uri
2183 return clone_uri
2184
2184
2185 @property
2185 @property
2186 def push_uri_hidden(self):
2186 def push_uri_hidden(self):
2187 push_uri = self.push_uri
2187 push_uri = self.push_uri
2188 if push_uri:
2188 if push_uri:
2189 import urlobject
2189 import urlobject
2190 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2190 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2191 if url_obj.password:
2191 if url_obj.password:
2192 push_uri = url_obj.with_password('*****')
2192 push_uri = url_obj.with_password('*****')
2193 return push_uri
2193 return push_uri
2194
2194
2195 def clone_url(self, **override):
2195 def clone_url(self, **override):
2196 from rhodecode.model.settings import SettingsModel
2196 from rhodecode.model.settings import SettingsModel
2197
2197
2198 uri_tmpl = None
2198 uri_tmpl = None
2199 if 'with_id' in override:
2199 if 'with_id' in override:
2200 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2200 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2201 del override['with_id']
2201 del override['with_id']
2202
2202
2203 if 'uri_tmpl' in override:
2203 if 'uri_tmpl' in override:
2204 uri_tmpl = override['uri_tmpl']
2204 uri_tmpl = override['uri_tmpl']
2205 del override['uri_tmpl']
2205 del override['uri_tmpl']
2206
2206
2207 ssh = False
2207 ssh = False
2208 if 'ssh' in override:
2208 if 'ssh' in override:
2209 ssh = True
2209 ssh = True
2210 del override['ssh']
2210 del override['ssh']
2211
2211
2212 # we didn't override our tmpl from **overrides
2212 # we didn't override our tmpl from **overrides
2213 if not uri_tmpl:
2213 if not uri_tmpl:
2214 rc_config = SettingsModel().get_all_settings(cache=True)
2214 rc_config = SettingsModel().get_all_settings(cache=True)
2215 if ssh:
2215 if ssh:
2216 uri_tmpl = rc_config.get(
2216 uri_tmpl = rc_config.get(
2217 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2217 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2218 else:
2218 else:
2219 uri_tmpl = rc_config.get(
2219 uri_tmpl = rc_config.get(
2220 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2220 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2221
2221
2222 request = get_current_request()
2222 request = get_current_request()
2223 return get_clone_url(request=request,
2223 return get_clone_url(request=request,
2224 uri_tmpl=uri_tmpl,
2224 uri_tmpl=uri_tmpl,
2225 repo_name=self.repo_name,
2225 repo_name=self.repo_name,
2226 repo_id=self.repo_id, **override)
2226 repo_id=self.repo_id, **override)
2227
2227
2228 def set_state(self, state):
2228 def set_state(self, state):
2229 self.repo_state = state
2229 self.repo_state = state
2230 Session().add(self)
2230 Session().add(self)
2231 #==========================================================================
2231 #==========================================================================
2232 # SCM PROPERTIES
2232 # SCM PROPERTIES
2233 #==========================================================================
2233 #==========================================================================
2234
2234
2235 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2235 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2236 return get_commit_safe(
2236 return get_commit_safe(
2237 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2237 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2238
2238
2239 def get_changeset(self, rev=None, pre_load=None):
2239 def get_changeset(self, rev=None, pre_load=None):
2240 warnings.warn("Use get_commit", DeprecationWarning)
2240 warnings.warn("Use get_commit", DeprecationWarning)
2241 commit_id = None
2241 commit_id = None
2242 commit_idx = None
2242 commit_idx = None
2243 if isinstance(rev, compat.string_types):
2243 if isinstance(rev, compat.string_types):
2244 commit_id = rev
2244 commit_id = rev
2245 else:
2245 else:
2246 commit_idx = rev
2246 commit_idx = rev
2247 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2247 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2248 pre_load=pre_load)
2248 pre_load=pre_load)
2249
2249
2250 def get_landing_commit(self):
2250 def get_landing_commit(self):
2251 """
2251 """
2252 Returns landing commit, or if that doesn't exist returns the tip
2252 Returns landing commit, or if that doesn't exist returns the tip
2253 """
2253 """
2254 _rev_type, _rev = self.landing_rev
2254 _rev_type, _rev = self.landing_rev
2255 commit = self.get_commit(_rev)
2255 commit = self.get_commit(_rev)
2256 if isinstance(commit, EmptyCommit):
2256 if isinstance(commit, EmptyCommit):
2257 return self.get_commit()
2257 return self.get_commit()
2258 return commit
2258 return commit
2259
2259
2260 def update_commit_cache(self, cs_cache=None, config=None):
2260 def update_commit_cache(self, cs_cache=None, config=None):
2261 """
2261 """
2262 Update cache of last changeset for repository, keys should be::
2262 Update cache of last changeset for repository, keys should be::
2263
2263
2264 short_id
2264 short_id
2265 raw_id
2265 raw_id
2266 revision
2266 revision
2267 parents
2267 parents
2268 message
2268 message
2269 date
2269 date
2270 author
2270 author
2271
2271
2272 :param cs_cache:
2272 :param cs_cache:
2273 """
2273 """
2274 from rhodecode.lib.vcs.backends.base import BaseChangeset
2274 from rhodecode.lib.vcs.backends.base import BaseChangeset
2275 if cs_cache is None:
2275 if cs_cache is None:
2276 # use no-cache version here
2276 # use no-cache version here
2277 scm_repo = self.scm_instance(cache=False, config=config)
2277 scm_repo = self.scm_instance(cache=False, config=config)
2278
2278
2279 empty = not scm_repo or scm_repo.is_empty()
2279 empty = not scm_repo or scm_repo.is_empty()
2280 if not empty:
2280 if not empty:
2281 cs_cache = scm_repo.get_commit(
2281 cs_cache = scm_repo.get_commit(
2282 pre_load=["author", "date", "message", "parents"])
2282 pre_load=["author", "date", "message", "parents"])
2283 else:
2283 else:
2284 cs_cache = EmptyCommit()
2284 cs_cache = EmptyCommit()
2285
2285
2286 if isinstance(cs_cache, BaseChangeset):
2286 if isinstance(cs_cache, BaseChangeset):
2287 cs_cache = cs_cache.__json__()
2287 cs_cache = cs_cache.__json__()
2288
2288
2289 def is_outdated(new_cs_cache):
2289 def is_outdated(new_cs_cache):
2290 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2290 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2291 new_cs_cache['revision'] != self.changeset_cache['revision']):
2291 new_cs_cache['revision'] != self.changeset_cache['revision']):
2292 return True
2292 return True
2293 return False
2293 return False
2294
2294
2295 # check if we have maybe already latest cached revision
2295 # check if we have maybe already latest cached revision
2296 if is_outdated(cs_cache) or not self.changeset_cache:
2296 if is_outdated(cs_cache) or not self.changeset_cache:
2297 _default = datetime.datetime.utcnow()
2297 _default = datetime.datetime.utcnow()
2298 last_change = cs_cache.get('date') or _default
2298 last_change = cs_cache.get('date') or _default
2299 if self.updated_on and self.updated_on > last_change:
2299 if self.updated_on and self.updated_on > last_change:
2300 # we check if last update is newer than the new value
2300 # we check if last update is newer than the new value
2301 # if yes, we use the current timestamp instead. Imagine you get
2301 # if yes, we use the current timestamp instead. Imagine you get
2302 # old commit pushed 1y ago, we'd set last update 1y to ago.
2302 # old commit pushed 1y ago, we'd set last update 1y to ago.
2303 last_change = _default
2303 last_change = _default
2304 log.debug('updated repo %s with new commit cache %s',
2304 log.debug('updated repo %s with new commit cache %s',
2305 self.repo_name, cs_cache)
2305 self.repo_name, cs_cache)
2306 self.updated_on = last_change
2306 self.updated_on = last_change
2307 self.changeset_cache = cs_cache
2307 self.changeset_cache = cs_cache
2308 Session().add(self)
2308 Session().add(self)
2309 Session().commit()
2309 Session().commit()
2310 else:
2310 else:
2311 log.debug('Skipping update_commit_cache for repo:`%s` '
2311 log.debug('Skipping update_commit_cache for repo:`%s` '
2312 'commit already with latest changes', self.repo_name)
2312 'commit already with latest changes', self.repo_name)
2313
2313
2314 @property
2314 @property
2315 def tip(self):
2315 def tip(self):
2316 return self.get_commit('tip')
2316 return self.get_commit('tip')
2317
2317
2318 @property
2318 @property
2319 def author(self):
2319 def author(self):
2320 return self.tip.author
2320 return self.tip.author
2321
2321
2322 @property
2322 @property
2323 def last_change(self):
2323 def last_change(self):
2324 return self.scm_instance().last_change
2324 return self.scm_instance().last_change
2325
2325
2326 def get_comments(self, revisions=None):
2326 def get_comments(self, revisions=None):
2327 """
2327 """
2328 Returns comments for this repository grouped by revisions
2328 Returns comments for this repository grouped by revisions
2329
2329
2330 :param revisions: filter query by revisions only
2330 :param revisions: filter query by revisions only
2331 """
2331 """
2332 cmts = ChangesetComment.query()\
2332 cmts = ChangesetComment.query()\
2333 .filter(ChangesetComment.repo == self)
2333 .filter(ChangesetComment.repo == self)
2334 if revisions:
2334 if revisions:
2335 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2335 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2336 grouped = collections.defaultdict(list)
2336 grouped = collections.defaultdict(list)
2337 for cmt in cmts.all():
2337 for cmt in cmts.all():
2338 grouped[cmt.revision].append(cmt)
2338 grouped[cmt.revision].append(cmt)
2339 return grouped
2339 return grouped
2340
2340
2341 def statuses(self, revisions=None):
2341 def statuses(self, revisions=None):
2342 """
2342 """
2343 Returns statuses for this repository
2343 Returns statuses for this repository
2344
2344
2345 :param revisions: list of revisions to get statuses for
2345 :param revisions: list of revisions to get statuses for
2346 """
2346 """
2347 statuses = ChangesetStatus.query()\
2347 statuses = ChangesetStatus.query()\
2348 .filter(ChangesetStatus.repo == self)\
2348 .filter(ChangesetStatus.repo == self)\
2349 .filter(ChangesetStatus.version == 0)
2349 .filter(ChangesetStatus.version == 0)
2350
2350
2351 if revisions:
2351 if revisions:
2352 # Try doing the filtering in chunks to avoid hitting limits
2352 # Try doing the filtering in chunks to avoid hitting limits
2353 size = 500
2353 size = 500
2354 status_results = []
2354 status_results = []
2355 for chunk in xrange(0, len(revisions), size):
2355 for chunk in xrange(0, len(revisions), size):
2356 status_results += statuses.filter(
2356 status_results += statuses.filter(
2357 ChangesetStatus.revision.in_(
2357 ChangesetStatus.revision.in_(
2358 revisions[chunk: chunk+size])
2358 revisions[chunk: chunk+size])
2359 ).all()
2359 ).all()
2360 else:
2360 else:
2361 status_results = statuses.all()
2361 status_results = statuses.all()
2362
2362
2363 grouped = {}
2363 grouped = {}
2364
2364
2365 # maybe we have open new pullrequest without a status?
2365 # maybe we have open new pullrequest without a status?
2366 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2366 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2367 status_lbl = ChangesetStatus.get_status_lbl(stat)
2367 status_lbl = ChangesetStatus.get_status_lbl(stat)
2368 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2368 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2369 for rev in pr.revisions:
2369 for rev in pr.revisions:
2370 pr_id = pr.pull_request_id
2370 pr_id = pr.pull_request_id
2371 pr_repo = pr.target_repo.repo_name
2371 pr_repo = pr.target_repo.repo_name
2372 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2372 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2373
2373
2374 for stat in status_results:
2374 for stat in status_results:
2375 pr_id = pr_repo = None
2375 pr_id = pr_repo = None
2376 if stat.pull_request:
2376 if stat.pull_request:
2377 pr_id = stat.pull_request.pull_request_id
2377 pr_id = stat.pull_request.pull_request_id
2378 pr_repo = stat.pull_request.target_repo.repo_name
2378 pr_repo = stat.pull_request.target_repo.repo_name
2379 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2379 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2380 pr_id, pr_repo]
2380 pr_id, pr_repo]
2381 return grouped
2381 return grouped
2382
2382
2383 # ==========================================================================
2383 # ==========================================================================
2384 # SCM CACHE INSTANCE
2384 # SCM CACHE INSTANCE
2385 # ==========================================================================
2385 # ==========================================================================
2386
2386
2387 def scm_instance(self, **kwargs):
2387 def scm_instance(self, **kwargs):
2388 import rhodecode
2388 import rhodecode
2389
2389
2390 # Passing a config will not hit the cache currently only used
2390 # Passing a config will not hit the cache currently only used
2391 # for repo2dbmapper
2391 # for repo2dbmapper
2392 config = kwargs.pop('config', None)
2392 config = kwargs.pop('config', None)
2393 cache = kwargs.pop('cache', None)
2393 cache = kwargs.pop('cache', None)
2394 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2394 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2395 # if cache is NOT defined use default global, else we have a full
2395 # if cache is NOT defined use default global, else we have a full
2396 # control over cache behaviour
2396 # control over cache behaviour
2397 if cache is None and full_cache and not config:
2397 if cache is None and full_cache and not config:
2398 return self._get_instance_cached()
2398 return self._get_instance_cached()
2399 return self._get_instance(cache=bool(cache), config=config)
2399 return self._get_instance(cache=bool(cache), config=config)
2400
2400
2401 def _get_instance_cached(self):
2401 def _get_instance_cached(self):
2402 from rhodecode.lib import rc_cache
2402 from rhodecode.lib import rc_cache
2403
2403
2404 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2404 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2405 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2405 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2406 repo_id=self.repo_id)
2406 repo_id=self.repo_id)
2407 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2407 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2408
2408
2409 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2409 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2410 def get_instance_cached(repo_id, context_id):
2410 def get_instance_cached(repo_id, context_id):
2411 return self._get_instance()
2411 return self._get_instance()
2412
2412
2413 # we must use thread scoped cache here,
2413 # we must use thread scoped cache here,
2414 # because each thread of gevent needs it's own not shared connection and cache
2414 # because each thread of gevent needs it's own not shared connection and cache
2415 # we also alter `args` so the cache key is individual for every green thread.
2415 # we also alter `args` so the cache key is individual for every green thread.
2416 inv_context_manager = rc_cache.InvalidationContext(
2416 inv_context_manager = rc_cache.InvalidationContext(
2417 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2417 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2418 thread_scoped=True)
2418 thread_scoped=True)
2419 with inv_context_manager as invalidation_context:
2419 with inv_context_manager as invalidation_context:
2420 args = (self.repo_id, inv_context_manager.cache_key)
2420 args = (self.repo_id, inv_context_manager.cache_key)
2421 # re-compute and store cache if we get invalidate signal
2421 # re-compute and store cache if we get invalidate signal
2422 if invalidation_context.should_invalidate():
2422 if invalidation_context.should_invalidate():
2423 instance = get_instance_cached.refresh(*args)
2423 instance = get_instance_cached.refresh(*args)
2424 else:
2424 else:
2425 instance = get_instance_cached(*args)
2425 instance = get_instance_cached(*args)
2426
2426
2427 log.debug(
2427 log.debug(
2428 'Repo instance fetched in %.3fs', inv_context_manager.compute_time)
2428 'Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2429 return instance
2429 return instance
2430
2430
2431 def _get_instance(self, cache=True, config=None):
2431 def _get_instance(self, cache=True, config=None):
2432 config = config or self._config
2432 config = config or self._config
2433 custom_wire = {
2433 custom_wire = {
2434 'cache': cache # controls the vcs.remote cache
2434 'cache': cache # controls the vcs.remote cache
2435 }
2435 }
2436 repo = get_vcs_instance(
2436 repo = get_vcs_instance(
2437 repo_path=safe_str(self.repo_full_path),
2437 repo_path=safe_str(self.repo_full_path),
2438 config=config,
2438 config=config,
2439 with_wire=custom_wire,
2439 with_wire=custom_wire,
2440 create=False,
2440 create=False,
2441 _vcs_alias=self.repo_type)
2441 _vcs_alias=self.repo_type)
2442
2442
2443 return repo
2443 return repo
2444
2444
2445 def __json__(self):
2445 def __json__(self):
2446 return {'landing_rev': self.landing_rev}
2446 return {'landing_rev': self.landing_rev}
2447
2447
2448 def get_dict(self):
2448 def get_dict(self):
2449
2449
2450 # Since we transformed `repo_name` to a hybrid property, we need to
2450 # Since we transformed `repo_name` to a hybrid property, we need to
2451 # keep compatibility with the code which uses `repo_name` field.
2451 # keep compatibility with the code which uses `repo_name` field.
2452
2452
2453 result = super(Repository, self).get_dict()
2453 result = super(Repository, self).get_dict()
2454 result['repo_name'] = result.pop('_repo_name', None)
2454 result['repo_name'] = result.pop('_repo_name', None)
2455 return result
2455 return result
2456
2456
2457
2457
2458 class RepoGroup(Base, BaseModel):
2458 class RepoGroup(Base, BaseModel):
2459 __tablename__ = 'groups'
2459 __tablename__ = 'groups'
2460 __table_args__ = (
2460 __table_args__ = (
2461 UniqueConstraint('group_name', 'group_parent_id'),
2461 UniqueConstraint('group_name', 'group_parent_id'),
2462 base_table_args,
2462 base_table_args,
2463 )
2463 )
2464 __mapper_args__ = {'order_by': 'group_name'}
2464 __mapper_args__ = {'order_by': 'group_name'}
2465
2465
2466 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2466 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2467
2467
2468 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2468 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2469 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2469 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2470 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2470 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2471 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2471 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2472 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2472 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2473 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2473 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2474 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2474 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2475 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2475 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2476 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2476 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2477
2477
2478 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2478 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2479 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2479 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2480 parent_group = relationship('RepoGroup', remote_side=group_id)
2480 parent_group = relationship('RepoGroup', remote_side=group_id)
2481 user = relationship('User')
2481 user = relationship('User')
2482 integrations = relationship('Integration',
2482 integrations = relationship('Integration',
2483 cascade="all, delete, delete-orphan")
2483 cascade="all, delete, delete-orphan")
2484
2484
2485 def __init__(self, group_name='', parent_group=None):
2485 def __init__(self, group_name='', parent_group=None):
2486 self.group_name = group_name
2486 self.group_name = group_name
2487 self.parent_group = parent_group
2487 self.parent_group = parent_group
2488
2488
2489 def __unicode__(self):
2489 def __unicode__(self):
2490 return u"<%s('id:%s:%s')>" % (
2490 return u"<%s('id:%s:%s')>" % (
2491 self.__class__.__name__, self.group_id, self.group_name)
2491 self.__class__.__name__, self.group_id, self.group_name)
2492
2492
2493 @hybrid_property
2493 @hybrid_property
2494 def description_safe(self):
2494 def description_safe(self):
2495 from rhodecode.lib import helpers as h
2495 from rhodecode.lib import helpers as h
2496 return h.escape(self.group_description)
2496 return h.escape(self.group_description)
2497
2497
2498 @classmethod
2498 @classmethod
2499 def _generate_choice(cls, repo_group):
2499 def _generate_choice(cls, repo_group):
2500 from webhelpers.html import literal as _literal
2500 from webhelpers.html import literal as _literal
2501 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2501 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2502 return repo_group.group_id, _name(repo_group.full_path_splitted)
2502 return repo_group.group_id, _name(repo_group.full_path_splitted)
2503
2503
2504 @classmethod
2504 @classmethod
2505 def groups_choices(cls, groups=None, show_empty_group=True):
2505 def groups_choices(cls, groups=None, show_empty_group=True):
2506 if not groups:
2506 if not groups:
2507 groups = cls.query().all()
2507 groups = cls.query().all()
2508
2508
2509 repo_groups = []
2509 repo_groups = []
2510 if show_empty_group:
2510 if show_empty_group:
2511 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2511 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2512
2512
2513 repo_groups.extend([cls._generate_choice(x) for x in groups])
2513 repo_groups.extend([cls._generate_choice(x) for x in groups])
2514
2514
2515 repo_groups = sorted(
2515 repo_groups = sorted(
2516 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2516 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2517 return repo_groups
2517 return repo_groups
2518
2518
2519 @classmethod
2519 @classmethod
2520 def url_sep(cls):
2520 def url_sep(cls):
2521 return URL_SEP
2521 return URL_SEP
2522
2522
2523 @classmethod
2523 @classmethod
2524 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2524 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2525 if case_insensitive:
2525 if case_insensitive:
2526 gr = cls.query().filter(func.lower(cls.group_name)
2526 gr = cls.query().filter(func.lower(cls.group_name)
2527 == func.lower(group_name))
2527 == func.lower(group_name))
2528 else:
2528 else:
2529 gr = cls.query().filter(cls.group_name == group_name)
2529 gr = cls.query().filter(cls.group_name == group_name)
2530 if cache:
2530 if cache:
2531 name_key = _hash_key(group_name)
2531 name_key = _hash_key(group_name)
2532 gr = gr.options(
2532 gr = gr.options(
2533 FromCache("sql_cache_short", "get_group_%s" % name_key))
2533 FromCache("sql_cache_short", "get_group_%s" % name_key))
2534 return gr.scalar()
2534 return gr.scalar()
2535
2535
2536 @classmethod
2536 @classmethod
2537 def get_user_personal_repo_group(cls, user_id):
2537 def get_user_personal_repo_group(cls, user_id):
2538 user = User.get(user_id)
2538 user = User.get(user_id)
2539 if user.username == User.DEFAULT_USER:
2539 if user.username == User.DEFAULT_USER:
2540 return None
2540 return None
2541
2541
2542 return cls.query()\
2542 return cls.query()\
2543 .filter(cls.personal == true()) \
2543 .filter(cls.personal == true()) \
2544 .filter(cls.user == user) \
2544 .filter(cls.user == user) \
2545 .order_by(cls.group_id.asc()) \
2545 .order_by(cls.group_id.asc()) \
2546 .first()
2546 .first()
2547
2547
2548 @classmethod
2548 @classmethod
2549 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2549 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2550 case_insensitive=True):
2550 case_insensitive=True):
2551 q = RepoGroup.query()
2551 q = RepoGroup.query()
2552
2552
2553 if not isinstance(user_id, Optional):
2553 if not isinstance(user_id, Optional):
2554 q = q.filter(RepoGroup.user_id == user_id)
2554 q = q.filter(RepoGroup.user_id == user_id)
2555
2555
2556 if not isinstance(group_id, Optional):
2556 if not isinstance(group_id, Optional):
2557 q = q.filter(RepoGroup.group_parent_id == group_id)
2557 q = q.filter(RepoGroup.group_parent_id == group_id)
2558
2558
2559 if case_insensitive:
2559 if case_insensitive:
2560 q = q.order_by(func.lower(RepoGroup.group_name))
2560 q = q.order_by(func.lower(RepoGroup.group_name))
2561 else:
2561 else:
2562 q = q.order_by(RepoGroup.group_name)
2562 q = q.order_by(RepoGroup.group_name)
2563 return q.all()
2563 return q.all()
2564
2564
2565 @property
2565 @property
2566 def parents(self):
2566 def parents(self):
2567 parents_recursion_limit = 10
2567 parents_recursion_limit = 10
2568 groups = []
2568 groups = []
2569 if self.parent_group is None:
2569 if self.parent_group is None:
2570 return groups
2570 return groups
2571 cur_gr = self.parent_group
2571 cur_gr = self.parent_group
2572 groups.insert(0, cur_gr)
2572 groups.insert(0, cur_gr)
2573 cnt = 0
2573 cnt = 0
2574 while 1:
2574 while 1:
2575 cnt += 1
2575 cnt += 1
2576 gr = getattr(cur_gr, 'parent_group', None)
2576 gr = getattr(cur_gr, 'parent_group', None)
2577 cur_gr = cur_gr.parent_group
2577 cur_gr = cur_gr.parent_group
2578 if gr is None:
2578 if gr is None:
2579 break
2579 break
2580 if cnt == parents_recursion_limit:
2580 if cnt == parents_recursion_limit:
2581 # this will prevent accidental infinit loops
2581 # this will prevent accidental infinit loops
2582 log.error('more than %s parents found for group %s, stopping '
2582 log.error('more than %s parents found for group %s, stopping '
2583 'recursive parent fetching', parents_recursion_limit, self)
2583 'recursive parent fetching', parents_recursion_limit, self)
2584 break
2584 break
2585
2585
2586 groups.insert(0, gr)
2586 groups.insert(0, gr)
2587 return groups
2587 return groups
2588
2588
2589 @property
2589 @property
2590 def last_db_change(self):
2590 def last_db_change(self):
2591 return self.updated_on
2591 return self.updated_on
2592
2592
2593 @property
2593 @property
2594 def children(self):
2594 def children(self):
2595 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2595 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2596
2596
2597 @property
2597 @property
2598 def name(self):
2598 def name(self):
2599 return self.group_name.split(RepoGroup.url_sep())[-1]
2599 return self.group_name.split(RepoGroup.url_sep())[-1]
2600
2600
2601 @property
2601 @property
2602 def full_path(self):
2602 def full_path(self):
2603 return self.group_name
2603 return self.group_name
2604
2604
2605 @property
2605 @property
2606 def full_path_splitted(self):
2606 def full_path_splitted(self):
2607 return self.group_name.split(RepoGroup.url_sep())
2607 return self.group_name.split(RepoGroup.url_sep())
2608
2608
2609 @property
2609 @property
2610 def repositories(self):
2610 def repositories(self):
2611 return Repository.query()\
2611 return Repository.query()\
2612 .filter(Repository.group == self)\
2612 .filter(Repository.group == self)\
2613 .order_by(Repository.repo_name)
2613 .order_by(Repository.repo_name)
2614
2614
2615 @property
2615 @property
2616 def repositories_recursive_count(self):
2616 def repositories_recursive_count(self):
2617 cnt = self.repositories.count()
2617 cnt = self.repositories.count()
2618
2618
2619 def children_count(group):
2619 def children_count(group):
2620 cnt = 0
2620 cnt = 0
2621 for child in group.children:
2621 for child in group.children:
2622 cnt += child.repositories.count()
2622 cnt += child.repositories.count()
2623 cnt += children_count(child)
2623 cnt += children_count(child)
2624 return cnt
2624 return cnt
2625
2625
2626 return cnt + children_count(self)
2626 return cnt + children_count(self)
2627
2627
2628 def _recursive_objects(self, include_repos=True):
2628 def _recursive_objects(self, include_repos=True):
2629 all_ = []
2629 all_ = []
2630
2630
2631 def _get_members(root_gr):
2631 def _get_members(root_gr):
2632 if include_repos:
2632 if include_repos:
2633 for r in root_gr.repositories:
2633 for r in root_gr.repositories:
2634 all_.append(r)
2634 all_.append(r)
2635 childs = root_gr.children.all()
2635 childs = root_gr.children.all()
2636 if childs:
2636 if childs:
2637 for gr in childs:
2637 for gr in childs:
2638 all_.append(gr)
2638 all_.append(gr)
2639 _get_members(gr)
2639 _get_members(gr)
2640
2640
2641 _get_members(self)
2641 _get_members(self)
2642 return [self] + all_
2642 return [self] + all_
2643
2643
2644 def recursive_groups_and_repos(self):
2644 def recursive_groups_and_repos(self):
2645 """
2645 """
2646 Recursive return all groups, with repositories in those groups
2646 Recursive return all groups, with repositories in those groups
2647 """
2647 """
2648 return self._recursive_objects()
2648 return self._recursive_objects()
2649
2649
2650 def recursive_groups(self):
2650 def recursive_groups(self):
2651 """
2651 """
2652 Returns all children groups for this group including children of children
2652 Returns all children groups for this group including children of children
2653 """
2653 """
2654 return self._recursive_objects(include_repos=False)
2654 return self._recursive_objects(include_repos=False)
2655
2655
2656 def get_new_name(self, group_name):
2656 def get_new_name(self, group_name):
2657 """
2657 """
2658 returns new full group name based on parent and new name
2658 returns new full group name based on parent and new name
2659
2659
2660 :param group_name:
2660 :param group_name:
2661 """
2661 """
2662 path_prefix = (self.parent_group.full_path_splitted if
2662 path_prefix = (self.parent_group.full_path_splitted if
2663 self.parent_group else [])
2663 self.parent_group else [])
2664 return RepoGroup.url_sep().join(path_prefix + [group_name])
2664 return RepoGroup.url_sep().join(path_prefix + [group_name])
2665
2665
2666 def permissions(self, with_admins=True, with_owner=True,
2666 def permissions(self, with_admins=True, with_owner=True,
2667 expand_from_user_groups=False):
2667 expand_from_user_groups=False):
2668 """
2668 """
2669 Permissions for repository groups
2669 Permissions for repository groups
2670 """
2670 """
2671 _admin_perm = 'group.admin'
2671 _admin_perm = 'group.admin'
2672
2672
2673 owner_row = []
2673 owner_row = []
2674 if with_owner:
2674 if with_owner:
2675 usr = AttributeDict(self.user.get_dict())
2675 usr = AttributeDict(self.user.get_dict())
2676 usr.owner_row = True
2676 usr.owner_row = True
2677 usr.permission = _admin_perm
2677 usr.permission = _admin_perm
2678 owner_row.append(usr)
2678 owner_row.append(usr)
2679
2679
2680 super_admin_ids = []
2680 super_admin_ids = []
2681 super_admin_rows = []
2681 super_admin_rows = []
2682 if with_admins:
2682 if with_admins:
2683 for usr in User.get_all_super_admins():
2683 for usr in User.get_all_super_admins():
2684 super_admin_ids.append(usr.user_id)
2684 super_admin_ids.append(usr.user_id)
2685 # if this admin is also owner, don't double the record
2685 # if this admin is also owner, don't double the record
2686 if usr.user_id == owner_row[0].user_id:
2686 if usr.user_id == owner_row[0].user_id:
2687 owner_row[0].admin_row = True
2687 owner_row[0].admin_row = True
2688 else:
2688 else:
2689 usr = AttributeDict(usr.get_dict())
2689 usr = AttributeDict(usr.get_dict())
2690 usr.admin_row = True
2690 usr.admin_row = True
2691 usr.permission = _admin_perm
2691 usr.permission = _admin_perm
2692 super_admin_rows.append(usr)
2692 super_admin_rows.append(usr)
2693
2693
2694 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2694 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2695 q = q.options(joinedload(UserRepoGroupToPerm.group),
2695 q = q.options(joinedload(UserRepoGroupToPerm.group),
2696 joinedload(UserRepoGroupToPerm.user),
2696 joinedload(UserRepoGroupToPerm.user),
2697 joinedload(UserRepoGroupToPerm.permission),)
2697 joinedload(UserRepoGroupToPerm.permission),)
2698
2698
2699 # get owners and admins and permissions. We do a trick of re-writing
2699 # get owners and admins and permissions. We do a trick of re-writing
2700 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2700 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2701 # has a global reference and changing one object propagates to all
2701 # has a global reference and changing one object propagates to all
2702 # others. This means if admin is also an owner admin_row that change
2702 # others. This means if admin is also an owner admin_row that change
2703 # would propagate to both objects
2703 # would propagate to both objects
2704 perm_rows = []
2704 perm_rows = []
2705 for _usr in q.all():
2705 for _usr in q.all():
2706 usr = AttributeDict(_usr.user.get_dict())
2706 usr = AttributeDict(_usr.user.get_dict())
2707 # if this user is also owner/admin, mark as duplicate record
2707 # if this user is also owner/admin, mark as duplicate record
2708 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2708 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2709 usr.duplicate_perm = True
2709 usr.duplicate_perm = True
2710 usr.permission = _usr.permission.permission_name
2710 usr.permission = _usr.permission.permission_name
2711 perm_rows.append(usr)
2711 perm_rows.append(usr)
2712
2712
2713 # filter the perm rows by 'default' first and then sort them by
2713 # filter the perm rows by 'default' first and then sort them by
2714 # admin,write,read,none permissions sorted again alphabetically in
2714 # admin,write,read,none permissions sorted again alphabetically in
2715 # each group
2715 # each group
2716 perm_rows = sorted(perm_rows, key=display_user_sort)
2716 perm_rows = sorted(perm_rows, key=display_user_sort)
2717
2717
2718 user_groups_rows = []
2718 user_groups_rows = []
2719 if expand_from_user_groups:
2719 if expand_from_user_groups:
2720 for ug in self.permission_user_groups(with_members=True):
2720 for ug in self.permission_user_groups(with_members=True):
2721 for user_data in ug.members:
2721 for user_data in ug.members:
2722 user_groups_rows.append(user_data)
2722 user_groups_rows.append(user_data)
2723
2723
2724 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2724 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2725
2725
2726 def permission_user_groups(self, with_members=False):
2726 def permission_user_groups(self, with_members=False):
2727 q = UserGroupRepoGroupToPerm.query()\
2727 q = UserGroupRepoGroupToPerm.query()\
2728 .filter(UserGroupRepoGroupToPerm.group == self)
2728 .filter(UserGroupRepoGroupToPerm.group == self)
2729 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2729 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2730 joinedload(UserGroupRepoGroupToPerm.users_group),
2730 joinedload(UserGroupRepoGroupToPerm.users_group),
2731 joinedload(UserGroupRepoGroupToPerm.permission),)
2731 joinedload(UserGroupRepoGroupToPerm.permission),)
2732
2732
2733 perm_rows = []
2733 perm_rows = []
2734 for _user_group in q.all():
2734 for _user_group in q.all():
2735 entry = AttributeDict(_user_group.users_group.get_dict())
2735 entry = AttributeDict(_user_group.users_group.get_dict())
2736 entry.permission = _user_group.permission.permission_name
2736 entry.permission = _user_group.permission.permission_name
2737 if with_members:
2737 if with_members:
2738 entry.members = [x.user.get_dict()
2738 entry.members = [x.user.get_dict()
2739 for x in _user_group.users_group.members]
2739 for x in _user_group.users_group.members]
2740 perm_rows.append(entry)
2740 perm_rows.append(entry)
2741
2741
2742 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2742 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2743 return perm_rows
2743 return perm_rows
2744
2744
2745 def get_api_data(self):
2745 def get_api_data(self):
2746 """
2746 """
2747 Common function for generating api data
2747 Common function for generating api data
2748
2748
2749 """
2749 """
2750 group = self
2750 group = self
2751 data = {
2751 data = {
2752 'group_id': group.group_id,
2752 'group_id': group.group_id,
2753 'group_name': group.group_name,
2753 'group_name': group.group_name,
2754 'group_description': group.description_safe,
2754 'group_description': group.description_safe,
2755 'parent_group': group.parent_group.group_name if group.parent_group else None,
2755 'parent_group': group.parent_group.group_name if group.parent_group else None,
2756 'repositories': [x.repo_name for x in group.repositories],
2756 'repositories': [x.repo_name for x in group.repositories],
2757 'owner': group.user.username,
2757 'owner': group.user.username,
2758 }
2758 }
2759 return data
2759 return data
2760
2760
2761
2761
2762 class Permission(Base, BaseModel):
2762 class Permission(Base, BaseModel):
2763 __tablename__ = 'permissions'
2763 __tablename__ = 'permissions'
2764 __table_args__ = (
2764 __table_args__ = (
2765 Index('p_perm_name_idx', 'permission_name'),
2765 Index('p_perm_name_idx', 'permission_name'),
2766 base_table_args,
2766 base_table_args,
2767 )
2767 )
2768
2768
2769 PERMS = [
2769 PERMS = [
2770 ('hg.admin', _('RhodeCode Super Administrator')),
2770 ('hg.admin', _('RhodeCode Super Administrator')),
2771
2771
2772 ('repository.none', _('Repository no access')),
2772 ('repository.none', _('Repository no access')),
2773 ('repository.read', _('Repository read access')),
2773 ('repository.read', _('Repository read access')),
2774 ('repository.write', _('Repository write access')),
2774 ('repository.write', _('Repository write access')),
2775 ('repository.admin', _('Repository admin access')),
2775 ('repository.admin', _('Repository admin access')),
2776
2776
2777 ('group.none', _('Repository group no access')),
2777 ('group.none', _('Repository group no access')),
2778 ('group.read', _('Repository group read access')),
2778 ('group.read', _('Repository group read access')),
2779 ('group.write', _('Repository group write access')),
2779 ('group.write', _('Repository group write access')),
2780 ('group.admin', _('Repository group admin access')),
2780 ('group.admin', _('Repository group admin access')),
2781
2781
2782 ('usergroup.none', _('User group no access')),
2782 ('usergroup.none', _('User group no access')),
2783 ('usergroup.read', _('User group read access')),
2783 ('usergroup.read', _('User group read access')),
2784 ('usergroup.write', _('User group write access')),
2784 ('usergroup.write', _('User group write access')),
2785 ('usergroup.admin', _('User group admin access')),
2785 ('usergroup.admin', _('User group admin access')),
2786
2786
2787 ('branch.none', _('Branch no permissions')),
2787 ('branch.none', _('Branch no permissions')),
2788 ('branch.merge', _('Branch access by web merge')),
2788 ('branch.merge', _('Branch access by web merge')),
2789 ('branch.push', _('Branch access by push')),
2789 ('branch.push', _('Branch access by push')),
2790 ('branch.push_force', _('Branch access by push with force')),
2790 ('branch.push_force', _('Branch access by push with force')),
2791
2791
2792 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2792 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2793 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2793 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2794
2794
2795 ('hg.usergroup.create.false', _('User Group creation disabled')),
2795 ('hg.usergroup.create.false', _('User Group creation disabled')),
2796 ('hg.usergroup.create.true', _('User Group creation enabled')),
2796 ('hg.usergroup.create.true', _('User Group creation enabled')),
2797
2797
2798 ('hg.create.none', _('Repository creation disabled')),
2798 ('hg.create.none', _('Repository creation disabled')),
2799 ('hg.create.repository', _('Repository creation enabled')),
2799 ('hg.create.repository', _('Repository creation enabled')),
2800 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2800 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2801 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2801 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2802
2802
2803 ('hg.fork.none', _('Repository forking disabled')),
2803 ('hg.fork.none', _('Repository forking disabled')),
2804 ('hg.fork.repository', _('Repository forking enabled')),
2804 ('hg.fork.repository', _('Repository forking enabled')),
2805
2805
2806 ('hg.register.none', _('Registration disabled')),
2806 ('hg.register.none', _('Registration disabled')),
2807 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2807 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2808 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2808 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2809
2809
2810 ('hg.password_reset.enabled', _('Password reset enabled')),
2810 ('hg.password_reset.enabled', _('Password reset enabled')),
2811 ('hg.password_reset.hidden', _('Password reset hidden')),
2811 ('hg.password_reset.hidden', _('Password reset hidden')),
2812 ('hg.password_reset.disabled', _('Password reset disabled')),
2812 ('hg.password_reset.disabled', _('Password reset disabled')),
2813
2813
2814 ('hg.extern_activate.manual', _('Manual activation of external account')),
2814 ('hg.extern_activate.manual', _('Manual activation of external account')),
2815 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2815 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2816
2816
2817 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2817 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2818 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2818 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2819 ]
2819 ]
2820
2820
2821 # definition of system default permissions for DEFAULT user, created on
2821 # definition of system default permissions for DEFAULT user, created on
2822 # system setup
2822 # system setup
2823 DEFAULT_USER_PERMISSIONS = [
2823 DEFAULT_USER_PERMISSIONS = [
2824 # object perms
2824 # object perms
2825 'repository.read',
2825 'repository.read',
2826 'group.read',
2826 'group.read',
2827 'usergroup.read',
2827 'usergroup.read',
2828 # branch, for backward compat we need same value as before so forced pushed
2828 # branch, for backward compat we need same value as before so forced pushed
2829 'branch.push_force',
2829 'branch.push_force',
2830 # global
2830 # global
2831 'hg.create.repository',
2831 'hg.create.repository',
2832 'hg.repogroup.create.false',
2832 'hg.repogroup.create.false',
2833 'hg.usergroup.create.false',
2833 'hg.usergroup.create.false',
2834 'hg.create.write_on_repogroup.true',
2834 'hg.create.write_on_repogroup.true',
2835 'hg.fork.repository',
2835 'hg.fork.repository',
2836 'hg.register.manual_activate',
2836 'hg.register.manual_activate',
2837 'hg.password_reset.enabled',
2837 'hg.password_reset.enabled',
2838 'hg.extern_activate.auto',
2838 'hg.extern_activate.auto',
2839 'hg.inherit_default_perms.true',
2839 'hg.inherit_default_perms.true',
2840 ]
2840 ]
2841
2841
2842 # defines which permissions are more important higher the more important
2842 # defines which permissions are more important higher the more important
2843 # Weight defines which permissions are more important.
2843 # Weight defines which permissions are more important.
2844 # The higher number the more important.
2844 # The higher number the more important.
2845 PERM_WEIGHTS = {
2845 PERM_WEIGHTS = {
2846 'repository.none': 0,
2846 'repository.none': 0,
2847 'repository.read': 1,
2847 'repository.read': 1,
2848 'repository.write': 3,
2848 'repository.write': 3,
2849 'repository.admin': 4,
2849 'repository.admin': 4,
2850
2850
2851 'group.none': 0,
2851 'group.none': 0,
2852 'group.read': 1,
2852 'group.read': 1,
2853 'group.write': 3,
2853 'group.write': 3,
2854 'group.admin': 4,
2854 'group.admin': 4,
2855
2855
2856 'usergroup.none': 0,
2856 'usergroup.none': 0,
2857 'usergroup.read': 1,
2857 'usergroup.read': 1,
2858 'usergroup.write': 3,
2858 'usergroup.write': 3,
2859 'usergroup.admin': 4,
2859 'usergroup.admin': 4,
2860
2860
2861 'branch.none': 0,
2861 'branch.none': 0,
2862 'branch.merge': 1,
2862 'branch.merge': 1,
2863 'branch.push': 3,
2863 'branch.push': 3,
2864 'branch.push_force': 4,
2864 'branch.push_force': 4,
2865
2865
2866 'hg.repogroup.create.false': 0,
2866 'hg.repogroup.create.false': 0,
2867 'hg.repogroup.create.true': 1,
2867 'hg.repogroup.create.true': 1,
2868
2868
2869 'hg.usergroup.create.false': 0,
2869 'hg.usergroup.create.false': 0,
2870 'hg.usergroup.create.true': 1,
2870 'hg.usergroup.create.true': 1,
2871
2871
2872 'hg.fork.none': 0,
2872 'hg.fork.none': 0,
2873 'hg.fork.repository': 1,
2873 'hg.fork.repository': 1,
2874 'hg.create.none': 0,
2874 'hg.create.none': 0,
2875 'hg.create.repository': 1
2875 'hg.create.repository': 1
2876 }
2876 }
2877
2877
2878 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2878 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2879 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2879 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2880 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2880 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2881
2881
2882 def __unicode__(self):
2882 def __unicode__(self):
2883 return u"<%s('%s:%s')>" % (
2883 return u"<%s('%s:%s')>" % (
2884 self.__class__.__name__, self.permission_id, self.permission_name
2884 self.__class__.__name__, self.permission_id, self.permission_name
2885 )
2885 )
2886
2886
2887 @classmethod
2887 @classmethod
2888 def get_by_key(cls, key):
2888 def get_by_key(cls, key):
2889 return cls.query().filter(cls.permission_name == key).scalar()
2889 return cls.query().filter(cls.permission_name == key).scalar()
2890
2890
2891 @classmethod
2891 @classmethod
2892 def get_default_repo_perms(cls, user_id, repo_id=None):
2892 def get_default_repo_perms(cls, user_id, repo_id=None):
2893 q = Session().query(UserRepoToPerm, Repository, Permission)\
2893 q = Session().query(UserRepoToPerm, Repository, Permission)\
2894 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2894 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2895 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2895 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2896 .filter(UserRepoToPerm.user_id == user_id)
2896 .filter(UserRepoToPerm.user_id == user_id)
2897 if repo_id:
2897 if repo_id:
2898 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2898 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2899 return q.all()
2899 return q.all()
2900
2900
2901 @classmethod
2901 @classmethod
2902 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2902 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
2903 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2903 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
2904 .join(
2904 .join(
2905 Permission,
2905 Permission,
2906 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2906 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
2907 .join(
2907 .join(
2908 UserRepoToPerm,
2908 UserRepoToPerm,
2909 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2909 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
2910 .filter(UserRepoToPerm.user_id == user_id)
2910 .filter(UserRepoToPerm.user_id == user_id)
2911
2911
2912 if repo_id:
2912 if repo_id:
2913 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2913 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
2914 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2914 return q.order_by(UserToRepoBranchPermission.rule_order).all()
2915
2915
2916 @classmethod
2916 @classmethod
2917 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2917 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2918 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2918 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2919 .join(
2919 .join(
2920 Permission,
2920 Permission,
2921 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2921 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2922 .join(
2922 .join(
2923 Repository,
2923 Repository,
2924 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2924 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2925 .join(
2925 .join(
2926 UserGroup,
2926 UserGroup,
2927 UserGroupRepoToPerm.users_group_id ==
2927 UserGroupRepoToPerm.users_group_id ==
2928 UserGroup.users_group_id)\
2928 UserGroup.users_group_id)\
2929 .join(
2929 .join(
2930 UserGroupMember,
2930 UserGroupMember,
2931 UserGroupRepoToPerm.users_group_id ==
2931 UserGroupRepoToPerm.users_group_id ==
2932 UserGroupMember.users_group_id)\
2932 UserGroupMember.users_group_id)\
2933 .filter(
2933 .filter(
2934 UserGroupMember.user_id == user_id,
2934 UserGroupMember.user_id == user_id,
2935 UserGroup.users_group_active == true())
2935 UserGroup.users_group_active == true())
2936 if repo_id:
2936 if repo_id:
2937 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2937 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2938 return q.all()
2938 return q.all()
2939
2939
2940 @classmethod
2940 @classmethod
2941 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2941 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
2942 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2942 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
2943 .join(
2943 .join(
2944 Permission,
2944 Permission,
2945 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2945 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
2946 .join(
2946 .join(
2947 UserGroupRepoToPerm,
2947 UserGroupRepoToPerm,
2948 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2948 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
2949 .join(
2949 .join(
2950 UserGroup,
2950 UserGroup,
2951 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2951 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
2952 .join(
2952 .join(
2953 UserGroupMember,
2953 UserGroupMember,
2954 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2954 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
2955 .filter(
2955 .filter(
2956 UserGroupMember.user_id == user_id,
2956 UserGroupMember.user_id == user_id,
2957 UserGroup.users_group_active == true())
2957 UserGroup.users_group_active == true())
2958
2958
2959 if repo_id:
2959 if repo_id:
2960 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2960 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
2961 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2961 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
2962
2962
2963 @classmethod
2963 @classmethod
2964 def get_default_group_perms(cls, user_id, repo_group_id=None):
2964 def get_default_group_perms(cls, user_id, repo_group_id=None):
2965 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2965 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2966 .join(
2966 .join(
2967 Permission,
2967 Permission,
2968 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2968 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
2969 .join(
2969 .join(
2970 RepoGroup,
2970 RepoGroup,
2971 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2971 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
2972 .filter(UserRepoGroupToPerm.user_id == user_id)
2972 .filter(UserRepoGroupToPerm.user_id == user_id)
2973 if repo_group_id:
2973 if repo_group_id:
2974 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2974 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2975 return q.all()
2975 return q.all()
2976
2976
2977 @classmethod
2977 @classmethod
2978 def get_default_group_perms_from_user_group(
2978 def get_default_group_perms_from_user_group(
2979 cls, user_id, repo_group_id=None):
2979 cls, user_id, repo_group_id=None):
2980 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2980 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2981 .join(
2981 .join(
2982 Permission,
2982 Permission,
2983 UserGroupRepoGroupToPerm.permission_id ==
2983 UserGroupRepoGroupToPerm.permission_id ==
2984 Permission.permission_id)\
2984 Permission.permission_id)\
2985 .join(
2985 .join(
2986 RepoGroup,
2986 RepoGroup,
2987 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2987 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2988 .join(
2988 .join(
2989 UserGroup,
2989 UserGroup,
2990 UserGroupRepoGroupToPerm.users_group_id ==
2990 UserGroupRepoGroupToPerm.users_group_id ==
2991 UserGroup.users_group_id)\
2991 UserGroup.users_group_id)\
2992 .join(
2992 .join(
2993 UserGroupMember,
2993 UserGroupMember,
2994 UserGroupRepoGroupToPerm.users_group_id ==
2994 UserGroupRepoGroupToPerm.users_group_id ==
2995 UserGroupMember.users_group_id)\
2995 UserGroupMember.users_group_id)\
2996 .filter(
2996 .filter(
2997 UserGroupMember.user_id == user_id,
2997 UserGroupMember.user_id == user_id,
2998 UserGroup.users_group_active == true())
2998 UserGroup.users_group_active == true())
2999 if repo_group_id:
2999 if repo_group_id:
3000 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3000 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3001 return q.all()
3001 return q.all()
3002
3002
3003 @classmethod
3003 @classmethod
3004 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3004 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3005 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3005 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3006 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3006 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3007 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3007 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3008 .filter(UserUserGroupToPerm.user_id == user_id)
3008 .filter(UserUserGroupToPerm.user_id == user_id)
3009 if user_group_id:
3009 if user_group_id:
3010 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3010 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3011 return q.all()
3011 return q.all()
3012
3012
3013 @classmethod
3013 @classmethod
3014 def get_default_user_group_perms_from_user_group(
3014 def get_default_user_group_perms_from_user_group(
3015 cls, user_id, user_group_id=None):
3015 cls, user_id, user_group_id=None):
3016 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3016 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3017 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3017 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3018 .join(
3018 .join(
3019 Permission,
3019 Permission,
3020 UserGroupUserGroupToPerm.permission_id ==
3020 UserGroupUserGroupToPerm.permission_id ==
3021 Permission.permission_id)\
3021 Permission.permission_id)\
3022 .join(
3022 .join(
3023 TargetUserGroup,
3023 TargetUserGroup,
3024 UserGroupUserGroupToPerm.target_user_group_id ==
3024 UserGroupUserGroupToPerm.target_user_group_id ==
3025 TargetUserGroup.users_group_id)\
3025 TargetUserGroup.users_group_id)\
3026 .join(
3026 .join(
3027 UserGroup,
3027 UserGroup,
3028 UserGroupUserGroupToPerm.user_group_id ==
3028 UserGroupUserGroupToPerm.user_group_id ==
3029 UserGroup.users_group_id)\
3029 UserGroup.users_group_id)\
3030 .join(
3030 .join(
3031 UserGroupMember,
3031 UserGroupMember,
3032 UserGroupUserGroupToPerm.user_group_id ==
3032 UserGroupUserGroupToPerm.user_group_id ==
3033 UserGroupMember.users_group_id)\
3033 UserGroupMember.users_group_id)\
3034 .filter(
3034 .filter(
3035 UserGroupMember.user_id == user_id,
3035 UserGroupMember.user_id == user_id,
3036 UserGroup.users_group_active == true())
3036 UserGroup.users_group_active == true())
3037 if user_group_id:
3037 if user_group_id:
3038 q = q.filter(
3038 q = q.filter(
3039 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3039 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3040
3040
3041 return q.all()
3041 return q.all()
3042
3042
3043
3043
3044 class UserRepoToPerm(Base, BaseModel):
3044 class UserRepoToPerm(Base, BaseModel):
3045 __tablename__ = 'repo_to_perm'
3045 __tablename__ = 'repo_to_perm'
3046 __table_args__ = (
3046 __table_args__ = (
3047 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3047 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3048 base_table_args
3048 base_table_args
3049 )
3049 )
3050
3050
3051 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3051 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3052 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3052 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3053 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3053 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3054 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3054 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3055
3055
3056 user = relationship('User')
3056 user = relationship('User')
3057 repository = relationship('Repository')
3057 repository = relationship('Repository')
3058 permission = relationship('Permission')
3058 permission = relationship('Permission')
3059
3059
3060 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3060 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3061
3061
3062 @classmethod
3062 @classmethod
3063 def create(cls, user, repository, permission):
3063 def create(cls, user, repository, permission):
3064 n = cls()
3064 n = cls()
3065 n.user = user
3065 n.user = user
3066 n.repository = repository
3066 n.repository = repository
3067 n.permission = permission
3067 n.permission = permission
3068 Session().add(n)
3068 Session().add(n)
3069 return n
3069 return n
3070
3070
3071 def __unicode__(self):
3071 def __unicode__(self):
3072 return u'<%s => %s >' % (self.user, self.repository)
3072 return u'<%s => %s >' % (self.user, self.repository)
3073
3073
3074
3074
3075 class UserUserGroupToPerm(Base, BaseModel):
3075 class UserUserGroupToPerm(Base, BaseModel):
3076 __tablename__ = 'user_user_group_to_perm'
3076 __tablename__ = 'user_user_group_to_perm'
3077 __table_args__ = (
3077 __table_args__ = (
3078 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3078 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3079 base_table_args
3079 base_table_args
3080 )
3080 )
3081
3081
3082 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3082 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3083 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3083 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3084 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3084 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3085 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3085 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3086
3086
3087 user = relationship('User')
3087 user = relationship('User')
3088 user_group = relationship('UserGroup')
3088 user_group = relationship('UserGroup')
3089 permission = relationship('Permission')
3089 permission = relationship('Permission')
3090
3090
3091 @classmethod
3091 @classmethod
3092 def create(cls, user, user_group, permission):
3092 def create(cls, user, user_group, permission):
3093 n = cls()
3093 n = cls()
3094 n.user = user
3094 n.user = user
3095 n.user_group = user_group
3095 n.user_group = user_group
3096 n.permission = permission
3096 n.permission = permission
3097 Session().add(n)
3097 Session().add(n)
3098 return n
3098 return n
3099
3099
3100 def __unicode__(self):
3100 def __unicode__(self):
3101 return u'<%s => %s >' % (self.user, self.user_group)
3101 return u'<%s => %s >' % (self.user, self.user_group)
3102
3102
3103
3103
3104 class UserToPerm(Base, BaseModel):
3104 class UserToPerm(Base, BaseModel):
3105 __tablename__ = 'user_to_perm'
3105 __tablename__ = 'user_to_perm'
3106 __table_args__ = (
3106 __table_args__ = (
3107 UniqueConstraint('user_id', 'permission_id'),
3107 UniqueConstraint('user_id', 'permission_id'),
3108 base_table_args
3108 base_table_args
3109 )
3109 )
3110
3110
3111 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3111 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3112 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3112 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3113 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3113 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3114
3114
3115 user = relationship('User')
3115 user = relationship('User')
3116 permission = relationship('Permission', lazy='joined')
3116 permission = relationship('Permission', lazy='joined')
3117
3117
3118 def __unicode__(self):
3118 def __unicode__(self):
3119 return u'<%s => %s >' % (self.user, self.permission)
3119 return u'<%s => %s >' % (self.user, self.permission)
3120
3120
3121
3121
3122 class UserGroupRepoToPerm(Base, BaseModel):
3122 class UserGroupRepoToPerm(Base, BaseModel):
3123 __tablename__ = 'users_group_repo_to_perm'
3123 __tablename__ = 'users_group_repo_to_perm'
3124 __table_args__ = (
3124 __table_args__ = (
3125 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3125 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3126 base_table_args
3126 base_table_args
3127 )
3127 )
3128
3128
3129 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3129 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3130 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3130 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3131 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3131 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3132 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3132 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3133
3133
3134 users_group = relationship('UserGroup')
3134 users_group = relationship('UserGroup')
3135 permission = relationship('Permission')
3135 permission = relationship('Permission')
3136 repository = relationship('Repository')
3136 repository = relationship('Repository')
3137 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3137 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3138
3138
3139 @classmethod
3139 @classmethod
3140 def create(cls, users_group, repository, permission):
3140 def create(cls, users_group, repository, permission):
3141 n = cls()
3141 n = cls()
3142 n.users_group = users_group
3142 n.users_group = users_group
3143 n.repository = repository
3143 n.repository = repository
3144 n.permission = permission
3144 n.permission = permission
3145 Session().add(n)
3145 Session().add(n)
3146 return n
3146 return n
3147
3147
3148 def __unicode__(self):
3148 def __unicode__(self):
3149 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3149 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3150
3150
3151
3151
3152 class UserGroupUserGroupToPerm(Base, BaseModel):
3152 class UserGroupUserGroupToPerm(Base, BaseModel):
3153 __tablename__ = 'user_group_user_group_to_perm'
3153 __tablename__ = 'user_group_user_group_to_perm'
3154 __table_args__ = (
3154 __table_args__ = (
3155 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3155 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3156 CheckConstraint('target_user_group_id != user_group_id'),
3156 CheckConstraint('target_user_group_id != user_group_id'),
3157 base_table_args
3157 base_table_args
3158 )
3158 )
3159
3159
3160 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)
3160 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3161 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3161 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3162 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3162 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3163 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3163 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3164
3164
3165 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3165 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3166 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3166 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3167 permission = relationship('Permission')
3167 permission = relationship('Permission')
3168
3168
3169 @classmethod
3169 @classmethod
3170 def create(cls, target_user_group, user_group, permission):
3170 def create(cls, target_user_group, user_group, permission):
3171 n = cls()
3171 n = cls()
3172 n.target_user_group = target_user_group
3172 n.target_user_group = target_user_group
3173 n.user_group = user_group
3173 n.user_group = user_group
3174 n.permission = permission
3174 n.permission = permission
3175 Session().add(n)
3175 Session().add(n)
3176 return n
3176 return n
3177
3177
3178 def __unicode__(self):
3178 def __unicode__(self):
3179 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3179 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3180
3180
3181
3181
3182 class UserGroupToPerm(Base, BaseModel):
3182 class UserGroupToPerm(Base, BaseModel):
3183 __tablename__ = 'users_group_to_perm'
3183 __tablename__ = 'users_group_to_perm'
3184 __table_args__ = (
3184 __table_args__ = (
3185 UniqueConstraint('users_group_id', 'permission_id',),
3185 UniqueConstraint('users_group_id', 'permission_id',),
3186 base_table_args
3186 base_table_args
3187 )
3187 )
3188
3188
3189 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3189 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3190 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3190 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3191 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3191 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3192
3192
3193 users_group = relationship('UserGroup')
3193 users_group = relationship('UserGroup')
3194 permission = relationship('Permission')
3194 permission = relationship('Permission')
3195
3195
3196
3196
3197 class UserRepoGroupToPerm(Base, BaseModel):
3197 class UserRepoGroupToPerm(Base, BaseModel):
3198 __tablename__ = 'user_repo_group_to_perm'
3198 __tablename__ = 'user_repo_group_to_perm'
3199 __table_args__ = (
3199 __table_args__ = (
3200 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3200 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3201 base_table_args
3201 base_table_args
3202 )
3202 )
3203
3203
3204 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3204 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3205 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3205 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3206 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3206 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3207 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3207 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3208
3208
3209 user = relationship('User')
3209 user = relationship('User')
3210 group = relationship('RepoGroup')
3210 group = relationship('RepoGroup')
3211 permission = relationship('Permission')
3211 permission = relationship('Permission')
3212
3212
3213 @classmethod
3213 @classmethod
3214 def create(cls, user, repository_group, permission):
3214 def create(cls, user, repository_group, permission):
3215 n = cls()
3215 n = cls()
3216 n.user = user
3216 n.user = user
3217 n.group = repository_group
3217 n.group = repository_group
3218 n.permission = permission
3218 n.permission = permission
3219 Session().add(n)
3219 Session().add(n)
3220 return n
3220 return n
3221
3221
3222
3222
3223 class UserGroupRepoGroupToPerm(Base, BaseModel):
3223 class UserGroupRepoGroupToPerm(Base, BaseModel):
3224 __tablename__ = 'users_group_repo_group_to_perm'
3224 __tablename__ = 'users_group_repo_group_to_perm'
3225 __table_args__ = (
3225 __table_args__ = (
3226 UniqueConstraint('users_group_id', 'group_id'),
3226 UniqueConstraint('users_group_id', 'group_id'),
3227 base_table_args
3227 base_table_args
3228 )
3228 )
3229
3229
3230 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)
3230 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3231 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3231 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3232 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3232 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3233 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3233 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3234
3234
3235 users_group = relationship('UserGroup')
3235 users_group = relationship('UserGroup')
3236 permission = relationship('Permission')
3236 permission = relationship('Permission')
3237 group = relationship('RepoGroup')
3237 group = relationship('RepoGroup')
3238
3238
3239 @classmethod
3239 @classmethod
3240 def create(cls, user_group, repository_group, permission):
3240 def create(cls, user_group, repository_group, permission):
3241 n = cls()
3241 n = cls()
3242 n.users_group = user_group
3242 n.users_group = user_group
3243 n.group = repository_group
3243 n.group = repository_group
3244 n.permission = permission
3244 n.permission = permission
3245 Session().add(n)
3245 Session().add(n)
3246 return n
3246 return n
3247
3247
3248 def __unicode__(self):
3248 def __unicode__(self):
3249 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3249 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3250
3250
3251
3251
3252 class Statistics(Base, BaseModel):
3252 class Statistics(Base, BaseModel):
3253 __tablename__ = 'statistics'
3253 __tablename__ = 'statistics'
3254 __table_args__ = (
3254 __table_args__ = (
3255 base_table_args
3255 base_table_args
3256 )
3256 )
3257
3257
3258 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3258 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3259 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3259 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3260 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3260 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3261 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3261 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3262 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3262 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3263 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3263 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3264
3264
3265 repository = relationship('Repository', single_parent=True)
3265 repository = relationship('Repository', single_parent=True)
3266
3266
3267
3267
3268 class UserFollowing(Base, BaseModel):
3268 class UserFollowing(Base, BaseModel):
3269 __tablename__ = 'user_followings'
3269 __tablename__ = 'user_followings'
3270 __table_args__ = (
3270 __table_args__ = (
3271 UniqueConstraint('user_id', 'follows_repository_id'),
3271 UniqueConstraint('user_id', 'follows_repository_id'),
3272 UniqueConstraint('user_id', 'follows_user_id'),
3272 UniqueConstraint('user_id', 'follows_user_id'),
3273 base_table_args
3273 base_table_args
3274 )
3274 )
3275
3275
3276 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3276 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3277 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3277 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3278 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3278 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3279 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3279 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3280 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3280 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3281
3281
3282 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3282 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3283
3283
3284 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3284 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3285 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3285 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3286
3286
3287 @classmethod
3287 @classmethod
3288 def get_repo_followers(cls, repo_id):
3288 def get_repo_followers(cls, repo_id):
3289 return cls.query().filter(cls.follows_repo_id == repo_id)
3289 return cls.query().filter(cls.follows_repo_id == repo_id)
3290
3290
3291
3291
3292 class CacheKey(Base, BaseModel):
3292 class CacheKey(Base, BaseModel):
3293 __tablename__ = 'cache_invalidation'
3293 __tablename__ = 'cache_invalidation'
3294 __table_args__ = (
3294 __table_args__ = (
3295 UniqueConstraint('cache_key'),
3295 UniqueConstraint('cache_key'),
3296 Index('key_idx', 'cache_key'),
3296 Index('key_idx', 'cache_key'),
3297 base_table_args,
3297 base_table_args,
3298 )
3298 )
3299
3299
3300 CACHE_TYPE_FEED = 'FEED'
3300 CACHE_TYPE_FEED = 'FEED'
3301 CACHE_TYPE_README = 'README'
3301 CACHE_TYPE_README = 'README'
3302 # namespaces used to register process/thread aware caches
3302 # namespaces used to register process/thread aware caches
3303 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3303 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3304 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3304 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3305
3305
3306 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3306 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3307 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3307 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3308 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3308 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3309 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3309 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3310
3310
3311 def __init__(self, cache_key, cache_args=''):
3311 def __init__(self, cache_key, cache_args=''):
3312 self.cache_key = cache_key
3312 self.cache_key = cache_key
3313 self.cache_args = cache_args
3313 self.cache_args = cache_args
3314 self.cache_active = False
3314 self.cache_active = False
3315
3315
3316 def __unicode__(self):
3316 def __unicode__(self):
3317 return u"<%s('%s:%s[%s]')>" % (
3317 return u"<%s('%s:%s[%s]')>" % (
3318 self.__class__.__name__,
3318 self.__class__.__name__,
3319 self.cache_id, self.cache_key, self.cache_active)
3319 self.cache_id, self.cache_key, self.cache_active)
3320
3320
3321 def _cache_key_partition(self):
3321 def _cache_key_partition(self):
3322 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3322 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3323 return prefix, repo_name, suffix
3323 return prefix, repo_name, suffix
3324
3324
3325 def get_prefix(self):
3325 def get_prefix(self):
3326 """
3326 """
3327 Try to extract prefix from existing cache key. The key could consist
3327 Try to extract prefix from existing cache key. The key could consist
3328 of prefix, repo_name, suffix
3328 of prefix, repo_name, suffix
3329 """
3329 """
3330 # this returns prefix, repo_name, suffix
3330 # this returns prefix, repo_name, suffix
3331 return self._cache_key_partition()[0]
3331 return self._cache_key_partition()[0]
3332
3332
3333 def get_suffix(self):
3333 def get_suffix(self):
3334 """
3334 """
3335 get suffix that might have been used in _get_cache_key to
3335 get suffix that might have been used in _get_cache_key to
3336 generate self.cache_key. Only used for informational purposes
3336 generate self.cache_key. Only used for informational purposes
3337 in repo_edit.mako.
3337 in repo_edit.mako.
3338 """
3338 """
3339 # prefix, repo_name, suffix
3339 # prefix, repo_name, suffix
3340 return self._cache_key_partition()[2]
3340 return self._cache_key_partition()[2]
3341
3341
3342 @classmethod
3342 @classmethod
3343 def delete_all_cache(cls):
3343 def delete_all_cache(cls):
3344 """
3344 """
3345 Delete all cache keys from database.
3345 Delete all cache keys from database.
3346 Should only be run when all instances are down and all entries
3346 Should only be run when all instances are down and all entries
3347 thus stale.
3347 thus stale.
3348 """
3348 """
3349 cls.query().delete()
3349 cls.query().delete()
3350 Session().commit()
3350 Session().commit()
3351
3351
3352 @classmethod
3352 @classmethod
3353 def set_invalidate(cls, cache_uid, delete=False):
3353 def set_invalidate(cls, cache_uid, delete=False):
3354 """
3354 """
3355 Mark all caches of a repo as invalid in the database.
3355 Mark all caches of a repo as invalid in the database.
3356 """
3356 """
3357
3357
3358 try:
3358 try:
3359 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3359 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3360 if delete:
3360 if delete:
3361 qry.delete()
3361 qry.delete()
3362 log.debug('cache objects deleted for cache args %s',
3362 log.debug('cache objects deleted for cache args %s',
3363 safe_str(cache_uid))
3363 safe_str(cache_uid))
3364 else:
3364 else:
3365 qry.update({"cache_active": False})
3365 qry.update({"cache_active": False})
3366 log.debug('cache objects marked as invalid for cache args %s',
3366 log.debug('cache objects marked as invalid for cache args %s',
3367 safe_str(cache_uid))
3367 safe_str(cache_uid))
3368
3368
3369 Session().commit()
3369 Session().commit()
3370 except Exception:
3370 except Exception:
3371 log.exception(
3371 log.exception(
3372 'Cache key invalidation failed for cache args %s',
3372 'Cache key invalidation failed for cache args %s',
3373 safe_str(cache_uid))
3373 safe_str(cache_uid))
3374 Session().rollback()
3374 Session().rollback()
3375
3375
3376 @classmethod
3376 @classmethod
3377 def get_active_cache(cls, cache_key):
3377 def get_active_cache(cls, cache_key):
3378 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3378 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3379 if inv_obj:
3379 if inv_obj:
3380 return inv_obj
3380 return inv_obj
3381 return None
3381 return None
3382
3382
3383
3383
3384 class ChangesetComment(Base, BaseModel):
3384 class ChangesetComment(Base, BaseModel):
3385 __tablename__ = 'changeset_comments'
3385 __tablename__ = 'changeset_comments'
3386 __table_args__ = (
3386 __table_args__ = (
3387 Index('cc_revision_idx', 'revision'),
3387 Index('cc_revision_idx', 'revision'),
3388 base_table_args,
3388 base_table_args,
3389 )
3389 )
3390
3390
3391 COMMENT_OUTDATED = u'comment_outdated'
3391 COMMENT_OUTDATED = u'comment_outdated'
3392 COMMENT_TYPE_NOTE = u'note'
3392 COMMENT_TYPE_NOTE = u'note'
3393 COMMENT_TYPE_TODO = u'todo'
3393 COMMENT_TYPE_TODO = u'todo'
3394 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3394 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3395
3395
3396 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3396 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3397 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3397 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3398 revision = Column('revision', String(40), nullable=True)
3398 revision = Column('revision', String(40), nullable=True)
3399 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3399 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3400 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3400 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3401 line_no = Column('line_no', Unicode(10), nullable=True)
3401 line_no = Column('line_no', Unicode(10), nullable=True)
3402 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3402 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3403 f_path = Column('f_path', Unicode(1000), nullable=True)
3403 f_path = Column('f_path', Unicode(1000), nullable=True)
3404 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3404 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3405 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3405 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3406 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3406 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3407 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3407 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3408 renderer = Column('renderer', Unicode(64), nullable=True)
3408 renderer = Column('renderer', Unicode(64), nullable=True)
3409 display_state = Column('display_state', Unicode(128), nullable=True)
3409 display_state = Column('display_state', Unicode(128), nullable=True)
3410
3410
3411 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3411 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3412 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3412 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3413
3413
3414 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3414 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3415 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3415 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3416
3416
3417 author = relationship('User', lazy='joined')
3417 author = relationship('User', lazy='joined')
3418 repo = relationship('Repository')
3418 repo = relationship('Repository')
3419 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3419 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3420 pull_request = relationship('PullRequest', lazy='joined')
3420 pull_request = relationship('PullRequest', lazy='joined')
3421 pull_request_version = relationship('PullRequestVersion')
3421 pull_request_version = relationship('PullRequestVersion')
3422
3422
3423 @classmethod
3423 @classmethod
3424 def get_users(cls, revision=None, pull_request_id=None):
3424 def get_users(cls, revision=None, pull_request_id=None):
3425 """
3425 """
3426 Returns user associated with this ChangesetComment. ie those
3426 Returns user associated with this ChangesetComment. ie those
3427 who actually commented
3427 who actually commented
3428
3428
3429 :param cls:
3429 :param cls:
3430 :param revision:
3430 :param revision:
3431 """
3431 """
3432 q = Session().query(User)\
3432 q = Session().query(User)\
3433 .join(ChangesetComment.author)
3433 .join(ChangesetComment.author)
3434 if revision:
3434 if revision:
3435 q = q.filter(cls.revision == revision)
3435 q = q.filter(cls.revision == revision)
3436 elif pull_request_id:
3436 elif pull_request_id:
3437 q = q.filter(cls.pull_request_id == pull_request_id)
3437 q = q.filter(cls.pull_request_id == pull_request_id)
3438 return q.all()
3438 return q.all()
3439
3439
3440 @classmethod
3440 @classmethod
3441 def get_index_from_version(cls, pr_version, versions):
3441 def get_index_from_version(cls, pr_version, versions):
3442 num_versions = [x.pull_request_version_id for x in versions]
3442 num_versions = [x.pull_request_version_id for x in versions]
3443 try:
3443 try:
3444 return num_versions.index(pr_version) +1
3444 return num_versions.index(pr_version) +1
3445 except (IndexError, ValueError):
3445 except (IndexError, ValueError):
3446 return
3446 return
3447
3447
3448 @property
3448 @property
3449 def outdated(self):
3449 def outdated(self):
3450 return self.display_state == self.COMMENT_OUTDATED
3450 return self.display_state == self.COMMENT_OUTDATED
3451
3451
3452 def outdated_at_version(self, version):
3452 def outdated_at_version(self, version):
3453 """
3453 """
3454 Checks if comment is outdated for given pull request version
3454 Checks if comment is outdated for given pull request version
3455 """
3455 """
3456 return self.outdated and self.pull_request_version_id != version
3456 return self.outdated and self.pull_request_version_id != version
3457
3457
3458 def older_than_version(self, version):
3458 def older_than_version(self, version):
3459 """
3459 """
3460 Checks if comment is made from previous version than given
3460 Checks if comment is made from previous version than given
3461 """
3461 """
3462 if version is None:
3462 if version is None:
3463 return self.pull_request_version_id is not None
3463 return self.pull_request_version_id is not None
3464
3464
3465 return self.pull_request_version_id < version
3465 return self.pull_request_version_id < version
3466
3466
3467 @property
3467 @property
3468 def resolved(self):
3468 def resolved(self):
3469 return self.resolved_by[0] if self.resolved_by else None
3469 return self.resolved_by[0] if self.resolved_by else None
3470
3470
3471 @property
3471 @property
3472 def is_todo(self):
3472 def is_todo(self):
3473 return self.comment_type == self.COMMENT_TYPE_TODO
3473 return self.comment_type == self.COMMENT_TYPE_TODO
3474
3474
3475 @property
3475 @property
3476 def is_inline(self):
3476 def is_inline(self):
3477 return self.line_no and self.f_path
3477 return self.line_no and self.f_path
3478
3478
3479 def get_index_version(self, versions):
3479 def get_index_version(self, versions):
3480 return self.get_index_from_version(
3480 return self.get_index_from_version(
3481 self.pull_request_version_id, versions)
3481 self.pull_request_version_id, versions)
3482
3482
3483 def __repr__(self):
3483 def __repr__(self):
3484 if self.comment_id:
3484 if self.comment_id:
3485 return '<DB:Comment #%s>' % self.comment_id
3485 return '<DB:Comment #%s>' % self.comment_id
3486 else:
3486 else:
3487 return '<DB:Comment at %#x>' % id(self)
3487 return '<DB:Comment at %#x>' % id(self)
3488
3488
3489 def get_api_data(self):
3489 def get_api_data(self):
3490 comment = self
3490 comment = self
3491 data = {
3491 data = {
3492 'comment_id': comment.comment_id,
3492 'comment_id': comment.comment_id,
3493 'comment_type': comment.comment_type,
3493 'comment_type': comment.comment_type,
3494 'comment_text': comment.text,
3494 'comment_text': comment.text,
3495 'comment_status': comment.status_change,
3495 'comment_status': comment.status_change,
3496 'comment_f_path': comment.f_path,
3496 'comment_f_path': comment.f_path,
3497 'comment_lineno': comment.line_no,
3497 'comment_lineno': comment.line_no,
3498 'comment_author': comment.author,
3498 'comment_author': comment.author,
3499 'comment_created_on': comment.created_on,
3499 'comment_created_on': comment.created_on,
3500 'comment_resolved_by': self.resolved
3500 'comment_resolved_by': self.resolved
3501 }
3501 }
3502 return data
3502 return data
3503
3503
3504 def __json__(self):
3504 def __json__(self):
3505 data = dict()
3505 data = dict()
3506 data.update(self.get_api_data())
3506 data.update(self.get_api_data())
3507 return data
3507 return data
3508
3508
3509
3509
3510 class ChangesetStatus(Base, BaseModel):
3510 class ChangesetStatus(Base, BaseModel):
3511 __tablename__ = 'changeset_statuses'
3511 __tablename__ = 'changeset_statuses'
3512 __table_args__ = (
3512 __table_args__ = (
3513 Index('cs_revision_idx', 'revision'),
3513 Index('cs_revision_idx', 'revision'),
3514 Index('cs_version_idx', 'version'),
3514 Index('cs_version_idx', 'version'),
3515 UniqueConstraint('repo_id', 'revision', 'version'),
3515 UniqueConstraint('repo_id', 'revision', 'version'),
3516 base_table_args
3516 base_table_args
3517 )
3517 )
3518
3518
3519 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3519 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3520 STATUS_APPROVED = 'approved'
3520 STATUS_APPROVED = 'approved'
3521 STATUS_REJECTED = 'rejected'
3521 STATUS_REJECTED = 'rejected'
3522 STATUS_UNDER_REVIEW = 'under_review'
3522 STATUS_UNDER_REVIEW = 'under_review'
3523
3523
3524 STATUSES = [
3524 STATUSES = [
3525 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3525 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3526 (STATUS_APPROVED, _("Approved")),
3526 (STATUS_APPROVED, _("Approved")),
3527 (STATUS_REJECTED, _("Rejected")),
3527 (STATUS_REJECTED, _("Rejected")),
3528 (STATUS_UNDER_REVIEW, _("Under Review")),
3528 (STATUS_UNDER_REVIEW, _("Under Review")),
3529 ]
3529 ]
3530
3530
3531 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3531 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3532 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3532 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3533 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3533 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3534 revision = Column('revision', String(40), nullable=False)
3534 revision = Column('revision', String(40), nullable=False)
3535 status = Column('status', String(128), nullable=False, default=DEFAULT)
3535 status = Column('status', String(128), nullable=False, default=DEFAULT)
3536 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3536 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3537 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3537 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3538 version = Column('version', Integer(), nullable=False, default=0)
3538 version = Column('version', Integer(), nullable=False, default=0)
3539 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3539 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3540
3540
3541 author = relationship('User', lazy='joined')
3541 author = relationship('User', lazy='joined')
3542 repo = relationship('Repository')
3542 repo = relationship('Repository')
3543 comment = relationship('ChangesetComment', lazy='joined')
3543 comment = relationship('ChangesetComment', lazy='joined')
3544 pull_request = relationship('PullRequest', lazy='joined')
3544 pull_request = relationship('PullRequest', lazy='joined')
3545
3545
3546 def __unicode__(self):
3546 def __unicode__(self):
3547 return u"<%s('%s[v%s]:%s')>" % (
3547 return u"<%s('%s[v%s]:%s')>" % (
3548 self.__class__.__name__,
3548 self.__class__.__name__,
3549 self.status, self.version, self.author
3549 self.status, self.version, self.author
3550 )
3550 )
3551
3551
3552 @classmethod
3552 @classmethod
3553 def get_status_lbl(cls, value):
3553 def get_status_lbl(cls, value):
3554 return dict(cls.STATUSES).get(value)
3554 return dict(cls.STATUSES).get(value)
3555
3555
3556 @property
3556 @property
3557 def status_lbl(self):
3557 def status_lbl(self):
3558 return ChangesetStatus.get_status_lbl(self.status)
3558 return ChangesetStatus.get_status_lbl(self.status)
3559
3559
3560 def get_api_data(self):
3560 def get_api_data(self):
3561 status = self
3561 status = self
3562 data = {
3562 data = {
3563 'status_id': status.changeset_status_id,
3563 'status_id': status.changeset_status_id,
3564 'status': status.status,
3564 'status': status.status,
3565 }
3565 }
3566 return data
3566 return data
3567
3567
3568 def __json__(self):
3568 def __json__(self):
3569 data = dict()
3569 data = dict()
3570 data.update(self.get_api_data())
3570 data.update(self.get_api_data())
3571 return data
3571 return data
3572
3572
3573
3573
3574 class _SetState(object):
3574 class _SetState(object):
3575 """
3575 """
3576 Context processor allowing changing state for sensitive operation such as
3576 Context processor allowing changing state for sensitive operation such as
3577 pull request update or merge
3577 pull request update or merge
3578 """
3578 """
3579
3579
3580 def __init__(self, pull_request, pr_state, back_state=None):
3580 def __init__(self, pull_request, pr_state, back_state=None):
3581 self._pr = pull_request
3581 self._pr = pull_request
3582 self._org_state = back_state or pull_request.pull_request_state
3582 self._org_state = back_state or pull_request.pull_request_state
3583 self._pr_state = pr_state
3583 self._pr_state = pr_state
3584
3584
3585 def __enter__(self):
3585 def __enter__(self):
3586 log.debug('StateLock: entering set state context, setting state to: `%s`',
3586 log.debug('StateLock: entering set state context, setting state to: `%s`',
3587 self._pr_state)
3587 self._pr_state)
3588 self._pr.pull_request_state = self._pr_state
3588 self._pr.pull_request_state = self._pr_state
3589 Session().add(self._pr)
3589 Session().add(self._pr)
3590 Session().commit()
3590 Session().commit()
3591
3591
3592 def __exit__(self, exc_type, exc_val, exc_tb):
3592 def __exit__(self, exc_type, exc_val, exc_tb):
3593 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3593 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3594 self._org_state)
3594 self._org_state)
3595 self._pr.pull_request_state = self._org_state
3595 self._pr.pull_request_state = self._org_state
3596 Session().add(self._pr)
3596 Session().add(self._pr)
3597 Session().commit()
3597 Session().commit()
3598
3598
3599
3599
3600 class _PullRequestBase(BaseModel):
3600 class _PullRequestBase(BaseModel):
3601 """
3601 """
3602 Common attributes of pull request and version entries.
3602 Common attributes of pull request and version entries.
3603 """
3603 """
3604
3604
3605 # .status values
3605 # .status values
3606 STATUS_NEW = u'new'
3606 STATUS_NEW = u'new'
3607 STATUS_OPEN = u'open'
3607 STATUS_OPEN = u'open'
3608 STATUS_CLOSED = u'closed'
3608 STATUS_CLOSED = u'closed'
3609
3609
3610 # available states
3610 # available states
3611 STATE_CREATING = u'creating'
3611 STATE_CREATING = u'creating'
3612 STATE_UPDATING = u'updating'
3612 STATE_UPDATING = u'updating'
3613 STATE_MERGING = u'merging'
3613 STATE_MERGING = u'merging'
3614 STATE_CREATED = u'created'
3614 STATE_CREATED = u'created'
3615
3615
3616 title = Column('title', Unicode(255), nullable=True)
3616 title = Column('title', Unicode(255), nullable=True)
3617 description = Column(
3617 description = Column(
3618 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3618 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3619 nullable=True)
3619 nullable=True)
3620 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3620 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3621
3621
3622 # new/open/closed status of pull request (not approve/reject/etc)
3622 # new/open/closed status of pull request (not approve/reject/etc)
3623 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3623 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3624 created_on = Column(
3624 created_on = Column(
3625 'created_on', DateTime(timezone=False), nullable=False,
3625 'created_on', DateTime(timezone=False), nullable=False,
3626 default=datetime.datetime.now)
3626 default=datetime.datetime.now)
3627 updated_on = Column(
3627 updated_on = Column(
3628 'updated_on', DateTime(timezone=False), nullable=False,
3628 'updated_on', DateTime(timezone=False), nullable=False,
3629 default=datetime.datetime.now)
3629 default=datetime.datetime.now)
3630
3630
3631 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3631 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3632
3632
3633 @declared_attr
3633 @declared_attr
3634 def user_id(cls):
3634 def user_id(cls):
3635 return Column(
3635 return Column(
3636 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3636 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3637 unique=None)
3637 unique=None)
3638
3638
3639 # 500 revisions max
3639 # 500 revisions max
3640 _revisions = Column(
3640 _revisions = Column(
3641 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3641 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3642
3642
3643 @declared_attr
3643 @declared_attr
3644 def source_repo_id(cls):
3644 def source_repo_id(cls):
3645 # TODO: dan: rename column to source_repo_id
3645 # TODO: dan: rename column to source_repo_id
3646 return Column(
3646 return Column(
3647 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3647 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3648 nullable=False)
3648 nullable=False)
3649
3649
3650 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3650 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3651
3651
3652 @hybrid_property
3652 @hybrid_property
3653 def source_ref(self):
3653 def source_ref(self):
3654 return self._source_ref
3654 return self._source_ref
3655
3655
3656 @source_ref.setter
3656 @source_ref.setter
3657 def source_ref(self, val):
3657 def source_ref(self, val):
3658 parts = (val or '').split(':')
3658 parts = (val or '').split(':')
3659 if len(parts) != 3:
3659 if len(parts) != 3:
3660 raise ValueError(
3660 raise ValueError(
3661 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3661 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3662 self._source_ref = safe_unicode(val)
3662 self._source_ref = safe_unicode(val)
3663
3663
3664 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3664 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3665
3665
3666 @hybrid_property
3666 @hybrid_property
3667 def target_ref(self):
3667 def target_ref(self):
3668 return self._target_ref
3668 return self._target_ref
3669
3669
3670 @target_ref.setter
3670 @target_ref.setter
3671 def target_ref(self, val):
3671 def target_ref(self, val):
3672 parts = (val or '').split(':')
3672 parts = (val or '').split(':')
3673 if len(parts) != 3:
3673 if len(parts) != 3:
3674 raise ValueError(
3674 raise ValueError(
3675 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3675 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3676 self._target_ref = safe_unicode(val)
3676 self._target_ref = safe_unicode(val)
3677
3677
3678 @declared_attr
3678 @declared_attr
3679 def target_repo_id(cls):
3679 def target_repo_id(cls):
3680 # TODO: dan: rename column to target_repo_id
3680 # TODO: dan: rename column to target_repo_id
3681 return Column(
3681 return Column(
3682 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3682 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3683 nullable=False)
3683 nullable=False)
3684
3684
3685 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3685 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3686
3686
3687 # TODO: dan: rename column to last_merge_source_rev
3687 # TODO: dan: rename column to last_merge_source_rev
3688 _last_merge_source_rev = Column(
3688 _last_merge_source_rev = Column(
3689 'last_merge_org_rev', String(40), nullable=True)
3689 'last_merge_org_rev', String(40), nullable=True)
3690 # TODO: dan: rename column to last_merge_target_rev
3690 # TODO: dan: rename column to last_merge_target_rev
3691 _last_merge_target_rev = Column(
3691 _last_merge_target_rev = Column(
3692 'last_merge_other_rev', String(40), nullable=True)
3692 'last_merge_other_rev', String(40), nullable=True)
3693 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3693 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3694 merge_rev = Column('merge_rev', String(40), nullable=True)
3694 merge_rev = Column('merge_rev', String(40), nullable=True)
3695
3695
3696 reviewer_data = Column(
3696 reviewer_data = Column(
3697 'reviewer_data_json', MutationObj.as_mutable(
3697 'reviewer_data_json', MutationObj.as_mutable(
3698 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3698 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3699
3699
3700 @property
3700 @property
3701 def reviewer_data_json(self):
3701 def reviewer_data_json(self):
3702 return json.dumps(self.reviewer_data)
3702 return json.dumps(self.reviewer_data)
3703
3703
3704 @hybrid_property
3704 @hybrid_property
3705 def description_safe(self):
3705 def description_safe(self):
3706 from rhodecode.lib import helpers as h
3706 from rhodecode.lib import helpers as h
3707 return h.escape(self.description)
3707 return h.escape(self.description)
3708
3708
3709 @hybrid_property
3709 @hybrid_property
3710 def revisions(self):
3710 def revisions(self):
3711 return self._revisions.split(':') if self._revisions else []
3711 return self._revisions.split(':') if self._revisions else []
3712
3712
3713 @revisions.setter
3713 @revisions.setter
3714 def revisions(self, val):
3714 def revisions(self, val):
3715 self._revisions = ':'.join(val)
3715 self._revisions = ':'.join(val)
3716
3716
3717 @hybrid_property
3717 @hybrid_property
3718 def last_merge_status(self):
3718 def last_merge_status(self):
3719 return safe_int(self._last_merge_status)
3719 return safe_int(self._last_merge_status)
3720
3720
3721 @last_merge_status.setter
3721 @last_merge_status.setter
3722 def last_merge_status(self, val):
3722 def last_merge_status(self, val):
3723 self._last_merge_status = val
3723 self._last_merge_status = val
3724
3724
3725 @declared_attr
3725 @declared_attr
3726 def author(cls):
3726 def author(cls):
3727 return relationship('User', lazy='joined')
3727 return relationship('User', lazy='joined')
3728
3728
3729 @declared_attr
3729 @declared_attr
3730 def source_repo(cls):
3730 def source_repo(cls):
3731 return relationship(
3731 return relationship(
3732 'Repository',
3732 'Repository',
3733 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3733 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3734
3734
3735 @property
3735 @property
3736 def source_ref_parts(self):
3736 def source_ref_parts(self):
3737 return self.unicode_to_reference(self.source_ref)
3737 return self.unicode_to_reference(self.source_ref)
3738
3738
3739 @declared_attr
3739 @declared_attr
3740 def target_repo(cls):
3740 def target_repo(cls):
3741 return relationship(
3741 return relationship(
3742 'Repository',
3742 'Repository',
3743 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3743 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3744
3744
3745 @property
3745 @property
3746 def target_ref_parts(self):
3746 def target_ref_parts(self):
3747 return self.unicode_to_reference(self.target_ref)
3747 return self.unicode_to_reference(self.target_ref)
3748
3748
3749 @property
3749 @property
3750 def shadow_merge_ref(self):
3750 def shadow_merge_ref(self):
3751 return self.unicode_to_reference(self._shadow_merge_ref)
3751 return self.unicode_to_reference(self._shadow_merge_ref)
3752
3752
3753 @shadow_merge_ref.setter
3753 @shadow_merge_ref.setter
3754 def shadow_merge_ref(self, ref):
3754 def shadow_merge_ref(self, ref):
3755 self._shadow_merge_ref = self.reference_to_unicode(ref)
3755 self._shadow_merge_ref = self.reference_to_unicode(ref)
3756
3756
3757 @staticmethod
3757 @staticmethod
3758 def unicode_to_reference(raw):
3758 def unicode_to_reference(raw):
3759 """
3759 """
3760 Convert a unicode (or string) to a reference object.
3760 Convert a unicode (or string) to a reference object.
3761 If unicode evaluates to False it returns None.
3761 If unicode evaluates to False it returns None.
3762 """
3762 """
3763 if raw:
3763 if raw:
3764 refs = raw.split(':')
3764 refs = raw.split(':')
3765 return Reference(*refs)
3765 return Reference(*refs)
3766 else:
3766 else:
3767 return None
3767 return None
3768
3768
3769 @staticmethod
3769 @staticmethod
3770 def reference_to_unicode(ref):
3770 def reference_to_unicode(ref):
3771 """
3771 """
3772 Convert a reference object to unicode.
3772 Convert a reference object to unicode.
3773 If reference is None it returns None.
3773 If reference is None it returns None.
3774 """
3774 """
3775 if ref:
3775 if ref:
3776 return u':'.join(ref)
3776 return u':'.join(ref)
3777 else:
3777 else:
3778 return None
3778 return None
3779
3779
3780 def get_api_data(self, with_merge_state=True):
3780 def get_api_data(self, with_merge_state=True):
3781 from rhodecode.model.pull_request import PullRequestModel
3781 from rhodecode.model.pull_request import PullRequestModel
3782
3782
3783 pull_request = self
3783 pull_request = self
3784 if with_merge_state:
3784 if with_merge_state:
3785 merge_status = PullRequestModel().merge_status(pull_request)
3785 merge_status = PullRequestModel().merge_status(pull_request)
3786 merge_state = {
3786 merge_state = {
3787 'status': merge_status[0],
3787 'status': merge_status[0],
3788 'message': safe_unicode(merge_status[1]),
3788 'message': safe_unicode(merge_status[1]),
3789 }
3789 }
3790 else:
3790 else:
3791 merge_state = {'status': 'not_available',
3791 merge_state = {'status': 'not_available',
3792 'message': 'not_available'}
3792 'message': 'not_available'}
3793
3793
3794 merge_data = {
3794 merge_data = {
3795 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3795 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3796 'reference': (
3796 'reference': (
3797 pull_request.shadow_merge_ref._asdict()
3797 pull_request.shadow_merge_ref._asdict()
3798 if pull_request.shadow_merge_ref else None),
3798 if pull_request.shadow_merge_ref else None),
3799 }
3799 }
3800
3800
3801 data = {
3801 data = {
3802 'pull_request_id': pull_request.pull_request_id,
3802 'pull_request_id': pull_request.pull_request_id,
3803 'url': PullRequestModel().get_url(pull_request),
3803 'url': PullRequestModel().get_url(pull_request),
3804 'title': pull_request.title,
3804 'title': pull_request.title,
3805 'description': pull_request.description,
3805 'description': pull_request.description,
3806 'status': pull_request.status,
3806 'status': pull_request.status,
3807 'state': pull_request.pull_request_state,
3807 'state': pull_request.pull_request_state,
3808 'created_on': pull_request.created_on,
3808 'created_on': pull_request.created_on,
3809 'updated_on': pull_request.updated_on,
3809 'updated_on': pull_request.updated_on,
3810 'commit_ids': pull_request.revisions,
3810 'commit_ids': pull_request.revisions,
3811 'review_status': pull_request.calculated_review_status(),
3811 'review_status': pull_request.calculated_review_status(),
3812 'mergeable': merge_state,
3812 'mergeable': merge_state,
3813 'source': {
3813 'source': {
3814 'clone_url': pull_request.source_repo.clone_url(),
3814 'clone_url': pull_request.source_repo.clone_url(),
3815 'repository': pull_request.source_repo.repo_name,
3815 'repository': pull_request.source_repo.repo_name,
3816 'reference': {
3816 'reference': {
3817 'name': pull_request.source_ref_parts.name,
3817 'name': pull_request.source_ref_parts.name,
3818 'type': pull_request.source_ref_parts.type,
3818 'type': pull_request.source_ref_parts.type,
3819 'commit_id': pull_request.source_ref_parts.commit_id,
3819 'commit_id': pull_request.source_ref_parts.commit_id,
3820 },
3820 },
3821 },
3821 },
3822 'target': {
3822 'target': {
3823 'clone_url': pull_request.target_repo.clone_url(),
3823 'clone_url': pull_request.target_repo.clone_url(),
3824 'repository': pull_request.target_repo.repo_name,
3824 'repository': pull_request.target_repo.repo_name,
3825 'reference': {
3825 'reference': {
3826 'name': pull_request.target_ref_parts.name,
3826 'name': pull_request.target_ref_parts.name,
3827 'type': pull_request.target_ref_parts.type,
3827 'type': pull_request.target_ref_parts.type,
3828 'commit_id': pull_request.target_ref_parts.commit_id,
3828 'commit_id': pull_request.target_ref_parts.commit_id,
3829 },
3829 },
3830 },
3830 },
3831 'merge': merge_data,
3831 'merge': merge_data,
3832 'author': pull_request.author.get_api_data(include_secrets=False,
3832 'author': pull_request.author.get_api_data(include_secrets=False,
3833 details='basic'),
3833 details='basic'),
3834 'reviewers': [
3834 'reviewers': [
3835 {
3835 {
3836 'user': reviewer.get_api_data(include_secrets=False,
3836 'user': reviewer.get_api_data(include_secrets=False,
3837 details='basic'),
3837 details='basic'),
3838 'reasons': reasons,
3838 'reasons': reasons,
3839 'review_status': st[0][1].status if st else 'not_reviewed',
3839 'review_status': st[0][1].status if st else 'not_reviewed',
3840 }
3840 }
3841 for obj, reviewer, reasons, mandatory, st in
3841 for obj, reviewer, reasons, mandatory, st in
3842 pull_request.reviewers_statuses()
3842 pull_request.reviewers_statuses()
3843 ]
3843 ]
3844 }
3844 }
3845
3845
3846 return data
3846 return data
3847
3847
3848 def set_state(self, pull_request_state, final_state=None):
3848 def set_state(self, pull_request_state, final_state=None):
3849 """
3849 """
3850 # goes from initial state to updating to initial state.
3850 # goes from initial state to updating to initial state.
3851 # initial state can be changed by specifying back_state=
3851 # initial state can be changed by specifying back_state=
3852 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
3852 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
3853 pull_request.merge()
3853 pull_request.merge()
3854
3854
3855 :param pull_request_state:
3855 :param pull_request_state:
3856 :param final_state:
3856 :param final_state:
3857
3857
3858 """
3858 """
3859
3859
3860 return _SetState(self, pull_request_state, back_state=final_state)
3860 return _SetState(self, pull_request_state, back_state=final_state)
3861
3861
3862
3862
3863 class PullRequest(Base, _PullRequestBase):
3863 class PullRequest(Base, _PullRequestBase):
3864 __tablename__ = 'pull_requests'
3864 __tablename__ = 'pull_requests'
3865 __table_args__ = (
3865 __table_args__ = (
3866 base_table_args,
3866 base_table_args,
3867 )
3867 )
3868
3868
3869 pull_request_id = Column(
3869 pull_request_id = Column(
3870 'pull_request_id', Integer(), nullable=False, primary_key=True)
3870 'pull_request_id', Integer(), nullable=False, primary_key=True)
3871
3871
3872 def __repr__(self):
3872 def __repr__(self):
3873 if self.pull_request_id:
3873 if self.pull_request_id:
3874 return '<DB:PullRequest #%s>' % self.pull_request_id
3874 return '<DB:PullRequest #%s>' % self.pull_request_id
3875 else:
3875 else:
3876 return '<DB:PullRequest at %#x>' % id(self)
3876 return '<DB:PullRequest at %#x>' % id(self)
3877
3877
3878 reviewers = relationship('PullRequestReviewers',
3878 reviewers = relationship('PullRequestReviewers',
3879 cascade="all, delete, delete-orphan")
3879 cascade="all, delete, delete-orphan")
3880 statuses = relationship('ChangesetStatus',
3880 statuses = relationship('ChangesetStatus',
3881 cascade="all, delete, delete-orphan")
3881 cascade="all, delete, delete-orphan")
3882 comments = relationship('ChangesetComment',
3882 comments = relationship('ChangesetComment',
3883 cascade="all, delete, delete-orphan")
3883 cascade="all, delete, delete-orphan")
3884 versions = relationship('PullRequestVersion',
3884 versions = relationship('PullRequestVersion',
3885 cascade="all, delete, delete-orphan",
3885 cascade="all, delete, delete-orphan",
3886 lazy='dynamic')
3886 lazy='dynamic')
3887
3887
3888 @classmethod
3888 @classmethod
3889 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3889 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3890 internal_methods=None):
3890 internal_methods=None):
3891
3891
3892 class PullRequestDisplay(object):
3892 class PullRequestDisplay(object):
3893 """
3893 """
3894 Special object wrapper for showing PullRequest data via Versions
3894 Special object wrapper for showing PullRequest data via Versions
3895 It mimics PR object as close as possible. This is read only object
3895 It mimics PR object as close as possible. This is read only object
3896 just for display
3896 just for display
3897 """
3897 """
3898
3898
3899 def __init__(self, attrs, internal=None):
3899 def __init__(self, attrs, internal=None):
3900 self.attrs = attrs
3900 self.attrs = attrs
3901 # internal have priority over the given ones via attrs
3901 # internal have priority over the given ones via attrs
3902 self.internal = internal or ['versions']
3902 self.internal = internal or ['versions']
3903
3903
3904 def __getattr__(self, item):
3904 def __getattr__(self, item):
3905 if item in self.internal:
3905 if item in self.internal:
3906 return getattr(self, item)
3906 return getattr(self, item)
3907 try:
3907 try:
3908 return self.attrs[item]
3908 return self.attrs[item]
3909 except KeyError:
3909 except KeyError:
3910 raise AttributeError(
3910 raise AttributeError(
3911 '%s object has no attribute %s' % (self, item))
3911 '%s object has no attribute %s' % (self, item))
3912
3912
3913 def __repr__(self):
3913 def __repr__(self):
3914 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3914 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3915
3915
3916 def versions(self):
3916 def versions(self):
3917 return pull_request_obj.versions.order_by(
3917 return pull_request_obj.versions.order_by(
3918 PullRequestVersion.pull_request_version_id).all()
3918 PullRequestVersion.pull_request_version_id).all()
3919
3919
3920 def is_closed(self):
3920 def is_closed(self):
3921 return pull_request_obj.is_closed()
3921 return pull_request_obj.is_closed()
3922
3922
3923 @property
3923 @property
3924 def pull_request_version_id(self):
3924 def pull_request_version_id(self):
3925 return getattr(pull_request_obj, 'pull_request_version_id', None)
3925 return getattr(pull_request_obj, 'pull_request_version_id', None)
3926
3926
3927 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3927 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3928
3928
3929 attrs.author = StrictAttributeDict(
3929 attrs.author = StrictAttributeDict(
3930 pull_request_obj.author.get_api_data())
3930 pull_request_obj.author.get_api_data())
3931 if pull_request_obj.target_repo:
3931 if pull_request_obj.target_repo:
3932 attrs.target_repo = StrictAttributeDict(
3932 attrs.target_repo = StrictAttributeDict(
3933 pull_request_obj.target_repo.get_api_data())
3933 pull_request_obj.target_repo.get_api_data())
3934 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3934 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3935
3935
3936 if pull_request_obj.source_repo:
3936 if pull_request_obj.source_repo:
3937 attrs.source_repo = StrictAttributeDict(
3937 attrs.source_repo = StrictAttributeDict(
3938 pull_request_obj.source_repo.get_api_data())
3938 pull_request_obj.source_repo.get_api_data())
3939 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3939 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3940
3940
3941 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3941 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3942 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3942 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3943 attrs.revisions = pull_request_obj.revisions
3943 attrs.revisions = pull_request_obj.revisions
3944
3944
3945 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3945 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3946 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3946 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3947 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3947 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3948
3948
3949 return PullRequestDisplay(attrs, internal=internal_methods)
3949 return PullRequestDisplay(attrs, internal=internal_methods)
3950
3950
3951 def is_closed(self):
3951 def is_closed(self):
3952 return self.status == self.STATUS_CLOSED
3952 return self.status == self.STATUS_CLOSED
3953
3953
3954 def __json__(self):
3954 def __json__(self):
3955 return {
3955 return {
3956 'revisions': self.revisions,
3956 'revisions': self.revisions,
3957 }
3957 }
3958
3958
3959 def calculated_review_status(self):
3959 def calculated_review_status(self):
3960 from rhodecode.model.changeset_status import ChangesetStatusModel
3960 from rhodecode.model.changeset_status import ChangesetStatusModel
3961 return ChangesetStatusModel().calculated_review_status(self)
3961 return ChangesetStatusModel().calculated_review_status(self)
3962
3962
3963 def reviewers_statuses(self):
3963 def reviewers_statuses(self):
3964 from rhodecode.model.changeset_status import ChangesetStatusModel
3964 from rhodecode.model.changeset_status import ChangesetStatusModel
3965 return ChangesetStatusModel().reviewers_statuses(self)
3965 return ChangesetStatusModel().reviewers_statuses(self)
3966
3966
3967 @property
3967 @property
3968 def workspace_id(self):
3968 def workspace_id(self):
3969 from rhodecode.model.pull_request import PullRequestModel
3969 from rhodecode.model.pull_request import PullRequestModel
3970 return PullRequestModel()._workspace_id(self)
3970 return PullRequestModel()._workspace_id(self)
3971
3971
3972 def get_shadow_repo(self):
3972 def get_shadow_repo(self):
3973 workspace_id = self.workspace_id
3973 workspace_id = self.workspace_id
3974 vcs_obj = self.target_repo.scm_instance()
3974 vcs_obj = self.target_repo.scm_instance()
3975 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3975 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3976 self.target_repo.repo_id, workspace_id)
3976 self.target_repo.repo_id, workspace_id)
3977 if os.path.isdir(shadow_repository_path):
3977 if os.path.isdir(shadow_repository_path):
3978 return vcs_obj.get_shadow_instance(shadow_repository_path)
3978 return vcs_obj.get_shadow_instance(shadow_repository_path)
3979
3979
3980
3980
3981 class PullRequestVersion(Base, _PullRequestBase):
3981 class PullRequestVersion(Base, _PullRequestBase):
3982 __tablename__ = 'pull_request_versions'
3982 __tablename__ = 'pull_request_versions'
3983 __table_args__ = (
3983 __table_args__ = (
3984 base_table_args,
3984 base_table_args,
3985 )
3985 )
3986
3986
3987 pull_request_version_id = Column(
3987 pull_request_version_id = Column(
3988 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3988 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3989 pull_request_id = Column(
3989 pull_request_id = Column(
3990 'pull_request_id', Integer(),
3990 'pull_request_id', Integer(),
3991 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3991 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3992 pull_request = relationship('PullRequest')
3992 pull_request = relationship('PullRequest')
3993
3993
3994 def __repr__(self):
3994 def __repr__(self):
3995 if self.pull_request_version_id:
3995 if self.pull_request_version_id:
3996 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3996 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3997 else:
3997 else:
3998 return '<DB:PullRequestVersion at %#x>' % id(self)
3998 return '<DB:PullRequestVersion at %#x>' % id(self)
3999
3999
4000 @property
4000 @property
4001 def reviewers(self):
4001 def reviewers(self):
4002 return self.pull_request.reviewers
4002 return self.pull_request.reviewers
4003
4003
4004 @property
4004 @property
4005 def versions(self):
4005 def versions(self):
4006 return self.pull_request.versions
4006 return self.pull_request.versions
4007
4007
4008 def is_closed(self):
4008 def is_closed(self):
4009 # calculate from original
4009 # calculate from original
4010 return self.pull_request.status == self.STATUS_CLOSED
4010 return self.pull_request.status == self.STATUS_CLOSED
4011
4011
4012 def calculated_review_status(self):
4012 def calculated_review_status(self):
4013 return self.pull_request.calculated_review_status()
4013 return self.pull_request.calculated_review_status()
4014
4014
4015 def reviewers_statuses(self):
4015 def reviewers_statuses(self):
4016 return self.pull_request.reviewers_statuses()
4016 return self.pull_request.reviewers_statuses()
4017
4017
4018
4018
4019 class PullRequestReviewers(Base, BaseModel):
4019 class PullRequestReviewers(Base, BaseModel):
4020 __tablename__ = 'pull_request_reviewers'
4020 __tablename__ = 'pull_request_reviewers'
4021 __table_args__ = (
4021 __table_args__ = (
4022 base_table_args,
4022 base_table_args,
4023 )
4023 )
4024
4024
4025 @hybrid_property
4025 @hybrid_property
4026 def reasons(self):
4026 def reasons(self):
4027 if not self._reasons:
4027 if not self._reasons:
4028 return []
4028 return []
4029 return self._reasons
4029 return self._reasons
4030
4030
4031 @reasons.setter
4031 @reasons.setter
4032 def reasons(self, val):
4032 def reasons(self, val):
4033 val = val or []
4033 val = val or []
4034 if any(not isinstance(x, compat.string_types) for x in val):
4034 if any(not isinstance(x, compat.string_types) for x in val):
4035 raise Exception('invalid reasons type, must be list of strings')
4035 raise Exception('invalid reasons type, must be list of strings')
4036 self._reasons = val
4036 self._reasons = val
4037
4037
4038 pull_requests_reviewers_id = Column(
4038 pull_requests_reviewers_id = Column(
4039 'pull_requests_reviewers_id', Integer(), nullable=False,
4039 'pull_requests_reviewers_id', Integer(), nullable=False,
4040 primary_key=True)
4040 primary_key=True)
4041 pull_request_id = Column(
4041 pull_request_id = Column(
4042 "pull_request_id", Integer(),
4042 "pull_request_id", Integer(),
4043 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4043 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4044 user_id = Column(
4044 user_id = Column(
4045 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4045 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4046 _reasons = Column(
4046 _reasons = Column(
4047 'reason', MutationList.as_mutable(
4047 'reason', MutationList.as_mutable(
4048 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4048 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4049
4049
4050 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4050 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4051 user = relationship('User')
4051 user = relationship('User')
4052 pull_request = relationship('PullRequest')
4052 pull_request = relationship('PullRequest')
4053
4053
4054 rule_data = Column(
4054 rule_data = Column(
4055 'rule_data_json',
4055 'rule_data_json',
4056 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4056 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4057
4057
4058 def rule_user_group_data(self):
4058 def rule_user_group_data(self):
4059 """
4059 """
4060 Returns the voting user group rule data for this reviewer
4060 Returns the voting user group rule data for this reviewer
4061 """
4061 """
4062
4062
4063 if self.rule_data and 'vote_rule' in self.rule_data:
4063 if self.rule_data and 'vote_rule' in self.rule_data:
4064 user_group_data = {}
4064 user_group_data = {}
4065 if 'rule_user_group_entry_id' in self.rule_data:
4065 if 'rule_user_group_entry_id' in self.rule_data:
4066 # means a group with voting rules !
4066 # means a group with voting rules !
4067 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4067 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4068 user_group_data['name'] = self.rule_data['rule_name']
4068 user_group_data['name'] = self.rule_data['rule_name']
4069 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4069 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4070
4070
4071 return user_group_data
4071 return user_group_data
4072
4072
4073 def __unicode__(self):
4073 def __unicode__(self):
4074 return u"<%s('id:%s')>" % (self.__class__.__name__,
4074 return u"<%s('id:%s')>" % (self.__class__.__name__,
4075 self.pull_requests_reviewers_id)
4075 self.pull_requests_reviewers_id)
4076
4076
4077
4077
4078 class Notification(Base, BaseModel):
4078 class Notification(Base, BaseModel):
4079 __tablename__ = 'notifications'
4079 __tablename__ = 'notifications'
4080 __table_args__ = (
4080 __table_args__ = (
4081 Index('notification_type_idx', 'type'),
4081 Index('notification_type_idx', 'type'),
4082 base_table_args,
4082 base_table_args,
4083 )
4083 )
4084
4084
4085 TYPE_CHANGESET_COMMENT = u'cs_comment'
4085 TYPE_CHANGESET_COMMENT = u'cs_comment'
4086 TYPE_MESSAGE = u'message'
4086 TYPE_MESSAGE = u'message'
4087 TYPE_MENTION = u'mention'
4087 TYPE_MENTION = u'mention'
4088 TYPE_REGISTRATION = u'registration'
4088 TYPE_REGISTRATION = u'registration'
4089 TYPE_PULL_REQUEST = u'pull_request'
4089 TYPE_PULL_REQUEST = u'pull_request'
4090 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4090 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4091
4091
4092 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4092 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4093 subject = Column('subject', Unicode(512), nullable=True)
4093 subject = Column('subject', Unicode(512), nullable=True)
4094 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4094 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4095 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4095 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4096 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4096 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4097 type_ = Column('type', Unicode(255))
4097 type_ = Column('type', Unicode(255))
4098
4098
4099 created_by_user = relationship('User')
4099 created_by_user = relationship('User')
4100 notifications_to_users = relationship('UserNotification', lazy='joined',
4100 notifications_to_users = relationship('UserNotification', lazy='joined',
4101 cascade="all, delete, delete-orphan")
4101 cascade="all, delete, delete-orphan")
4102
4102
4103 @property
4103 @property
4104 def recipients(self):
4104 def recipients(self):
4105 return [x.user for x in UserNotification.query()\
4105 return [x.user for x in UserNotification.query()\
4106 .filter(UserNotification.notification == self)\
4106 .filter(UserNotification.notification == self)\
4107 .order_by(UserNotification.user_id.asc()).all()]
4107 .order_by(UserNotification.user_id.asc()).all()]
4108
4108
4109 @classmethod
4109 @classmethod
4110 def create(cls, created_by, subject, body, recipients, type_=None):
4110 def create(cls, created_by, subject, body, recipients, type_=None):
4111 if type_ is None:
4111 if type_ is None:
4112 type_ = Notification.TYPE_MESSAGE
4112 type_ = Notification.TYPE_MESSAGE
4113
4113
4114 notification = cls()
4114 notification = cls()
4115 notification.created_by_user = created_by
4115 notification.created_by_user = created_by
4116 notification.subject = subject
4116 notification.subject = subject
4117 notification.body = body
4117 notification.body = body
4118 notification.type_ = type_
4118 notification.type_ = type_
4119 notification.created_on = datetime.datetime.now()
4119 notification.created_on = datetime.datetime.now()
4120
4120
4121 # For each recipient link the created notification to his account
4121 # For each recipient link the created notification to his account
4122 for u in recipients:
4122 for u in recipients:
4123 assoc = UserNotification()
4123 assoc = UserNotification()
4124 assoc.user_id = u.user_id
4124 assoc.user_id = u.user_id
4125 assoc.notification = notification
4125 assoc.notification = notification
4126
4126
4127 # if created_by is inside recipients mark his notification
4127 # if created_by is inside recipients mark his notification
4128 # as read
4128 # as read
4129 if u.user_id == created_by.user_id:
4129 if u.user_id == created_by.user_id:
4130 assoc.read = True
4130 assoc.read = True
4131 Session().add(assoc)
4131 Session().add(assoc)
4132
4132
4133 Session().add(notification)
4133 Session().add(notification)
4134
4134
4135 return notification
4135 return notification
4136
4136
4137
4137
4138 class UserNotification(Base, BaseModel):
4138 class UserNotification(Base, BaseModel):
4139 __tablename__ = 'user_to_notification'
4139 __tablename__ = 'user_to_notification'
4140 __table_args__ = (
4140 __table_args__ = (
4141 UniqueConstraint('user_id', 'notification_id'),
4141 UniqueConstraint('user_id', 'notification_id'),
4142 base_table_args
4142 base_table_args
4143 )
4143 )
4144
4144
4145 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4145 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4146 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4146 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4147 read = Column('read', Boolean, default=False)
4147 read = Column('read', Boolean, default=False)
4148 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4148 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4149
4149
4150 user = relationship('User', lazy="joined")
4150 user = relationship('User', lazy="joined")
4151 notification = relationship('Notification', lazy="joined",
4151 notification = relationship('Notification', lazy="joined",
4152 order_by=lambda: Notification.created_on.desc(),)
4152 order_by=lambda: Notification.created_on.desc(),)
4153
4153
4154 def mark_as_read(self):
4154 def mark_as_read(self):
4155 self.read = True
4155 self.read = True
4156 Session().add(self)
4156 Session().add(self)
4157
4157
4158
4158
4159 class Gist(Base, BaseModel):
4159 class Gist(Base, BaseModel):
4160 __tablename__ = 'gists'
4160 __tablename__ = 'gists'
4161 __table_args__ = (
4161 __table_args__ = (
4162 Index('g_gist_access_id_idx', 'gist_access_id'),
4162 Index('g_gist_access_id_idx', 'gist_access_id'),
4163 Index('g_created_on_idx', 'created_on'),
4163 Index('g_created_on_idx', 'created_on'),
4164 base_table_args
4164 base_table_args
4165 )
4165 )
4166
4166
4167 GIST_PUBLIC = u'public'
4167 GIST_PUBLIC = u'public'
4168 GIST_PRIVATE = u'private'
4168 GIST_PRIVATE = u'private'
4169 DEFAULT_FILENAME = u'gistfile1.txt'
4169 DEFAULT_FILENAME = u'gistfile1.txt'
4170
4170
4171 ACL_LEVEL_PUBLIC = u'acl_public'
4171 ACL_LEVEL_PUBLIC = u'acl_public'
4172 ACL_LEVEL_PRIVATE = u'acl_private'
4172 ACL_LEVEL_PRIVATE = u'acl_private'
4173
4173
4174 gist_id = Column('gist_id', Integer(), primary_key=True)
4174 gist_id = Column('gist_id', Integer(), primary_key=True)
4175 gist_access_id = Column('gist_access_id', Unicode(250))
4175 gist_access_id = Column('gist_access_id', Unicode(250))
4176 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4176 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4177 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4177 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4178 gist_expires = Column('gist_expires', Float(53), nullable=False)
4178 gist_expires = Column('gist_expires', Float(53), nullable=False)
4179 gist_type = Column('gist_type', Unicode(128), nullable=False)
4179 gist_type = Column('gist_type', Unicode(128), nullable=False)
4180 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4180 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4181 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4181 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4182 acl_level = Column('acl_level', Unicode(128), nullable=True)
4182 acl_level = Column('acl_level', Unicode(128), nullable=True)
4183
4183
4184 owner = relationship('User')
4184 owner = relationship('User')
4185
4185
4186 def __repr__(self):
4186 def __repr__(self):
4187 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4187 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4188
4188
4189 @hybrid_property
4189 @hybrid_property
4190 def description_safe(self):
4190 def description_safe(self):
4191 from rhodecode.lib import helpers as h
4191 from rhodecode.lib import helpers as h
4192 return h.escape(self.gist_description)
4192 return h.escape(self.gist_description)
4193
4193
4194 @classmethod
4194 @classmethod
4195 def get_or_404(cls, id_):
4195 def get_or_404(cls, id_):
4196 from pyramid.httpexceptions import HTTPNotFound
4196 from pyramid.httpexceptions import HTTPNotFound
4197
4197
4198 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4198 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4199 if not res:
4199 if not res:
4200 raise HTTPNotFound()
4200 raise HTTPNotFound()
4201 return res
4201 return res
4202
4202
4203 @classmethod
4203 @classmethod
4204 def get_by_access_id(cls, gist_access_id):
4204 def get_by_access_id(cls, gist_access_id):
4205 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4205 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4206
4206
4207 def gist_url(self):
4207 def gist_url(self):
4208 from rhodecode.model.gist import GistModel
4208 from rhodecode.model.gist import GistModel
4209 return GistModel().get_url(self)
4209 return GistModel().get_url(self)
4210
4210
4211 @classmethod
4211 @classmethod
4212 def base_path(cls):
4212 def base_path(cls):
4213 """
4213 """
4214 Returns base path when all gists are stored
4214 Returns base path when all gists are stored
4215
4215
4216 :param cls:
4216 :param cls:
4217 """
4217 """
4218 from rhodecode.model.gist import GIST_STORE_LOC
4218 from rhodecode.model.gist import GIST_STORE_LOC
4219 q = Session().query(RhodeCodeUi)\
4219 q = Session().query(RhodeCodeUi)\
4220 .filter(RhodeCodeUi.ui_key == URL_SEP)
4220 .filter(RhodeCodeUi.ui_key == URL_SEP)
4221 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4221 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4222 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4222 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4223
4223
4224 def get_api_data(self):
4224 def get_api_data(self):
4225 """
4225 """
4226 Common function for generating gist related data for API
4226 Common function for generating gist related data for API
4227 """
4227 """
4228 gist = self
4228 gist = self
4229 data = {
4229 data = {
4230 'gist_id': gist.gist_id,
4230 'gist_id': gist.gist_id,
4231 'type': gist.gist_type,
4231 'type': gist.gist_type,
4232 'access_id': gist.gist_access_id,
4232 'access_id': gist.gist_access_id,
4233 'description': gist.gist_description,
4233 'description': gist.gist_description,
4234 'url': gist.gist_url(),
4234 'url': gist.gist_url(),
4235 'expires': gist.gist_expires,
4235 'expires': gist.gist_expires,
4236 'created_on': gist.created_on,
4236 'created_on': gist.created_on,
4237 'modified_at': gist.modified_at,
4237 'modified_at': gist.modified_at,
4238 'content': None,
4238 'content': None,
4239 'acl_level': gist.acl_level,
4239 'acl_level': gist.acl_level,
4240 }
4240 }
4241 return data
4241 return data
4242
4242
4243 def __json__(self):
4243 def __json__(self):
4244 data = dict(
4244 data = dict(
4245 )
4245 )
4246 data.update(self.get_api_data())
4246 data.update(self.get_api_data())
4247 return data
4247 return data
4248 # SCM functions
4248 # SCM functions
4249
4249
4250 def scm_instance(self, **kwargs):
4250 def scm_instance(self, **kwargs):
4251 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4251 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4252 return get_vcs_instance(
4252 return get_vcs_instance(
4253 repo_path=safe_str(full_repo_path), create=False)
4253 repo_path=safe_str(full_repo_path), create=False)
4254
4254
4255
4255
4256 class ExternalIdentity(Base, BaseModel):
4256 class ExternalIdentity(Base, BaseModel):
4257 __tablename__ = 'external_identities'
4257 __tablename__ = 'external_identities'
4258 __table_args__ = (
4258 __table_args__ = (
4259 Index('local_user_id_idx', 'local_user_id'),
4259 Index('local_user_id_idx', 'local_user_id'),
4260 Index('external_id_idx', 'external_id'),
4260 Index('external_id_idx', 'external_id'),
4261 base_table_args
4261 base_table_args
4262 )
4262 )
4263
4263
4264 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4264 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4265 external_username = Column('external_username', Unicode(1024), default=u'')
4265 external_username = Column('external_username', Unicode(1024), default=u'')
4266 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4266 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4267 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4267 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4268 access_token = Column('access_token', String(1024), default=u'')
4268 access_token = Column('access_token', String(1024), default=u'')
4269 alt_token = Column('alt_token', String(1024), default=u'')
4269 alt_token = Column('alt_token', String(1024), default=u'')
4270 token_secret = Column('token_secret', String(1024), default=u'')
4270 token_secret = Column('token_secret', String(1024), default=u'')
4271
4271
4272 @classmethod
4272 @classmethod
4273 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4273 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4274 """
4274 """
4275 Returns ExternalIdentity instance based on search params
4275 Returns ExternalIdentity instance based on search params
4276
4276
4277 :param external_id:
4277 :param external_id:
4278 :param provider_name:
4278 :param provider_name:
4279 :return: ExternalIdentity
4279 :return: ExternalIdentity
4280 """
4280 """
4281 query = cls.query()
4281 query = cls.query()
4282 query = query.filter(cls.external_id == external_id)
4282 query = query.filter(cls.external_id == external_id)
4283 query = query.filter(cls.provider_name == provider_name)
4283 query = query.filter(cls.provider_name == provider_name)
4284 if local_user_id:
4284 if local_user_id:
4285 query = query.filter(cls.local_user_id == local_user_id)
4285 query = query.filter(cls.local_user_id == local_user_id)
4286 return query.first()
4286 return query.first()
4287
4287
4288 @classmethod
4288 @classmethod
4289 def user_by_external_id_and_provider(cls, external_id, provider_name):
4289 def user_by_external_id_and_provider(cls, external_id, provider_name):
4290 """
4290 """
4291 Returns User instance based on search params
4291 Returns User instance based on search params
4292
4292
4293 :param external_id:
4293 :param external_id:
4294 :param provider_name:
4294 :param provider_name:
4295 :return: User
4295 :return: User
4296 """
4296 """
4297 query = User.query()
4297 query = User.query()
4298 query = query.filter(cls.external_id == external_id)
4298 query = query.filter(cls.external_id == external_id)
4299 query = query.filter(cls.provider_name == provider_name)
4299 query = query.filter(cls.provider_name == provider_name)
4300 query = query.filter(User.user_id == cls.local_user_id)
4300 query = query.filter(User.user_id == cls.local_user_id)
4301 return query.first()
4301 return query.first()
4302
4302
4303 @classmethod
4303 @classmethod
4304 def by_local_user_id(cls, local_user_id):
4304 def by_local_user_id(cls, local_user_id):
4305 """
4305 """
4306 Returns all tokens for user
4306 Returns all tokens for user
4307
4307
4308 :param local_user_id:
4308 :param local_user_id:
4309 :return: ExternalIdentity
4309 :return: ExternalIdentity
4310 """
4310 """
4311 query = cls.query()
4311 query = cls.query()
4312 query = query.filter(cls.local_user_id == local_user_id)
4312 query = query.filter(cls.local_user_id == local_user_id)
4313 return query
4313 return query
4314
4314
4315 @classmethod
4315 @classmethod
4316 def load_provider_plugin(cls, plugin_id):
4316 def load_provider_plugin(cls, plugin_id):
4317 from rhodecode.authentication.base import loadplugin
4317 from rhodecode.authentication.base import loadplugin
4318 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4318 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4319 auth_plugin = loadplugin(_plugin_id)
4319 auth_plugin = loadplugin(_plugin_id)
4320 return auth_plugin
4320 return auth_plugin
4321
4321
4322
4322
4323 class Integration(Base, BaseModel):
4323 class Integration(Base, BaseModel):
4324 __tablename__ = 'integrations'
4324 __tablename__ = 'integrations'
4325 __table_args__ = (
4325 __table_args__ = (
4326 base_table_args
4326 base_table_args
4327 )
4327 )
4328
4328
4329 integration_id = Column('integration_id', Integer(), primary_key=True)
4329 integration_id = Column('integration_id', Integer(), primary_key=True)
4330 integration_type = Column('integration_type', String(255))
4330 integration_type = Column('integration_type', String(255))
4331 enabled = Column('enabled', Boolean(), nullable=False)
4331 enabled = Column('enabled', Boolean(), nullable=False)
4332 name = Column('name', String(255), nullable=False)
4332 name = Column('name', String(255), nullable=False)
4333 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4333 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4334 default=False)
4334 default=False)
4335
4335
4336 settings = Column(
4336 settings = Column(
4337 'settings_json', MutationObj.as_mutable(
4337 'settings_json', MutationObj.as_mutable(
4338 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4338 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4339 repo_id = Column(
4339 repo_id = Column(
4340 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4340 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4341 nullable=True, unique=None, default=None)
4341 nullable=True, unique=None, default=None)
4342 repo = relationship('Repository', lazy='joined')
4342 repo = relationship('Repository', lazy='joined')
4343
4343
4344 repo_group_id = Column(
4344 repo_group_id = Column(
4345 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4345 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4346 nullable=True, unique=None, default=None)
4346 nullable=True, unique=None, default=None)
4347 repo_group = relationship('RepoGroup', lazy='joined')
4347 repo_group = relationship('RepoGroup', lazy='joined')
4348
4348
4349 @property
4349 @property
4350 def scope(self):
4350 def scope(self):
4351 if self.repo:
4351 if self.repo:
4352 return repr(self.repo)
4352 return repr(self.repo)
4353 if self.repo_group:
4353 if self.repo_group:
4354 if self.child_repos_only:
4354 if self.child_repos_only:
4355 return repr(self.repo_group) + ' (child repos only)'
4355 return repr(self.repo_group) + ' (child repos only)'
4356 else:
4356 else:
4357 return repr(self.repo_group) + ' (recursive)'
4357 return repr(self.repo_group) + ' (recursive)'
4358 if self.child_repos_only:
4358 if self.child_repos_only:
4359 return 'root_repos'
4359 return 'root_repos'
4360 return 'global'
4360 return 'global'
4361
4361
4362 def __repr__(self):
4362 def __repr__(self):
4363 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4363 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4364
4364
4365
4365
4366 class RepoReviewRuleUser(Base, BaseModel):
4366 class RepoReviewRuleUser(Base, BaseModel):
4367 __tablename__ = 'repo_review_rules_users'
4367 __tablename__ = 'repo_review_rules_users'
4368 __table_args__ = (
4368 __table_args__ = (
4369 base_table_args
4369 base_table_args
4370 )
4370 )
4371
4371
4372 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4372 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4373 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4373 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4374 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4374 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4375 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4375 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4376 user = relationship('User')
4376 user = relationship('User')
4377
4377
4378 def rule_data(self):
4378 def rule_data(self):
4379 return {
4379 return {
4380 'mandatory': self.mandatory
4380 'mandatory': self.mandatory
4381 }
4381 }
4382
4382
4383
4383
4384 class RepoReviewRuleUserGroup(Base, BaseModel):
4384 class RepoReviewRuleUserGroup(Base, BaseModel):
4385 __tablename__ = 'repo_review_rules_users_groups'
4385 __tablename__ = 'repo_review_rules_users_groups'
4386 __table_args__ = (
4386 __table_args__ = (
4387 base_table_args
4387 base_table_args
4388 )
4388 )
4389
4389
4390 VOTE_RULE_ALL = -1
4390 VOTE_RULE_ALL = -1
4391
4391
4392 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4392 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4393 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4393 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4394 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4394 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4395 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4395 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4396 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4396 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4397 users_group = relationship('UserGroup')
4397 users_group = relationship('UserGroup')
4398
4398
4399 def rule_data(self):
4399 def rule_data(self):
4400 return {
4400 return {
4401 'mandatory': self.mandatory,
4401 'mandatory': self.mandatory,
4402 'vote_rule': self.vote_rule
4402 'vote_rule': self.vote_rule
4403 }
4403 }
4404
4404
4405 @property
4405 @property
4406 def vote_rule_label(self):
4406 def vote_rule_label(self):
4407 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4407 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4408 return 'all must vote'
4408 return 'all must vote'
4409 else:
4409 else:
4410 return 'min. vote {}'.format(self.vote_rule)
4410 return 'min. vote {}'.format(self.vote_rule)
4411
4411
4412
4412
4413 class RepoReviewRule(Base, BaseModel):
4413 class RepoReviewRule(Base, BaseModel):
4414 __tablename__ = 'repo_review_rules'
4414 __tablename__ = 'repo_review_rules'
4415 __table_args__ = (
4415 __table_args__ = (
4416 base_table_args
4416 base_table_args
4417 )
4417 )
4418
4418
4419 repo_review_rule_id = Column(
4419 repo_review_rule_id = Column(
4420 'repo_review_rule_id', Integer(), primary_key=True)
4420 'repo_review_rule_id', Integer(), primary_key=True)
4421 repo_id = Column(
4421 repo_id = Column(
4422 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4422 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4423 repo = relationship('Repository', backref='review_rules')
4423 repo = relationship('Repository', backref='review_rules')
4424
4424
4425 review_rule_name = Column('review_rule_name', String(255))
4425 review_rule_name = Column('review_rule_name', String(255))
4426 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4426 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4427 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4427 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4428 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4428 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4429
4429
4430 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4430 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4431 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4431 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4432 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4432 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4433 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4433 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4434
4434
4435 rule_users = relationship('RepoReviewRuleUser')
4435 rule_users = relationship('RepoReviewRuleUser')
4436 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4436 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4437
4437
4438 def _validate_pattern(self, value):
4438 def _validate_pattern(self, value):
4439 re.compile('^' + glob2re(value) + '$')
4439 re.compile('^' + glob2re(value) + '$')
4440
4440
4441 @hybrid_property
4441 @hybrid_property
4442 def source_branch_pattern(self):
4442 def source_branch_pattern(self):
4443 return self._branch_pattern or '*'
4443 return self._branch_pattern or '*'
4444
4444
4445 @source_branch_pattern.setter
4445 @source_branch_pattern.setter
4446 def source_branch_pattern(self, value):
4446 def source_branch_pattern(self, value):
4447 self._validate_pattern(value)
4447 self._validate_pattern(value)
4448 self._branch_pattern = value or '*'
4448 self._branch_pattern = value or '*'
4449
4449
4450 @hybrid_property
4450 @hybrid_property
4451 def target_branch_pattern(self):
4451 def target_branch_pattern(self):
4452 return self._target_branch_pattern or '*'
4452 return self._target_branch_pattern or '*'
4453
4453
4454 @target_branch_pattern.setter
4454 @target_branch_pattern.setter
4455 def target_branch_pattern(self, value):
4455 def target_branch_pattern(self, value):
4456 self._validate_pattern(value)
4456 self._validate_pattern(value)
4457 self._target_branch_pattern = value or '*'
4457 self._target_branch_pattern = value or '*'
4458
4458
4459 @hybrid_property
4459 @hybrid_property
4460 def file_pattern(self):
4460 def file_pattern(self):
4461 return self._file_pattern or '*'
4461 return self._file_pattern or '*'
4462
4462
4463 @file_pattern.setter
4463 @file_pattern.setter
4464 def file_pattern(self, value):
4464 def file_pattern(self, value):
4465 self._validate_pattern(value)
4465 self._validate_pattern(value)
4466 self._file_pattern = value or '*'
4466 self._file_pattern = value or '*'
4467
4467
4468 def matches(self, source_branch, target_branch, files_changed):
4468 def matches(self, source_branch, target_branch, files_changed):
4469 """
4469 """
4470 Check if this review rule matches a branch/files in a pull request
4470 Check if this review rule matches a branch/files in a pull request
4471
4471
4472 :param source_branch: source branch name for the commit
4472 :param source_branch: source branch name for the commit
4473 :param target_branch: target branch name for the commit
4473 :param target_branch: target branch name for the commit
4474 :param files_changed: list of file paths changed in the pull request
4474 :param files_changed: list of file paths changed in the pull request
4475 """
4475 """
4476
4476
4477 source_branch = source_branch or ''
4477 source_branch = source_branch or ''
4478 target_branch = target_branch or ''
4478 target_branch = target_branch or ''
4479 files_changed = files_changed or []
4479 files_changed = files_changed or []
4480
4480
4481 branch_matches = True
4481 branch_matches = True
4482 if source_branch or target_branch:
4482 if source_branch or target_branch:
4483 if self.source_branch_pattern == '*':
4483 if self.source_branch_pattern == '*':
4484 source_branch_match = True
4484 source_branch_match = True
4485 else:
4485 else:
4486 if self.source_branch_pattern.startswith('re:'):
4486 if self.source_branch_pattern.startswith('re:'):
4487 source_pattern = self.source_branch_pattern[3:]
4487 source_pattern = self.source_branch_pattern[3:]
4488 else:
4488 else:
4489 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4489 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4490 source_branch_regex = re.compile(source_pattern)
4490 source_branch_regex = re.compile(source_pattern)
4491 source_branch_match = bool(source_branch_regex.search(source_branch))
4491 source_branch_match = bool(source_branch_regex.search(source_branch))
4492 if self.target_branch_pattern == '*':
4492 if self.target_branch_pattern == '*':
4493 target_branch_match = True
4493 target_branch_match = True
4494 else:
4494 else:
4495 if self.target_branch_pattern.startswith('re:'):
4495 if self.target_branch_pattern.startswith('re:'):
4496 target_pattern = self.target_branch_pattern[3:]
4496 target_pattern = self.target_branch_pattern[3:]
4497 else:
4497 else:
4498 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4498 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4499 target_branch_regex = re.compile(target_pattern)
4499 target_branch_regex = re.compile(target_pattern)
4500 target_branch_match = bool(target_branch_regex.search(target_branch))
4500 target_branch_match = bool(target_branch_regex.search(target_branch))
4501
4501
4502 branch_matches = source_branch_match and target_branch_match
4502 branch_matches = source_branch_match and target_branch_match
4503
4503
4504 files_matches = True
4504 files_matches = True
4505 if self.file_pattern != '*':
4505 if self.file_pattern != '*':
4506 files_matches = False
4506 files_matches = False
4507 if self.file_pattern.startswith('re:'):
4507 if self.file_pattern.startswith('re:'):
4508 file_pattern = self.file_pattern[3:]
4508 file_pattern = self.file_pattern[3:]
4509 else:
4509 else:
4510 file_pattern = glob2re(self.file_pattern)
4510 file_pattern = glob2re(self.file_pattern)
4511 file_regex = re.compile(file_pattern)
4511 file_regex = re.compile(file_pattern)
4512 for filename in files_changed:
4512 for filename in files_changed:
4513 if file_regex.search(filename):
4513 if file_regex.search(filename):
4514 files_matches = True
4514 files_matches = True
4515 break
4515 break
4516
4516
4517 return branch_matches and files_matches
4517 return branch_matches and files_matches
4518
4518
4519 @property
4519 @property
4520 def review_users(self):
4520 def review_users(self):
4521 """ Returns the users which this rule applies to """
4521 """ Returns the users which this rule applies to """
4522
4522
4523 users = collections.OrderedDict()
4523 users = collections.OrderedDict()
4524
4524
4525 for rule_user in self.rule_users:
4525 for rule_user in self.rule_users:
4526 if rule_user.user.active:
4526 if rule_user.user.active:
4527 if rule_user.user not in users:
4527 if rule_user.user not in users:
4528 users[rule_user.user.username] = {
4528 users[rule_user.user.username] = {
4529 'user': rule_user.user,
4529 'user': rule_user.user,
4530 'source': 'user',
4530 'source': 'user',
4531 'source_data': {},
4531 'source_data': {},
4532 'data': rule_user.rule_data()
4532 'data': rule_user.rule_data()
4533 }
4533 }
4534
4534
4535 for rule_user_group in self.rule_user_groups:
4535 for rule_user_group in self.rule_user_groups:
4536 source_data = {
4536 source_data = {
4537 'user_group_id': rule_user_group.users_group.users_group_id,
4537 'user_group_id': rule_user_group.users_group.users_group_id,
4538 'name': rule_user_group.users_group.users_group_name,
4538 'name': rule_user_group.users_group.users_group_name,
4539 'members': len(rule_user_group.users_group.members)
4539 'members': len(rule_user_group.users_group.members)
4540 }
4540 }
4541 for member in rule_user_group.users_group.members:
4541 for member in rule_user_group.users_group.members:
4542 if member.user.active:
4542 if member.user.active:
4543 key = member.user.username
4543 key = member.user.username
4544 if key in users:
4544 if key in users:
4545 # skip this member as we have him already
4545 # skip this member as we have him already
4546 # this prevents from override the "first" matched
4546 # this prevents from override the "first" matched
4547 # users with duplicates in multiple groups
4547 # users with duplicates in multiple groups
4548 continue
4548 continue
4549
4549
4550 users[key] = {
4550 users[key] = {
4551 'user': member.user,
4551 'user': member.user,
4552 'source': 'user_group',
4552 'source': 'user_group',
4553 'source_data': source_data,
4553 'source_data': source_data,
4554 'data': rule_user_group.rule_data()
4554 'data': rule_user_group.rule_data()
4555 }
4555 }
4556
4556
4557 return users
4557 return users
4558
4558
4559 def user_group_vote_rule(self, user_id):
4559 def user_group_vote_rule(self, user_id):
4560
4560
4561 rules = []
4561 rules = []
4562 if not self.rule_user_groups:
4562 if not self.rule_user_groups:
4563 return rules
4563 return rules
4564
4564
4565 for user_group in self.rule_user_groups:
4565 for user_group in self.rule_user_groups:
4566 user_group_members = [x.user_id for x in user_group.users_group.members]
4566 user_group_members = [x.user_id for x in user_group.users_group.members]
4567 if user_id in user_group_members:
4567 if user_id in user_group_members:
4568 rules.append(user_group)
4568 rules.append(user_group)
4569 return rules
4569 return rules
4570
4570
4571 def __repr__(self):
4571 def __repr__(self):
4572 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4572 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4573 self.repo_review_rule_id, self.repo)
4573 self.repo_review_rule_id, self.repo)
4574
4574
4575
4575
4576 class ScheduleEntry(Base, BaseModel):
4576 class ScheduleEntry(Base, BaseModel):
4577 __tablename__ = 'schedule_entries'
4577 __tablename__ = 'schedule_entries'
4578 __table_args__ = (
4578 __table_args__ = (
4579 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4579 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4580 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4580 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4581 base_table_args,
4581 base_table_args,
4582 )
4582 )
4583
4583
4584 schedule_types = ['crontab', 'timedelta', 'integer']
4584 schedule_types = ['crontab', 'timedelta', 'integer']
4585 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4585 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4586
4586
4587 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4587 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4588 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4588 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4589 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4589 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4590
4590
4591 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4591 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4592 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4592 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4593
4593
4594 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4594 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4595 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4595 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4596
4596
4597 # task
4597 # task
4598 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4598 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4599 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4599 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4600 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4600 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4601 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4601 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4602
4602
4603 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4603 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4604 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4604 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4605
4605
4606 @hybrid_property
4606 @hybrid_property
4607 def schedule_type(self):
4607 def schedule_type(self):
4608 return self._schedule_type
4608 return self._schedule_type
4609
4609
4610 @schedule_type.setter
4610 @schedule_type.setter
4611 def schedule_type(self, val):
4611 def schedule_type(self, val):
4612 if val not in self.schedule_types:
4612 if val not in self.schedule_types:
4613 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4613 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4614 val, self.schedule_type))
4614 val, self.schedule_type))
4615
4615
4616 self._schedule_type = val
4616 self._schedule_type = val
4617
4617
4618 @classmethod
4618 @classmethod
4619 def get_uid(cls, obj):
4619 def get_uid(cls, obj):
4620 args = obj.task_args
4620 args = obj.task_args
4621 kwargs = obj.task_kwargs
4621 kwargs = obj.task_kwargs
4622 if isinstance(args, JsonRaw):
4622 if isinstance(args, JsonRaw):
4623 try:
4623 try:
4624 args = json.loads(args)
4624 args = json.loads(args)
4625 except ValueError:
4625 except ValueError:
4626 args = tuple()
4626 args = tuple()
4627
4627
4628 if isinstance(kwargs, JsonRaw):
4628 if isinstance(kwargs, JsonRaw):
4629 try:
4629 try:
4630 kwargs = json.loads(kwargs)
4630 kwargs = json.loads(kwargs)
4631 except ValueError:
4631 except ValueError:
4632 kwargs = dict()
4632 kwargs = dict()
4633
4633
4634 dot_notation = obj.task_dot_notation
4634 dot_notation = obj.task_dot_notation
4635 val = '.'.join(map(safe_str, [
4635 val = '.'.join(map(safe_str, [
4636 sorted(dot_notation), args, sorted(kwargs.items())]))
4636 sorted(dot_notation), args, sorted(kwargs.items())]))
4637 return hashlib.sha1(val).hexdigest()
4637 return hashlib.sha1(val).hexdigest()
4638
4638
4639 @classmethod
4639 @classmethod
4640 def get_by_schedule_name(cls, schedule_name):
4640 def get_by_schedule_name(cls, schedule_name):
4641 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4641 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4642
4642
4643 @classmethod
4643 @classmethod
4644 def get_by_schedule_id(cls, schedule_id):
4644 def get_by_schedule_id(cls, schedule_id):
4645 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4645 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4646
4646
4647 @property
4647 @property
4648 def task(self):
4648 def task(self):
4649 return self.task_dot_notation
4649 return self.task_dot_notation
4650
4650
4651 @property
4651 @property
4652 def schedule(self):
4652 def schedule(self):
4653 from rhodecode.lib.celerylib.utils import raw_2_schedule
4653 from rhodecode.lib.celerylib.utils import raw_2_schedule
4654 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4654 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4655 return schedule
4655 return schedule
4656
4656
4657 @property
4657 @property
4658 def args(self):
4658 def args(self):
4659 try:
4659 try:
4660 return list(self.task_args or [])
4660 return list(self.task_args or [])
4661 except ValueError:
4661 except ValueError:
4662 return list()
4662 return list()
4663
4663
4664 @property
4664 @property
4665 def kwargs(self):
4665 def kwargs(self):
4666 try:
4666 try:
4667 return dict(self.task_kwargs or {})
4667 return dict(self.task_kwargs or {})
4668 except ValueError:
4668 except ValueError:
4669 return dict()
4669 return dict()
4670
4670
4671 def _as_raw(self, val):
4671 def _as_raw(self, val):
4672 if hasattr(val, 'de_coerce'):
4672 if hasattr(val, 'de_coerce'):
4673 val = val.de_coerce()
4673 val = val.de_coerce()
4674 if val:
4674 if val:
4675 val = json.dumps(val)
4675 val = json.dumps(val)
4676
4676
4677 return val
4677 return val
4678
4678
4679 @property
4679 @property
4680 def schedule_definition_raw(self):
4680 def schedule_definition_raw(self):
4681 return self._as_raw(self.schedule_definition)
4681 return self._as_raw(self.schedule_definition)
4682
4682
4683 @property
4683 @property
4684 def args_raw(self):
4684 def args_raw(self):
4685 return self._as_raw(self.task_args)
4685 return self._as_raw(self.task_args)
4686
4686
4687 @property
4687 @property
4688 def kwargs_raw(self):
4688 def kwargs_raw(self):
4689 return self._as_raw(self.task_kwargs)
4689 return self._as_raw(self.task_kwargs)
4690
4690
4691 def __repr__(self):
4691 def __repr__(self):
4692 return '<DB:ScheduleEntry({}:{})>'.format(
4692 return '<DB:ScheduleEntry({}:{})>'.format(
4693 self.schedule_entry_id, self.schedule_name)
4693 self.schedule_entry_id, self.schedule_name)
4694
4694
4695
4695
4696 @event.listens_for(ScheduleEntry, 'before_update')
4696 @event.listens_for(ScheduleEntry, 'before_update')
4697 def update_task_uid(mapper, connection, target):
4697 def update_task_uid(mapper, connection, target):
4698 target.task_uid = ScheduleEntry.get_uid(target)
4698 target.task_uid = ScheduleEntry.get_uid(target)
4699
4699
4700
4700
4701 @event.listens_for(ScheduleEntry, 'before_insert')
4701 @event.listens_for(ScheduleEntry, 'before_insert')
4702 def set_task_uid(mapper, connection, target):
4702 def set_task_uid(mapper, connection, target):
4703 target.task_uid = ScheduleEntry.get_uid(target)
4703 target.task_uid = ScheduleEntry.get_uid(target)
4704
4704
4705
4705
4706 class _BaseBranchPerms(BaseModel):
4706 class _BaseBranchPerms(BaseModel):
4707 @classmethod
4707 @classmethod
4708 def compute_hash(cls, value):
4708 def compute_hash(cls, value):
4709 return sha1_safe(value)
4709 return sha1_safe(value)
4710
4710
4711 @hybrid_property
4711 @hybrid_property
4712 def branch_pattern(self):
4712 def branch_pattern(self):
4713 return self._branch_pattern or '*'
4713 return self._branch_pattern or '*'
4714
4714
4715 @hybrid_property
4715 @hybrid_property
4716 def branch_hash(self):
4716 def branch_hash(self):
4717 return self._branch_hash
4717 return self._branch_hash
4718
4718
4719 def _validate_glob(self, value):
4719 def _validate_glob(self, value):
4720 re.compile('^' + glob2re(value) + '$')
4720 re.compile('^' + glob2re(value) + '$')
4721
4721
4722 @branch_pattern.setter
4722 @branch_pattern.setter
4723 def branch_pattern(self, value):
4723 def branch_pattern(self, value):
4724 self._validate_glob(value)
4724 self._validate_glob(value)
4725 self._branch_pattern = value or '*'
4725 self._branch_pattern = value or '*'
4726 # set the Hash when setting the branch pattern
4726 # set the Hash when setting the branch pattern
4727 self._branch_hash = self.compute_hash(self._branch_pattern)
4727 self._branch_hash = self.compute_hash(self._branch_pattern)
4728
4728
4729 def matches(self, branch):
4729 def matches(self, branch):
4730 """
4730 """
4731 Check if this the branch matches entry
4731 Check if this the branch matches entry
4732
4732
4733 :param branch: branch name for the commit
4733 :param branch: branch name for the commit
4734 """
4734 """
4735
4735
4736 branch = branch or ''
4736 branch = branch or ''
4737
4737
4738 branch_matches = True
4738 branch_matches = True
4739 if branch:
4739 if branch:
4740 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4740 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4741 branch_matches = bool(branch_regex.search(branch))
4741 branch_matches = bool(branch_regex.search(branch))
4742
4742
4743 return branch_matches
4743 return branch_matches
4744
4744
4745
4745
4746 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4746 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4747 __tablename__ = 'user_to_repo_branch_permissions'
4747 __tablename__ = 'user_to_repo_branch_permissions'
4748 __table_args__ = (
4748 __table_args__ = (
4749 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4749 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4750 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4750 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4751 )
4751 )
4752
4752
4753 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4753 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4754
4754
4755 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4755 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4756 repo = relationship('Repository', backref='user_branch_perms')
4756 repo = relationship('Repository', backref='user_branch_perms')
4757
4757
4758 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4758 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4759 permission = relationship('Permission')
4759 permission = relationship('Permission')
4760
4760
4761 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4761 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4762 user_repo_to_perm = relationship('UserRepoToPerm')
4762 user_repo_to_perm = relationship('UserRepoToPerm')
4763
4763
4764 rule_order = Column('rule_order', Integer(), nullable=False)
4764 rule_order = Column('rule_order', Integer(), nullable=False)
4765 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4765 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4766 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4766 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4767
4767
4768 def __unicode__(self):
4768 def __unicode__(self):
4769 return u'<UserBranchPermission(%s => %r)>' % (
4769 return u'<UserBranchPermission(%s => %r)>' % (
4770 self.user_repo_to_perm, self.branch_pattern)
4770 self.user_repo_to_perm, self.branch_pattern)
4771
4771
4772
4772
4773 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4773 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4774 __tablename__ = 'user_group_to_repo_branch_permissions'
4774 __tablename__ = 'user_group_to_repo_branch_permissions'
4775 __table_args__ = (
4775 __table_args__ = (
4776 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4776 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4777 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4777 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4778 )
4778 )
4779
4779
4780 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4780 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4781
4781
4782 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4782 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4783 repo = relationship('Repository', backref='user_group_branch_perms')
4783 repo = relationship('Repository', backref='user_group_branch_perms')
4784
4784
4785 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4785 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4786 permission = relationship('Permission')
4786 permission = relationship('Permission')
4787
4787
4788 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
4788 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
4789 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4789 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
4790
4790
4791 rule_order = Column('rule_order', Integer(), nullable=False)
4791 rule_order = Column('rule_order', Integer(), nullable=False)
4792 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4792 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4793 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4793 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4794
4794
4795 def __unicode__(self):
4795 def __unicode__(self):
4796 return u'<UserBranchPermission(%s => %r)>' % (
4796 return u'<UserBranchPermission(%s => %r)>' % (
4797 self.user_group_repo_to_perm, self.branch_pattern)
4797 self.user_group_repo_to_perm, self.branch_pattern)
4798
4798
4799
4799
4800 class UserBookmark(Base, BaseModel):
4800 class UserBookmark(Base, BaseModel):
4801 __tablename__ = 'user_bookmarks'
4801 __tablename__ = 'user_bookmarks'
4802 __table_args__ = (
4802 __table_args__ = (
4803 UniqueConstraint('user_id', 'bookmark_repo_id'),
4803 UniqueConstraint('user_id', 'bookmark_repo_id'),
4804 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
4804 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
4805 UniqueConstraint('user_id', 'bookmark_position'),
4805 UniqueConstraint('user_id', 'bookmark_position'),
4806 base_table_args
4806 base_table_args
4807 )
4807 )
4808
4808
4809 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
4809 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
4810 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
4810 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
4811 position = Column("bookmark_position", Integer(), nullable=False)
4811 position = Column("bookmark_position", Integer(), nullable=False)
4812 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
4812 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
4813 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
4813 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
4814 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4814 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4815
4815
4816 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
4816 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
4817 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
4817 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
4818
4818
4819 user = relationship("User")
4819 user = relationship("User")
4820
4820
4821 repository = relationship("Repository")
4821 repository = relationship("Repository")
4822 repository_group = relationship("RepoGroup")
4822 repository_group = relationship("RepoGroup")
4823
4823
4824 @classmethod
4824 @classmethod
4825 def get_by_position_for_user(cls, position, user_id):
4825 def get_by_position_for_user(cls, position, user_id):
4826 return cls.query() \
4826 return cls.query() \
4827 .filter(UserBookmark.user_id == user_id) \
4827 .filter(UserBookmark.user_id == user_id) \
4828 .filter(UserBookmark.position == position).scalar()
4828 .filter(UserBookmark.position == position).scalar()
4829
4829
4830 @classmethod
4830 @classmethod
4831 def get_bookmarks_for_user(cls, user_id):
4831 def get_bookmarks_for_user(cls, user_id):
4832 return cls.query() \
4832 return cls.query() \
4833 .filter(UserBookmark.user_id == user_id) \
4833 .filter(UserBookmark.user_id == user_id) \
4834 .options(joinedload(UserBookmark.repository)) \
4834 .options(joinedload(UserBookmark.repository)) \
4835 .options(joinedload(UserBookmark.repository_group)) \
4835 .options(joinedload(UserBookmark.repository_group)) \
4836 .order_by(UserBookmark.position.asc()) \
4836 .order_by(UserBookmark.position.asc()) \
4837 .all()
4837 .all()
4838
4838
4839 def __unicode__(self):
4839 def __unicode__(self):
4840 return u'<UserBookmark(%d @ %r)>' % (self.position, self.redirect_url)
4840 return u'<UserBookmark(%d @ %r)>' % (self.position, self.redirect_url)
4841
4841
4842
4842
4843 class FileStore(Base, BaseModel):
4843 class FileStore(Base, BaseModel):
4844 __tablename__ = 'file_store'
4844 __tablename__ = 'file_store'
4845 __table_args__ = (
4845 __table_args__ = (
4846 base_table_args
4846 base_table_args
4847 )
4847 )
4848
4848
4849 file_store_id = Column('file_store_id', Integer(), primary_key=True)
4849 file_store_id = Column('file_store_id', Integer(), primary_key=True)
4850 file_uid = Column('file_uid', String(1024), nullable=False)
4850 file_uid = Column('file_uid', String(1024), nullable=False)
4851 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
4851 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
4852 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
4852 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
4853 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
4853 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
4854
4854
4855 # sha256 hash
4855 # sha256 hash
4856 file_hash = Column('file_hash', String(512), nullable=False)
4856 file_hash = Column('file_hash', String(512), nullable=False)
4857 file_size = Column('file_size', Integer(), nullable=False)
4857 file_size = Column('file_size', Integer(), nullable=False)
4858
4858
4859 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4859 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4860 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
4860 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
4861 accessed_count = Column('accessed_count', Integer(), default=0)
4861 accessed_count = Column('accessed_count', Integer(), default=0)
4862
4862
4863 enabled = Column('enabled', Boolean(), nullable=False, default=True)
4863 enabled = Column('enabled', Boolean(), nullable=False, default=True)
4864
4864
4865 # if repo/repo_group reference is set, check for permissions
4865 # if repo/repo_group reference is set, check for permissions
4866 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
4866 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
4867
4867
4868 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
4868 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
4869 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
4869 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
4870
4870
4871 # scope limited to user, which requester have access to
4871 # scope limited to user, which requester have access to
4872 scope_user_id = Column(
4872 scope_user_id = Column(
4873 'scope_user_id', Integer(), ForeignKey('users.user_id'),
4873 'scope_user_id', Integer(), ForeignKey('users.user_id'),
4874 nullable=True, unique=None, default=None)
4874 nullable=True, unique=None, default=None)
4875 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
4875 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
4876
4876
4877 # scope limited to user group, which requester have access to
4877 # scope limited to user group, which requester have access to
4878 scope_user_group_id = Column(
4878 scope_user_group_id = Column(
4879 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
4879 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
4880 nullable=True, unique=None, default=None)
4880 nullable=True, unique=None, default=None)
4881 user_group = relationship('UserGroup', lazy='joined')
4881 user_group = relationship('UserGroup', lazy='joined')
4882
4882
4883 # scope limited to repo, which requester have access to
4883 # scope limited to repo, which requester have access to
4884 scope_repo_id = Column(
4884 scope_repo_id = Column(
4885 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4885 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
4886 nullable=True, unique=None, default=None)
4886 nullable=True, unique=None, default=None)
4887 repo = relationship('Repository', lazy='joined')
4887 repo = relationship('Repository', lazy='joined')
4888
4888
4889 # scope limited to repo group, which requester have access to
4889 # scope limited to repo group, which requester have access to
4890 scope_repo_group_id = Column(
4890 scope_repo_group_id = Column(
4891 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
4891 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
4892 nullable=True, unique=None, default=None)
4892 nullable=True, unique=None, default=None)
4893 repo_group = relationship('RepoGroup', lazy='joined')
4893 repo_group = relationship('RepoGroup', lazy='joined')
4894
4894
4895 def __repr__(self):
4895 def __repr__(self):
4896 return '<FileStore({})>'.format(self.file_store_id)
4896 return '<FileStore({})>'.format(self.file_store_id)
4897
4897
4898
4898
4899 class DbMigrateVersion(Base, BaseModel):
4899 class DbMigrateVersion(Base, BaseModel):
4900 __tablename__ = 'db_migrate_version'
4900 __tablename__ = 'db_migrate_version'
4901 __table_args__ = (
4901 __table_args__ = (
4902 base_table_args,
4902 base_table_args,
4903 )
4903 )
4904
4904
4905 repository_id = Column('repository_id', String(250), primary_key=True)
4905 repository_id = Column('repository_id', String(250), primary_key=True)
4906 repository_path = Column('repository_path', Text)
4906 repository_path = Column('repository_path', Text)
4907 version = Column('version', Integer)
4907 version = Column('version', Integer)
4908
4908
4909 @classmethod
4909 @classmethod
4910 def set_version(cls, version):
4910 def set_version(cls, version):
4911 """
4911 """
4912 Helper for forcing a different version, usually for debugging purposes via ishell.
4912 Helper for forcing a different version, usually for debugging purposes via ishell.
4913 """
4913 """
4914 ver = DbMigrateVersion.query().first()
4914 ver = DbMigrateVersion.query().first()
4915 ver.version = version
4915 ver.version = version
4916 Session().commit()
4916 Session().commit()
4917
4917
4918
4918
4919 class DbSession(Base, BaseModel):
4919 class DbSession(Base, BaseModel):
4920 __tablename__ = 'db_session'
4920 __tablename__ = 'db_session'
4921 __table_args__ = (
4921 __table_args__ = (
4922 base_table_args,
4922 base_table_args,
4923 )
4923 )
4924
4924
4925 def __repr__(self):
4925 def __repr__(self):
4926 return '<DB:DbSession({})>'.format(self.id)
4926 return '<DB:DbSession({})>'.format(self.id)
4927
4927
4928 id = Column('id', Integer())
4928 id = Column('id', Integer())
4929 namespace = Column('namespace', String(255), primary_key=True)
4929 namespace = Column('namespace', String(255), primary_key=True)
4930 accessed = Column('accessed', DateTime, nullable=False)
4930 accessed = Column('accessed', DateTime, nullable=False)
4931 created = Column('created', DateTime, nullable=False)
4931 created = Column('created', DateTime, nullable=False)
4932 data = Column('data', PickleType, nullable=False)
4932 data = Column('data', PickleType, nullable=False)
@@ -1,1254 +1,1254 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2019 RhodeCode GmbH
3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21
21
22 """
22 """
23 Set of diffing helpers, previously part of vcs
23 Set of diffing helpers, previously part of vcs
24 """
24 """
25
25
26 import os
26 import os
27 import re
27 import re
28 import bz2
28 import bz2
29 import time
29 import time
30
30
31 import collections
31 import collections
32 import difflib
32 import difflib
33 import logging
33 import logging
34 import cPickle as pickle
34 import cPickle as pickle
35 from itertools import tee, imap
35 from itertools import tee, imap
36
36
37 from rhodecode.lib.vcs.exceptions import VCSError
37 from rhodecode.lib.vcs.exceptions import VCSError
38 from rhodecode.lib.vcs.nodes import FileNode, SubModuleNode
38 from rhodecode.lib.vcs.nodes import FileNode, SubModuleNode
39 from rhodecode.lib.utils2 import safe_unicode, safe_str
39 from rhodecode.lib.utils2 import safe_unicode, safe_str
40
40
41 log = logging.getLogger(__name__)
41 log = logging.getLogger(__name__)
42
42
43 # define max context, a file with more than this numbers of lines is unusable
43 # define max context, a file with more than this numbers of lines is unusable
44 # in browser anyway
44 # in browser anyway
45 MAX_CONTEXT = 20 * 1024
45 MAX_CONTEXT = 20 * 1024
46 DEFAULT_CONTEXT = 3
46 DEFAULT_CONTEXT = 3
47
47
48
48
49 def get_diff_context(request):
49 def get_diff_context(request):
50 return MAX_CONTEXT if request.GET.get('fullcontext', '') == '1' else DEFAULT_CONTEXT
50 return MAX_CONTEXT if request.GET.get('fullcontext', '') == '1' else DEFAULT_CONTEXT
51
51
52
52
53 def get_diff_whitespace_flag(request):
53 def get_diff_whitespace_flag(request):
54 return request.GET.get('ignorews', '') == '1'
54 return request.GET.get('ignorews', '') == '1'
55
55
56
56
57 class OPS(object):
57 class OPS(object):
58 ADD = 'A'
58 ADD = 'A'
59 MOD = 'M'
59 MOD = 'M'
60 DEL = 'D'
60 DEL = 'D'
61
61
62
62
63 def get_gitdiff(filenode_old, filenode_new, ignore_whitespace=True, context=3):
63 def get_gitdiff(filenode_old, filenode_new, ignore_whitespace=True, context=3):
64 """
64 """
65 Returns git style diff between given ``filenode_old`` and ``filenode_new``.
65 Returns git style diff between given ``filenode_old`` and ``filenode_new``.
66
66
67 :param ignore_whitespace: ignore whitespaces in diff
67 :param ignore_whitespace: ignore whitespaces in diff
68 """
68 """
69 # make sure we pass in default context
69 # make sure we pass in default context
70 context = context or 3
70 context = context or 3
71 # protect against IntOverflow when passing HUGE context
71 # protect against IntOverflow when passing HUGE context
72 if context > MAX_CONTEXT:
72 if context > MAX_CONTEXT:
73 context = MAX_CONTEXT
73 context = MAX_CONTEXT
74
74
75 submodules = filter(lambda o: isinstance(o, SubModuleNode),
75 submodules = filter(lambda o: isinstance(o, SubModuleNode),
76 [filenode_new, filenode_old])
76 [filenode_new, filenode_old])
77 if submodules:
77 if submodules:
78 return ''
78 return ''
79
79
80 for filenode in (filenode_old, filenode_new):
80 for filenode in (filenode_old, filenode_new):
81 if not isinstance(filenode, FileNode):
81 if not isinstance(filenode, FileNode):
82 raise VCSError(
82 raise VCSError(
83 "Given object should be FileNode object, not %s"
83 "Given object should be FileNode object, not %s"
84 % filenode.__class__)
84 % filenode.__class__)
85
85
86 repo = filenode_new.commit.repository
86 repo = filenode_new.commit.repository
87 old_commit = filenode_old.commit or repo.EMPTY_COMMIT
87 old_commit = filenode_old.commit or repo.EMPTY_COMMIT
88 new_commit = filenode_new.commit
88 new_commit = filenode_new.commit
89
89
90 vcs_gitdiff = repo.get_diff(
90 vcs_gitdiff = repo.get_diff(
91 old_commit, new_commit, filenode_new.path,
91 old_commit, new_commit, filenode_new.path,
92 ignore_whitespace, context, path1=filenode_old.path)
92 ignore_whitespace, context, path1=filenode_old.path)
93 return vcs_gitdiff
93 return vcs_gitdiff
94
94
95 NEW_FILENODE = 1
95 NEW_FILENODE = 1
96 DEL_FILENODE = 2
96 DEL_FILENODE = 2
97 MOD_FILENODE = 3
97 MOD_FILENODE = 3
98 RENAMED_FILENODE = 4
98 RENAMED_FILENODE = 4
99 COPIED_FILENODE = 5
99 COPIED_FILENODE = 5
100 CHMOD_FILENODE = 6
100 CHMOD_FILENODE = 6
101 BIN_FILENODE = 7
101 BIN_FILENODE = 7
102
102
103
103
104 class LimitedDiffContainer(object):
104 class LimitedDiffContainer(object):
105
105
106 def __init__(self, diff_limit, cur_diff_size, diff):
106 def __init__(self, diff_limit, cur_diff_size, diff):
107 self.diff = diff
107 self.diff = diff
108 self.diff_limit = diff_limit
108 self.diff_limit = diff_limit
109 self.cur_diff_size = cur_diff_size
109 self.cur_diff_size = cur_diff_size
110
110
111 def __getitem__(self, key):
111 def __getitem__(self, key):
112 return self.diff.__getitem__(key)
112 return self.diff.__getitem__(key)
113
113
114 def __iter__(self):
114 def __iter__(self):
115 for l in self.diff:
115 for l in self.diff:
116 yield l
116 yield l
117
117
118
118
119 class Action(object):
119 class Action(object):
120 """
120 """
121 Contains constants for the action value of the lines in a parsed diff.
121 Contains constants for the action value of the lines in a parsed diff.
122 """
122 """
123
123
124 ADD = 'add'
124 ADD = 'add'
125 DELETE = 'del'
125 DELETE = 'del'
126 UNMODIFIED = 'unmod'
126 UNMODIFIED = 'unmod'
127
127
128 CONTEXT = 'context'
128 CONTEXT = 'context'
129 OLD_NO_NL = 'old-no-nl'
129 OLD_NO_NL = 'old-no-nl'
130 NEW_NO_NL = 'new-no-nl'
130 NEW_NO_NL = 'new-no-nl'
131
131
132
132
133 class DiffProcessor(object):
133 class DiffProcessor(object):
134 """
134 """
135 Give it a unified or git diff and it returns a list of the files that were
135 Give it a unified or git diff and it returns a list of the files that were
136 mentioned in the diff together with a dict of meta information that
136 mentioned in the diff together with a dict of meta information that
137 can be used to render it in a HTML template.
137 can be used to render it in a HTML template.
138
138
139 .. note:: Unicode handling
139 .. note:: Unicode handling
140
140
141 The original diffs are a byte sequence and can contain filenames
141 The original diffs are a byte sequence and can contain filenames
142 in mixed encodings. This class generally returns `unicode` objects
142 in mixed encodings. This class generally returns `unicode` objects
143 since the result is intended for presentation to the user.
143 since the result is intended for presentation to the user.
144
144
145 """
145 """
146 _chunk_re = re.compile(r'^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)')
146 _chunk_re = re.compile(r'^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)')
147 _newline_marker = re.compile(r'^\\ No newline at end of file')
147 _newline_marker = re.compile(r'^\\ No newline at end of file')
148
148
149 # used for inline highlighter word split
149 # used for inline highlighter word split
150 _token_re = re.compile(r'()(&gt;|&lt;|&amp;|\W+?)')
150 _token_re = re.compile(r'()(&gt;|&lt;|&amp;|\W+?)')
151
151
152 # collapse ranges of commits over given number
152 # collapse ranges of commits over given number
153 _collapse_commits_over = 5
153 _collapse_commits_over = 5
154
154
155 def __init__(self, diff, format='gitdiff', diff_limit=None,
155 def __init__(self, diff, format='gitdiff', diff_limit=None,
156 file_limit=None, show_full_diff=True):
156 file_limit=None, show_full_diff=True):
157 """
157 """
158 :param diff: A `Diff` object representing a diff from a vcs backend
158 :param diff: A `Diff` object representing a diff from a vcs backend
159 :param format: format of diff passed, `udiff` or `gitdiff`
159 :param format: format of diff passed, `udiff` or `gitdiff`
160 :param diff_limit: define the size of diff that is considered "big"
160 :param diff_limit: define the size of diff that is considered "big"
161 based on that parameter cut off will be triggered, set to None
161 based on that parameter cut off will be triggered, set to None
162 to show full diff
162 to show full diff
163 """
163 """
164 self._diff = diff
164 self._diff = diff
165 self._format = format
165 self._format = format
166 self.adds = 0
166 self.adds = 0
167 self.removes = 0
167 self.removes = 0
168 # calculate diff size
168 # calculate diff size
169 self.diff_limit = diff_limit
169 self.diff_limit = diff_limit
170 self.file_limit = file_limit
170 self.file_limit = file_limit
171 self.show_full_diff = show_full_diff
171 self.show_full_diff = show_full_diff
172 self.cur_diff_size = 0
172 self.cur_diff_size = 0
173 self.parsed = False
173 self.parsed = False
174 self.parsed_diff = []
174 self.parsed_diff = []
175
175
176 log.debug('Initialized DiffProcessor with %s mode', format)
176 log.debug('Initialized DiffProcessor with %s mode', format)
177 if format == 'gitdiff':
177 if format == 'gitdiff':
178 self.differ = self._highlight_line_difflib
178 self.differ = self._highlight_line_difflib
179 self._parser = self._parse_gitdiff
179 self._parser = self._parse_gitdiff
180 else:
180 else:
181 self.differ = self._highlight_line_udiff
181 self.differ = self._highlight_line_udiff
182 self._parser = self._new_parse_gitdiff
182 self._parser = self._new_parse_gitdiff
183
183
184 def _copy_iterator(self):
184 def _copy_iterator(self):
185 """
185 """
186 make a fresh copy of generator, we should not iterate thru
186 make a fresh copy of generator, we should not iterate thru
187 an original as it's needed for repeating operations on
187 an original as it's needed for repeating operations on
188 this instance of DiffProcessor
188 this instance of DiffProcessor
189 """
189 """
190 self.__udiff, iterator_copy = tee(self.__udiff)
190 self.__udiff, iterator_copy = tee(self.__udiff)
191 return iterator_copy
191 return iterator_copy
192
192
193 def _escaper(self, string):
193 def _escaper(self, string):
194 """
194 """
195 Escaper for diff escapes special chars and checks the diff limit
195 Escaper for diff escapes special chars and checks the diff limit
196
196
197 :param string:
197 :param string:
198 """
198 """
199 self.cur_diff_size += len(string)
199 self.cur_diff_size += len(string)
200
200
201 if not self.show_full_diff and (self.cur_diff_size > self.diff_limit):
201 if not self.show_full_diff and (self.cur_diff_size > self.diff_limit):
202 raise DiffLimitExceeded('Diff Limit Exceeded')
202 raise DiffLimitExceeded('Diff Limit Exceeded')
203
203
204 return string \
204 return string \
205 .replace('&', '&amp;')\
205 .replace('&', '&amp;')\
206 .replace('<', '&lt;')\
206 .replace('<', '&lt;')\
207 .replace('>', '&gt;')
207 .replace('>', '&gt;')
208
208
209 def _line_counter(self, l):
209 def _line_counter(self, l):
210 """
210 """
211 Checks each line and bumps total adds/removes for this diff
211 Checks each line and bumps total adds/removes for this diff
212
212
213 :param l:
213 :param l:
214 """
214 """
215 if l.startswith('+') and not l.startswith('+++'):
215 if l.startswith('+') and not l.startswith('+++'):
216 self.adds += 1
216 self.adds += 1
217 elif l.startswith('-') and not l.startswith('---'):
217 elif l.startswith('-') and not l.startswith('---'):
218 self.removes += 1
218 self.removes += 1
219 return safe_unicode(l)
219 return safe_unicode(l)
220
220
221 def _highlight_line_difflib(self, line, next_):
221 def _highlight_line_difflib(self, line, next_):
222 """
222 """
223 Highlight inline changes in both lines.
223 Highlight inline changes in both lines.
224 """
224 """
225
225
226 if line['action'] == Action.DELETE:
226 if line['action'] == Action.DELETE:
227 old, new = line, next_
227 old, new = line, next_
228 else:
228 else:
229 old, new = next_, line
229 old, new = next_, line
230
230
231 oldwords = self._token_re.split(old['line'])
231 oldwords = self._token_re.split(old['line'])
232 newwords = self._token_re.split(new['line'])
232 newwords = self._token_re.split(new['line'])
233 sequence = difflib.SequenceMatcher(None, oldwords, newwords)
233 sequence = difflib.SequenceMatcher(None, oldwords, newwords)
234
234
235 oldfragments, newfragments = [], []
235 oldfragments, newfragments = [], []
236 for tag, i1, i2, j1, j2 in sequence.get_opcodes():
236 for tag, i1, i2, j1, j2 in sequence.get_opcodes():
237 oldfrag = ''.join(oldwords[i1:i2])
237 oldfrag = ''.join(oldwords[i1:i2])
238 newfrag = ''.join(newwords[j1:j2])
238 newfrag = ''.join(newwords[j1:j2])
239 if tag != 'equal':
239 if tag != 'equal':
240 if oldfrag:
240 if oldfrag:
241 oldfrag = '<del>%s</del>' % oldfrag
241 oldfrag = '<del>%s</del>' % oldfrag
242 if newfrag:
242 if newfrag:
243 newfrag = '<ins>%s</ins>' % newfrag
243 newfrag = '<ins>%s</ins>' % newfrag
244 oldfragments.append(oldfrag)
244 oldfragments.append(oldfrag)
245 newfragments.append(newfrag)
245 newfragments.append(newfrag)
246
246
247 old['line'] = "".join(oldfragments)
247 old['line'] = "".join(oldfragments)
248 new['line'] = "".join(newfragments)
248 new['line'] = "".join(newfragments)
249
249
250 def _highlight_line_udiff(self, line, next_):
250 def _highlight_line_udiff(self, line, next_):
251 """
251 """
252 Highlight inline changes in both lines.
252 Highlight inline changes in both lines.
253 """
253 """
254 start = 0
254 start = 0
255 limit = min(len(line['line']), len(next_['line']))
255 limit = min(len(line['line']), len(next_['line']))
256 while start < limit and line['line'][start] == next_['line'][start]:
256 while start < limit and line['line'][start] == next_['line'][start]:
257 start += 1
257 start += 1
258 end = -1
258 end = -1
259 limit -= start
259 limit -= start
260 while -end <= limit and line['line'][end] == next_['line'][end]:
260 while -end <= limit and line['line'][end] == next_['line'][end]:
261 end -= 1
261 end -= 1
262 end += 1
262 end += 1
263 if start or end:
263 if start or end:
264 def do(l):
264 def do(l):
265 last = end + len(l['line'])
265 last = end + len(l['line'])
266 if l['action'] == Action.ADD:
266 if l['action'] == Action.ADD:
267 tag = 'ins'
267 tag = 'ins'
268 else:
268 else:
269 tag = 'del'
269 tag = 'del'
270 l['line'] = '%s<%s>%s</%s>%s' % (
270 l['line'] = '%s<%s>%s</%s>%s' % (
271 l['line'][:start],
271 l['line'][:start],
272 tag,
272 tag,
273 l['line'][start:last],
273 l['line'][start:last],
274 tag,
274 tag,
275 l['line'][last:]
275 l['line'][last:]
276 )
276 )
277 do(line)
277 do(line)
278 do(next_)
278 do(next_)
279
279
280 def _clean_line(self, line, command):
280 def _clean_line(self, line, command):
281 if command in ['+', '-', ' ']:
281 if command in ['+', '-', ' ']:
282 # only modify the line if it's actually a diff thing
282 # only modify the line if it's actually a diff thing
283 line = line[1:]
283 line = line[1:]
284 return line
284 return line
285
285
286 def _parse_gitdiff(self, inline_diff=True):
286 def _parse_gitdiff(self, inline_diff=True):
287 _files = []
287 _files = []
288 diff_container = lambda arg: arg
288 diff_container = lambda arg: arg
289
289
290 for chunk in self._diff.chunks():
290 for chunk in self._diff.chunks():
291 head = chunk.header
291 head = chunk.header
292
292
293 diff = imap(self._escaper, self.diff_splitter(chunk.diff))
293 diff = imap(self._escaper, self.diff_splitter(chunk.diff))
294 raw_diff = chunk.raw
294 raw_diff = chunk.raw
295 limited_diff = False
295 limited_diff = False
296 exceeds_limit = False
296 exceeds_limit = False
297
297
298 op = None
298 op = None
299 stats = {
299 stats = {
300 'added': 0,
300 'added': 0,
301 'deleted': 0,
301 'deleted': 0,
302 'binary': False,
302 'binary': False,
303 'ops': {},
303 'ops': {},
304 }
304 }
305
305
306 if head['deleted_file_mode']:
306 if head['deleted_file_mode']:
307 op = OPS.DEL
307 op = OPS.DEL
308 stats['binary'] = True
308 stats['binary'] = True
309 stats['ops'][DEL_FILENODE] = 'deleted file'
309 stats['ops'][DEL_FILENODE] = 'deleted file'
310
310
311 elif head['new_file_mode']:
311 elif head['new_file_mode']:
312 op = OPS.ADD
312 op = OPS.ADD
313 stats['binary'] = True
313 stats['binary'] = True
314 stats['ops'][NEW_FILENODE] = 'new file %s' % head['new_file_mode']
314 stats['ops'][NEW_FILENODE] = 'new file %s' % head['new_file_mode']
315 else: # modify operation, can be copy, rename or chmod
315 else: # modify operation, can be copy, rename or chmod
316
316
317 # CHMOD
317 # CHMOD
318 if head['new_mode'] and head['old_mode']:
318 if head['new_mode'] and head['old_mode']:
319 op = OPS.MOD
319 op = OPS.MOD
320 stats['binary'] = True
320 stats['binary'] = True
321 stats['ops'][CHMOD_FILENODE] = (
321 stats['ops'][CHMOD_FILENODE] = (
322 'modified file chmod %s => %s' % (
322 'modified file chmod %s => %s' % (
323 head['old_mode'], head['new_mode']))
323 head['old_mode'], head['new_mode']))
324 # RENAME
324 # RENAME
325 if head['rename_from'] != head['rename_to']:
325 if head['rename_from'] != head['rename_to']:
326 op = OPS.MOD
326 op = OPS.MOD
327 stats['binary'] = True
327 stats['binary'] = True
328 stats['ops'][RENAMED_FILENODE] = (
328 stats['ops'][RENAMED_FILENODE] = (
329 'file renamed from %s to %s' % (
329 'file renamed from %s to %s' % (
330 head['rename_from'], head['rename_to']))
330 head['rename_from'], head['rename_to']))
331 # COPY
331 # COPY
332 if head.get('copy_from') and head.get('copy_to'):
332 if head.get('copy_from') and head.get('copy_to'):
333 op = OPS.MOD
333 op = OPS.MOD
334 stats['binary'] = True
334 stats['binary'] = True
335 stats['ops'][COPIED_FILENODE] = (
335 stats['ops'][COPIED_FILENODE] = (
336 'file copied from %s to %s' % (
336 'file copied from %s to %s' % (
337 head['copy_from'], head['copy_to']))
337 head['copy_from'], head['copy_to']))
338
338
339 # If our new parsed headers didn't match anything fallback to
339 # If our new parsed headers didn't match anything fallback to
340 # old style detection
340 # old style detection
341 if op is None:
341 if op is None:
342 if not head['a_file'] and head['b_file']:
342 if not head['a_file'] and head['b_file']:
343 op = OPS.ADD
343 op = OPS.ADD
344 stats['binary'] = True
344 stats['binary'] = True
345 stats['ops'][NEW_FILENODE] = 'new file'
345 stats['ops'][NEW_FILENODE] = 'new file'
346
346
347 elif head['a_file'] and not head['b_file']:
347 elif head['a_file'] and not head['b_file']:
348 op = OPS.DEL
348 op = OPS.DEL
349 stats['binary'] = True
349 stats['binary'] = True
350 stats['ops'][DEL_FILENODE] = 'deleted file'
350 stats['ops'][DEL_FILENODE] = 'deleted file'
351
351
352 # it's not ADD not DELETE
352 # it's not ADD not DELETE
353 if op is None:
353 if op is None:
354 op = OPS.MOD
354 op = OPS.MOD
355 stats['binary'] = True
355 stats['binary'] = True
356 stats['ops'][MOD_FILENODE] = 'modified file'
356 stats['ops'][MOD_FILENODE] = 'modified file'
357
357
358 # a real non-binary diff
358 # a real non-binary diff
359 if head['a_file'] or head['b_file']:
359 if head['a_file'] or head['b_file']:
360 try:
360 try:
361 raw_diff, chunks, _stats = self._parse_lines(diff)
361 raw_diff, chunks, _stats = self._parse_lines(diff)
362 stats['binary'] = False
362 stats['binary'] = False
363 stats['added'] = _stats[0]
363 stats['added'] = _stats[0]
364 stats['deleted'] = _stats[1]
364 stats['deleted'] = _stats[1]
365 # explicit mark that it's a modified file
365 # explicit mark that it's a modified file
366 if op == OPS.MOD:
366 if op == OPS.MOD:
367 stats['ops'][MOD_FILENODE] = 'modified file'
367 stats['ops'][MOD_FILENODE] = 'modified file'
368 exceeds_limit = len(raw_diff) > self.file_limit
368 exceeds_limit = len(raw_diff) > self.file_limit
369
369
370 # changed from _escaper function so we validate size of
370 # changed from _escaper function so we validate size of
371 # each file instead of the whole diff
371 # each file instead of the whole diff
372 # diff will hide big files but still show small ones
372 # diff will hide big files but still show small ones
373 # from my tests, big files are fairly safe to be parsed
373 # from my tests, big files are fairly safe to be parsed
374 # but the browser is the bottleneck
374 # but the browser is the bottleneck
375 if not self.show_full_diff and exceeds_limit:
375 if not self.show_full_diff and exceeds_limit:
376 raise DiffLimitExceeded('File Limit Exceeded')
376 raise DiffLimitExceeded('File Limit Exceeded')
377
377
378 except DiffLimitExceeded:
378 except DiffLimitExceeded:
379 diff_container = lambda _diff: \
379 diff_container = lambda _diff: \
380 LimitedDiffContainer(
380 LimitedDiffContainer(
381 self.diff_limit, self.cur_diff_size, _diff)
381 self.diff_limit, self.cur_diff_size, _diff)
382
382
383 exceeds_limit = len(raw_diff) > self.file_limit
383 exceeds_limit = len(raw_diff) > self.file_limit
384 limited_diff = True
384 limited_diff = True
385 chunks = []
385 chunks = []
386
386
387 else: # GIT format binary patch, or possibly empty diff
387 else: # GIT format binary patch, or possibly empty diff
388 if head['bin_patch']:
388 if head['bin_patch']:
389 # we have operation already extracted, but we mark simply
389 # we have operation already extracted, but we mark simply
390 # it's a diff we wont show for binary files
390 # it's a diff we wont show for binary files
391 stats['ops'][BIN_FILENODE] = 'binary diff hidden'
391 stats['ops'][BIN_FILENODE] = 'binary diff hidden'
392 chunks = []
392 chunks = []
393
393
394 if chunks and not self.show_full_diff and op == OPS.DEL:
394 if chunks and not self.show_full_diff and op == OPS.DEL:
395 # if not full diff mode show deleted file contents
395 # if not full diff mode show deleted file contents
396 # TODO: anderson: if the view is not too big, there is no way
396 # TODO: anderson: if the view is not too big, there is no way
397 # to see the content of the file
397 # to see the content of the file
398 chunks = []
398 chunks = []
399
399
400 chunks.insert(0, [{
400 chunks.insert(0, [{
401 'old_lineno': '',
401 'old_lineno': '',
402 'new_lineno': '',
402 'new_lineno': '',
403 'action': Action.CONTEXT,
403 'action': Action.CONTEXT,
404 'line': msg,
404 'line': msg,
405 } for _op, msg in stats['ops'].iteritems()
405 } for _op, msg in stats['ops'].iteritems()
406 if _op not in [MOD_FILENODE]])
406 if _op not in [MOD_FILENODE]])
407
407
408 _files.append({
408 _files.append({
409 'filename': safe_unicode(head['b_path']),
409 'filename': safe_unicode(head['b_path']),
410 'old_revision': head['a_blob_id'],
410 'old_revision': head['a_blob_id'],
411 'new_revision': head['b_blob_id'],
411 'new_revision': head['b_blob_id'],
412 'chunks': chunks,
412 'chunks': chunks,
413 'raw_diff': safe_unicode(raw_diff),
413 'raw_diff': safe_unicode(raw_diff),
414 'operation': op,
414 'operation': op,
415 'stats': stats,
415 'stats': stats,
416 'exceeds_limit': exceeds_limit,
416 'exceeds_limit': exceeds_limit,
417 'is_limited_diff': limited_diff,
417 'is_limited_diff': limited_diff,
418 })
418 })
419
419
420 sorter = lambda info: {OPS.ADD: 0, OPS.MOD: 1,
420 sorter = lambda info: {OPS.ADD: 0, OPS.MOD: 1,
421 OPS.DEL: 2}.get(info['operation'])
421 OPS.DEL: 2}.get(info['operation'])
422
422
423 if not inline_diff:
423 if not inline_diff:
424 return diff_container(sorted(_files, key=sorter))
424 return diff_container(sorted(_files, key=sorter))
425
425
426 # highlight inline changes
426 # highlight inline changes
427 for diff_data in _files:
427 for diff_data in _files:
428 for chunk in diff_data['chunks']:
428 for chunk in diff_data['chunks']:
429 lineiter = iter(chunk)
429 lineiter = iter(chunk)
430 try:
430 try:
431 while 1:
431 while 1:
432 line = lineiter.next()
432 line = lineiter.next()
433 if line['action'] not in (
433 if line['action'] not in (
434 Action.UNMODIFIED, Action.CONTEXT):
434 Action.UNMODIFIED, Action.CONTEXT):
435 nextline = lineiter.next()
435 nextline = lineiter.next()
436 if nextline['action'] in ['unmod', 'context'] or \
436 if nextline['action'] in ['unmod', 'context'] or \
437 nextline['action'] == line['action']:
437 nextline['action'] == line['action']:
438 continue
438 continue
439 self.differ(line, nextline)
439 self.differ(line, nextline)
440 except StopIteration:
440 except StopIteration:
441 pass
441 pass
442
442
443 return diff_container(sorted(_files, key=sorter))
443 return diff_container(sorted(_files, key=sorter))
444
444
445 def _check_large_diff(self):
445 def _check_large_diff(self):
446 log.debug('Diff exceeds current diff_limit of %s', self.diff_limit)
446 log.debug('Diff exceeds current diff_limit of %s', self.diff_limit)
447 if not self.show_full_diff and (self.cur_diff_size > self.diff_limit):
447 if not self.show_full_diff and (self.cur_diff_size > self.diff_limit):
448 raise DiffLimitExceeded('Diff Limit `%s` Exceeded', self.diff_limit)
448 raise DiffLimitExceeded('Diff Limit `%s` Exceeded', self.diff_limit)
449
449
450 # FIXME: NEWDIFFS: dan: this replaces _parse_gitdiff
450 # FIXME: NEWDIFFS: dan: this replaces _parse_gitdiff
451 def _new_parse_gitdiff(self, inline_diff=True):
451 def _new_parse_gitdiff(self, inline_diff=True):
452 _files = []
452 _files = []
453
453
454 # this can be overriden later to a LimitedDiffContainer type
454 # this can be overriden later to a LimitedDiffContainer type
455 diff_container = lambda arg: arg
455 diff_container = lambda arg: arg
456
456
457 for chunk in self._diff.chunks():
457 for chunk in self._diff.chunks():
458 head = chunk.header
458 head = chunk.header
459 log.debug('parsing diff %r', head)
459 log.debug('parsing diff %r', head)
460
460
461 raw_diff = chunk.raw
461 raw_diff = chunk.raw
462 limited_diff = False
462 limited_diff = False
463 exceeds_limit = False
463 exceeds_limit = False
464
464
465 op = None
465 op = None
466 stats = {
466 stats = {
467 'added': 0,
467 'added': 0,
468 'deleted': 0,
468 'deleted': 0,
469 'binary': False,
469 'binary': False,
470 'old_mode': None,
470 'old_mode': None,
471 'new_mode': None,
471 'new_mode': None,
472 'ops': {},
472 'ops': {},
473 }
473 }
474 if head['old_mode']:
474 if head['old_mode']:
475 stats['old_mode'] = head['old_mode']
475 stats['old_mode'] = head['old_mode']
476 if head['new_mode']:
476 if head['new_mode']:
477 stats['new_mode'] = head['new_mode']
477 stats['new_mode'] = head['new_mode']
478 if head['b_mode']:
478 if head['b_mode']:
479 stats['new_mode'] = head['b_mode']
479 stats['new_mode'] = head['b_mode']
480
480
481 # delete file
481 # delete file
482 if head['deleted_file_mode']:
482 if head['deleted_file_mode']:
483 op = OPS.DEL
483 op = OPS.DEL
484 stats['binary'] = True
484 stats['binary'] = True
485 stats['ops'][DEL_FILENODE] = 'deleted file'
485 stats['ops'][DEL_FILENODE] = 'deleted file'
486
486
487 # new file
487 # new file
488 elif head['new_file_mode']:
488 elif head['new_file_mode']:
489 op = OPS.ADD
489 op = OPS.ADD
490 stats['binary'] = True
490 stats['binary'] = True
491 stats['old_mode'] = None
491 stats['old_mode'] = None
492 stats['new_mode'] = head['new_file_mode']
492 stats['new_mode'] = head['new_file_mode']
493 stats['ops'][NEW_FILENODE] = 'new file %s' % head['new_file_mode']
493 stats['ops'][NEW_FILENODE] = 'new file %s' % head['new_file_mode']
494
494
495 # modify operation, can be copy, rename or chmod
495 # modify operation, can be copy, rename or chmod
496 else:
496 else:
497 # CHMOD
497 # CHMOD
498 if head['new_mode'] and head['old_mode']:
498 if head['new_mode'] and head['old_mode']:
499 op = OPS.MOD
499 op = OPS.MOD
500 stats['binary'] = True
500 stats['binary'] = True
501 stats['ops'][CHMOD_FILENODE] = (
501 stats['ops'][CHMOD_FILENODE] = (
502 'modified file chmod %s => %s' % (
502 'modified file chmod %s => %s' % (
503 head['old_mode'], head['new_mode']))
503 head['old_mode'], head['new_mode']))
504
504
505 # RENAME
505 # RENAME
506 if head['rename_from'] != head['rename_to']:
506 if head['rename_from'] != head['rename_to']:
507 op = OPS.MOD
507 op = OPS.MOD
508 stats['binary'] = True
508 stats['binary'] = True
509 stats['renamed'] = (head['rename_from'], head['rename_to'])
509 stats['renamed'] = (head['rename_from'], head['rename_to'])
510 stats['ops'][RENAMED_FILENODE] = (
510 stats['ops'][RENAMED_FILENODE] = (
511 'file renamed from %s to %s' % (
511 'file renamed from %s to %s' % (
512 head['rename_from'], head['rename_to']))
512 head['rename_from'], head['rename_to']))
513 # COPY
513 # COPY
514 if head.get('copy_from') and head.get('copy_to'):
514 if head.get('copy_from') and head.get('copy_to'):
515 op = OPS.MOD
515 op = OPS.MOD
516 stats['binary'] = True
516 stats['binary'] = True
517 stats['copied'] = (head['copy_from'], head['copy_to'])
517 stats['copied'] = (head['copy_from'], head['copy_to'])
518 stats['ops'][COPIED_FILENODE] = (
518 stats['ops'][COPIED_FILENODE] = (
519 'file copied from %s to %s' % (
519 'file copied from %s to %s' % (
520 head['copy_from'], head['copy_to']))
520 head['copy_from'], head['copy_to']))
521
521
522 # If our new parsed headers didn't match anything fallback to
522 # If our new parsed headers didn't match anything fallback to
523 # old style detection
523 # old style detection
524 if op is None:
524 if op is None:
525 if not head['a_file'] and head['b_file']:
525 if not head['a_file'] and head['b_file']:
526 op = OPS.ADD
526 op = OPS.ADD
527 stats['binary'] = True
527 stats['binary'] = True
528 stats['new_file'] = True
528 stats['new_file'] = True
529 stats['ops'][NEW_FILENODE] = 'new file'
529 stats['ops'][NEW_FILENODE] = 'new file'
530
530
531 elif head['a_file'] and not head['b_file']:
531 elif head['a_file'] and not head['b_file']:
532 op = OPS.DEL
532 op = OPS.DEL
533 stats['binary'] = True
533 stats['binary'] = True
534 stats['ops'][DEL_FILENODE] = 'deleted file'
534 stats['ops'][DEL_FILENODE] = 'deleted file'
535
535
536 # it's not ADD not DELETE
536 # it's not ADD not DELETE
537 if op is None:
537 if op is None:
538 op = OPS.MOD
538 op = OPS.MOD
539 stats['binary'] = True
539 stats['binary'] = True
540 stats['ops'][MOD_FILENODE] = 'modified file'
540 stats['ops'][MOD_FILENODE] = 'modified file'
541
541
542 # a real non-binary diff
542 # a real non-binary diff
543 if head['a_file'] or head['b_file']:
543 if head['a_file'] or head['b_file']:
544 # simulate splitlines, so we keep the line end part
544 # simulate splitlines, so we keep the line end part
545 diff = self.diff_splitter(chunk.diff)
545 diff = self.diff_splitter(chunk.diff)
546
546
547 # append each file to the diff size
547 # append each file to the diff size
548 raw_chunk_size = len(raw_diff)
548 raw_chunk_size = len(raw_diff)
549
549
550 exceeds_limit = raw_chunk_size > self.file_limit
550 exceeds_limit = raw_chunk_size > self.file_limit
551 self.cur_diff_size += raw_chunk_size
551 self.cur_diff_size += raw_chunk_size
552
552
553 try:
553 try:
554 # Check each file instead of the whole diff.
554 # Check each file instead of the whole diff.
555 # Diff will hide big files but still show small ones.
555 # Diff will hide big files but still show small ones.
556 # From the tests big files are fairly safe to be parsed
556 # From the tests big files are fairly safe to be parsed
557 # but the browser is the bottleneck.
557 # but the browser is the bottleneck.
558 if not self.show_full_diff and exceeds_limit:
558 if not self.show_full_diff and exceeds_limit:
559 log.debug('File `%s` exceeds current file_limit of %s',
559 log.debug('File `%s` exceeds current file_limit of %s',
560 safe_unicode(head['b_path']), self.file_limit)
560 safe_unicode(head['b_path']), self.file_limit)
561 raise DiffLimitExceeded(
561 raise DiffLimitExceeded(
562 'File Limit %s Exceeded', self.file_limit)
562 'File Limit %s Exceeded', self.file_limit)
563
563
564 self._check_large_diff()
564 self._check_large_diff()
565
565
566 raw_diff, chunks, _stats = self._new_parse_lines(diff)
566 raw_diff, chunks, _stats = self._new_parse_lines(diff)
567 stats['binary'] = False
567 stats['binary'] = False
568 stats['added'] = _stats[0]
568 stats['added'] = _stats[0]
569 stats['deleted'] = _stats[1]
569 stats['deleted'] = _stats[1]
570 # explicit mark that it's a modified file
570 # explicit mark that it's a modified file
571 if op == OPS.MOD:
571 if op == OPS.MOD:
572 stats['ops'][MOD_FILENODE] = 'modified file'
572 stats['ops'][MOD_FILENODE] = 'modified file'
573
573
574 except DiffLimitExceeded:
574 except DiffLimitExceeded:
575 diff_container = lambda _diff: \
575 diff_container = lambda _diff: \
576 LimitedDiffContainer(
576 LimitedDiffContainer(
577 self.diff_limit, self.cur_diff_size, _diff)
577 self.diff_limit, self.cur_diff_size, _diff)
578
578
579 limited_diff = True
579 limited_diff = True
580 chunks = []
580 chunks = []
581
581
582 else: # GIT format binary patch, or possibly empty diff
582 else: # GIT format binary patch, or possibly empty diff
583 if head['bin_patch']:
583 if head['bin_patch']:
584 # we have operation already extracted, but we mark simply
584 # we have operation already extracted, but we mark simply
585 # it's a diff we wont show for binary files
585 # it's a diff we wont show for binary files
586 stats['ops'][BIN_FILENODE] = 'binary diff hidden'
586 stats['ops'][BIN_FILENODE] = 'binary diff hidden'
587 chunks = []
587 chunks = []
588
588
589 # Hide content of deleted node by setting empty chunks
589 # Hide content of deleted node by setting empty chunks
590 if chunks and not self.show_full_diff and op == OPS.DEL:
590 if chunks and not self.show_full_diff and op == OPS.DEL:
591 # if not full diff mode show deleted file contents
591 # if not full diff mode show deleted file contents
592 # TODO: anderson: if the view is not too big, there is no way
592 # TODO: anderson: if the view is not too big, there is no way
593 # to see the content of the file
593 # to see the content of the file
594 chunks = []
594 chunks = []
595
595
596 chunks.insert(
596 chunks.insert(
597 0, [{'old_lineno': '',
597 0, [{'old_lineno': '',
598 'new_lineno': '',
598 'new_lineno': '',
599 'action': Action.CONTEXT,
599 'action': Action.CONTEXT,
600 'line': msg,
600 'line': msg,
601 } for _op, msg in stats['ops'].iteritems()
601 } for _op, msg in stats['ops'].iteritems()
602 if _op not in [MOD_FILENODE]])
602 if _op not in [MOD_FILENODE]])
603
603
604 original_filename = safe_unicode(head['a_path'])
604 original_filename = safe_unicode(head['a_path'])
605 _files.append({
605 _files.append({
606 'original_filename': original_filename,
606 'original_filename': original_filename,
607 'filename': safe_unicode(head['b_path']),
607 'filename': safe_unicode(head['b_path']),
608 'old_revision': head['a_blob_id'],
608 'old_revision': head['a_blob_id'],
609 'new_revision': head['b_blob_id'],
609 'new_revision': head['b_blob_id'],
610 'chunks': chunks,
610 'chunks': chunks,
611 'raw_diff': safe_unicode(raw_diff),
611 'raw_diff': safe_unicode(raw_diff),
612 'operation': op,
612 'operation': op,
613 'stats': stats,
613 'stats': stats,
614 'exceeds_limit': exceeds_limit,
614 'exceeds_limit': exceeds_limit,
615 'is_limited_diff': limited_diff,
615 'is_limited_diff': limited_diff,
616 })
616 })
617
617
618 sorter = lambda info: {OPS.ADD: 0, OPS.MOD: 1,
618 sorter = lambda info: {OPS.ADD: 0, OPS.MOD: 1,
619 OPS.DEL: 2}.get(info['operation'])
619 OPS.DEL: 2}.get(info['operation'])
620
620
621 return diff_container(sorted(_files, key=sorter))
621 return diff_container(sorted(_files, key=sorter))
622
622
623 # FIXME: NEWDIFFS: dan: this gets replaced by _new_parse_lines
623 # FIXME: NEWDIFFS: dan: this gets replaced by _new_parse_lines
624 def _parse_lines(self, diff_iter):
624 def _parse_lines(self, diff_iter):
625 """
625 """
626 Parse the diff an return data for the template.
626 Parse the diff an return data for the template.
627 """
627 """
628
628
629 stats = [0, 0]
629 stats = [0, 0]
630 chunks = []
630 chunks = []
631 raw_diff = []
631 raw_diff = []
632
632
633 try:
633 try:
634 line = diff_iter.next()
634 line = diff_iter.next()
635
635
636 while line:
636 while line:
637 raw_diff.append(line)
637 raw_diff.append(line)
638 lines = []
638 lines = []
639 chunks.append(lines)
639 chunks.append(lines)
640
640
641 match = self._chunk_re.match(line)
641 match = self._chunk_re.match(line)
642
642
643 if not match:
643 if not match:
644 break
644 break
645
645
646 gr = match.groups()
646 gr = match.groups()
647 (old_line, old_end,
647 (old_line, old_end,
648 new_line, new_end) = [int(x or 1) for x in gr[:-1]]
648 new_line, new_end) = [int(x or 1) for x in gr[:-1]]
649 old_line -= 1
649 old_line -= 1
650 new_line -= 1
650 new_line -= 1
651
651
652 context = len(gr) == 5
652 context = len(gr) == 5
653 old_end += old_line
653 old_end += old_line
654 new_end += new_line
654 new_end += new_line
655
655
656 if context:
656 if context:
657 # skip context only if it's first line
657 # skip context only if it's first line
658 if int(gr[0]) > 1:
658 if int(gr[0]) > 1:
659 lines.append({
659 lines.append({
660 'old_lineno': '...',
660 'old_lineno': '...',
661 'new_lineno': '...',
661 'new_lineno': '...',
662 'action': Action.CONTEXT,
662 'action': Action.CONTEXT,
663 'line': line,
663 'line': line,
664 })
664 })
665
665
666 line = diff_iter.next()
666 line = diff_iter.next()
667
667
668 while old_line < old_end or new_line < new_end:
668 while old_line < old_end or new_line < new_end:
669 command = ' '
669 command = ' '
670 if line:
670 if line:
671 command = line[0]
671 command = line[0]
672
672
673 affects_old = affects_new = False
673 affects_old = affects_new = False
674
674
675 # ignore those if we don't expect them
675 # ignore those if we don't expect them
676 if command in '#@':
676 if command in '#@':
677 continue
677 continue
678 elif command == '+':
678 elif command == '+':
679 affects_new = True
679 affects_new = True
680 action = Action.ADD
680 action = Action.ADD
681 stats[0] += 1
681 stats[0] += 1
682 elif command == '-':
682 elif command == '-':
683 affects_old = True
683 affects_old = True
684 action = Action.DELETE
684 action = Action.DELETE
685 stats[1] += 1
685 stats[1] += 1
686 else:
686 else:
687 affects_old = affects_new = True
687 affects_old = affects_new = True
688 action = Action.UNMODIFIED
688 action = Action.UNMODIFIED
689
689
690 if not self._newline_marker.match(line):
690 if not self._newline_marker.match(line):
691 old_line += affects_old
691 old_line += affects_old
692 new_line += affects_new
692 new_line += affects_new
693 lines.append({
693 lines.append({
694 'old_lineno': affects_old and old_line or '',
694 'old_lineno': affects_old and old_line or '',
695 'new_lineno': affects_new and new_line or '',
695 'new_lineno': affects_new and new_line or '',
696 'action': action,
696 'action': action,
697 'line': self._clean_line(line, command)
697 'line': self._clean_line(line, command)
698 })
698 })
699 raw_diff.append(line)
699 raw_diff.append(line)
700
700
701 line = diff_iter.next()
701 line = diff_iter.next()
702
702
703 if self._newline_marker.match(line):
703 if self._newline_marker.match(line):
704 # we need to append to lines, since this is not
704 # we need to append to lines, since this is not
705 # counted in the line specs of diff
705 # counted in the line specs of diff
706 lines.append({
706 lines.append({
707 'old_lineno': '...',
707 'old_lineno': '...',
708 'new_lineno': '...',
708 'new_lineno': '...',
709 'action': Action.CONTEXT,
709 'action': Action.CONTEXT,
710 'line': self._clean_line(line, command)
710 'line': self._clean_line(line, command)
711 })
711 })
712
712
713 except StopIteration:
713 except StopIteration:
714 pass
714 pass
715 return ''.join(raw_diff), chunks, stats
715 return ''.join(raw_diff), chunks, stats
716
716
717 # FIXME: NEWDIFFS: dan: this replaces _parse_lines
717 # FIXME: NEWDIFFS: dan: this replaces _parse_lines
718 def _new_parse_lines(self, diff_iter):
718 def _new_parse_lines(self, diff_iter):
719 """
719 """
720 Parse the diff an return data for the template.
720 Parse the diff an return data for the template.
721 """
721 """
722
722
723 stats = [0, 0]
723 stats = [0, 0]
724 chunks = []
724 chunks = []
725 raw_diff = []
725 raw_diff = []
726
726
727 try:
727 try:
728 line = diff_iter.next()
728 line = diff_iter.next()
729
729
730 while line:
730 while line:
731 raw_diff.append(line)
731 raw_diff.append(line)
732 # match header e.g @@ -0,0 +1 @@\n'
732 # match header e.g @@ -0,0 +1 @@\n'
733 match = self._chunk_re.match(line)
733 match = self._chunk_re.match(line)
734
734
735 if not match:
735 if not match:
736 break
736 break
737
737
738 gr = match.groups()
738 gr = match.groups()
739 (old_line, old_end,
739 (old_line, old_end,
740 new_line, new_end) = [int(x or 1) for x in gr[:-1]]
740 new_line, new_end) = [int(x or 1) for x in gr[:-1]]
741
741
742 lines = []
742 lines = []
743 hunk = {
743 hunk = {
744 'section_header': gr[-1],
744 'section_header': gr[-1],
745 'source_start': old_line,
745 'source_start': old_line,
746 'source_length': old_end,
746 'source_length': old_end,
747 'target_start': new_line,
747 'target_start': new_line,
748 'target_length': new_end,
748 'target_length': new_end,
749 'lines': lines,
749 'lines': lines,
750 }
750 }
751 chunks.append(hunk)
751 chunks.append(hunk)
752
752
753 old_line -= 1
753 old_line -= 1
754 new_line -= 1
754 new_line -= 1
755
755
756 context = len(gr) == 5
756 context = len(gr) == 5
757 old_end += old_line
757 old_end += old_line
758 new_end += new_line
758 new_end += new_line
759
759
760 line = diff_iter.next()
760 line = diff_iter.next()
761
761
762 while old_line < old_end or new_line < new_end:
762 while old_line < old_end or new_line < new_end:
763 command = ' '
763 command = ' '
764 if line:
764 if line:
765 command = line[0]
765 command = line[0]
766
766
767 affects_old = affects_new = False
767 affects_old = affects_new = False
768
768
769 # ignore those if we don't expect them
769 # ignore those if we don't expect them
770 if command in '#@':
770 if command in '#@':
771 continue
771 continue
772 elif command == '+':
772 elif command == '+':
773 affects_new = True
773 affects_new = True
774 action = Action.ADD
774 action = Action.ADD
775 stats[0] += 1
775 stats[0] += 1
776 elif command == '-':
776 elif command == '-':
777 affects_old = True
777 affects_old = True
778 action = Action.DELETE
778 action = Action.DELETE
779 stats[1] += 1
779 stats[1] += 1
780 else:
780 else:
781 affects_old = affects_new = True
781 affects_old = affects_new = True
782 action = Action.UNMODIFIED
782 action = Action.UNMODIFIED
783
783
784 if not self._newline_marker.match(line):
784 if not self._newline_marker.match(line):
785 old_line += affects_old
785 old_line += affects_old
786 new_line += affects_new
786 new_line += affects_new
787 lines.append({
787 lines.append({
788 'old_lineno': affects_old and old_line or '',
788 'old_lineno': affects_old and old_line or '',
789 'new_lineno': affects_new and new_line or '',
789 'new_lineno': affects_new and new_line or '',
790 'action': action,
790 'action': action,
791 'line': self._clean_line(line, command)
791 'line': self._clean_line(line, command)
792 })
792 })
793 raw_diff.append(line)
793 raw_diff.append(line)
794
794
795 line = diff_iter.next()
795 line = diff_iter.next()
796
796
797 if self._newline_marker.match(line):
797 if self._newline_marker.match(line):
798 # we need to append to lines, since this is not
798 # we need to append to lines, since this is not
799 # counted in the line specs of diff
799 # counted in the line specs of diff
800 if affects_old:
800 if affects_old:
801 action = Action.OLD_NO_NL
801 action = Action.OLD_NO_NL
802 elif affects_new:
802 elif affects_new:
803 action = Action.NEW_NO_NL
803 action = Action.NEW_NO_NL
804 else:
804 else:
805 raise Exception('invalid context for no newline')
805 raise Exception('invalid context for no newline')
806
806
807 lines.append({
807 lines.append({
808 'old_lineno': None,
808 'old_lineno': None,
809 'new_lineno': None,
809 'new_lineno': None,
810 'action': action,
810 'action': action,
811 'line': self._clean_line(line, command)
811 'line': self._clean_line(line, command)
812 })
812 })
813
813
814 except StopIteration:
814 except StopIteration:
815 pass
815 pass
816
816
817 return ''.join(raw_diff), chunks, stats
817 return ''.join(raw_diff), chunks, stats
818
818
819 def _safe_id(self, idstring):
819 def _safe_id(self, idstring):
820 """Make a string safe for including in an id attribute.
820 """Make a string safe for including in an id attribute.
821
821
822 The HTML spec says that id attributes 'must begin with
822 The HTML spec says that id attributes 'must begin with
823 a letter ([A-Za-z]) and may be followed by any number
823 a letter ([A-Za-z]) and may be followed by any number
824 of letters, digits ([0-9]), hyphens ("-"), underscores
824 of letters, digits ([0-9]), hyphens ("-"), underscores
825 ("_"), colons (":"), and periods (".")'. These regexps
825 ("_"), colons (":"), and periods (".")'. These regexps
826 are slightly over-zealous, in that they remove colons
826 are slightly over-zealous, in that they remove colons
827 and periods unnecessarily.
827 and periods unnecessarily.
828
828
829 Whitespace is transformed into underscores, and then
829 Whitespace is transformed into underscores, and then
830 anything which is not a hyphen or a character that
830 anything which is not a hyphen or a character that
831 matches \w (alphanumerics and underscore) is removed.
831 matches \w (alphanumerics and underscore) is removed.
832
832
833 """
833 """
834 # Transform all whitespace to underscore
834 # Transform all whitespace to underscore
835 idstring = re.sub(r'\s', "_", '%s' % idstring)
835 idstring = re.sub(r'\s', "_", '%s' % idstring)
836 # Remove everything that is not a hyphen or a member of \w
836 # Remove everything that is not a hyphen or a member of \w
837 idstring = re.sub(r'(?!-)\W', "", idstring).lower()
837 idstring = re.sub(r'(?!-)\W', "", idstring).lower()
838 return idstring
838 return idstring
839
839
840 @classmethod
840 @classmethod
841 def diff_splitter(cls, string):
841 def diff_splitter(cls, string):
842 """
842 """
843 Diff split that emulates .splitlines() but works only on \n
843 Diff split that emulates .splitlines() but works only on \n
844 """
844 """
845 if not string:
845 if not string:
846 return
846 return
847 elif string == '\n':
847 elif string == '\n':
848 yield u'\n'
848 yield u'\n'
849 else:
849 else:
850
850
851 has_newline = string.endswith('\n')
851 has_newline = string.endswith('\n')
852 elements = string.split('\n')
852 elements = string.split('\n')
853 if has_newline:
853 if has_newline:
854 # skip last element as it's empty string from newlines
854 # skip last element as it's empty string from newlines
855 elements = elements[:-1]
855 elements = elements[:-1]
856
856
857 len_elements = len(elements)
857 len_elements = len(elements)
858
858
859 for cnt, line in enumerate(elements, start=1):
859 for cnt, line in enumerate(elements, start=1):
860 last_line = cnt == len_elements
860 last_line = cnt == len_elements
861 if last_line and not has_newline:
861 if last_line and not has_newline:
862 yield safe_unicode(line)
862 yield safe_unicode(line)
863 else:
863 else:
864 yield safe_unicode(line) + '\n'
864 yield safe_unicode(line) + '\n'
865
865
866 def prepare(self, inline_diff=True):
866 def prepare(self, inline_diff=True):
867 """
867 """
868 Prepare the passed udiff for HTML rendering.
868 Prepare the passed udiff for HTML rendering.
869
869
870 :return: A list of dicts with diff information.
870 :return: A list of dicts with diff information.
871 """
871 """
872 parsed = self._parser(inline_diff=inline_diff)
872 parsed = self._parser(inline_diff=inline_diff)
873 self.parsed = True
873 self.parsed = True
874 self.parsed_diff = parsed
874 self.parsed_diff = parsed
875 return parsed
875 return parsed
876
876
877 def as_raw(self, diff_lines=None):
877 def as_raw(self, diff_lines=None):
878 """
878 """
879 Returns raw diff as a byte string
879 Returns raw diff as a byte string
880 """
880 """
881 return self._diff.raw
881 return self._diff.raw
882
882
883 def as_html(self, table_class='code-difftable', line_class='line',
883 def as_html(self, table_class='code-difftable', line_class='line',
884 old_lineno_class='lineno old', new_lineno_class='lineno new',
884 old_lineno_class='lineno old', new_lineno_class='lineno new',
885 code_class='code', enable_comments=False, parsed_lines=None):
885 code_class='code', enable_comments=False, parsed_lines=None):
886 """
886 """
887 Return given diff as html table with customized css classes
887 Return given diff as html table with customized css classes
888 """
888 """
889 # TODO(marcink): not sure how to pass in translator
889 # TODO(marcink): not sure how to pass in translator
890 # here in an efficient way, leave the _ for proper gettext extraction
890 # here in an efficient way, leave the _ for proper gettext extraction
891 _ = lambda s: s
891 _ = lambda s: s
892
892
893 def _link_to_if(condition, label, url):
893 def _link_to_if(condition, label, url):
894 """
894 """
895 Generates a link if condition is meet or just the label if not.
895 Generates a link if condition is meet or just the label if not.
896 """
896 """
897
897
898 if condition:
898 if condition:
899 return '''<a href="%(url)s" class="tooltip"
899 return '''<a href="%(url)s" class="tooltip"
900 title="%(title)s">%(label)s</a>''' % {
900 title="%(title)s">%(label)s</a>''' % {
901 'title': _('Click to select line'),
901 'title': _('Click to select line'),
902 'url': url,
902 'url': url,
903 'label': label
903 'label': label
904 }
904 }
905 else:
905 else:
906 return label
906 return label
907 if not self.parsed:
907 if not self.parsed:
908 self.prepare()
908 self.prepare()
909
909
910 diff_lines = self.parsed_diff
910 diff_lines = self.parsed_diff
911 if parsed_lines:
911 if parsed_lines:
912 diff_lines = parsed_lines
912 diff_lines = parsed_lines
913
913
914 _html_empty = True
914 _html_empty = True
915 _html = []
915 _html = []
916 _html.append('''<table class="%(table_class)s">\n''' % {
916 _html.append('''<table class="%(table_class)s">\n''' % {
917 'table_class': table_class
917 'table_class': table_class
918 })
918 })
919
919
920 for diff in diff_lines:
920 for diff in diff_lines:
921 for line in diff['chunks']:
921 for line in diff['chunks']:
922 _html_empty = False
922 _html_empty = False
923 for change in line:
923 for change in line:
924 _html.append('''<tr class="%(lc)s %(action)s">\n''' % {
924 _html.append('''<tr class="%(lc)s %(action)s">\n''' % {
925 'lc': line_class,
925 'lc': line_class,
926 'action': change['action']
926 'action': change['action']
927 })
927 })
928 anchor_old_id = ''
928 anchor_old_id = ''
929 anchor_new_id = ''
929 anchor_new_id = ''
930 anchor_old = "%(filename)s_o%(oldline_no)s" % {
930 anchor_old = "%(filename)s_o%(oldline_no)s" % {
931 'filename': self._safe_id(diff['filename']),
931 'filename': self._safe_id(diff['filename']),
932 'oldline_no': change['old_lineno']
932 'oldline_no': change['old_lineno']
933 }
933 }
934 anchor_new = "%(filename)s_n%(oldline_no)s" % {
934 anchor_new = "%(filename)s_n%(oldline_no)s" % {
935 'filename': self._safe_id(diff['filename']),
935 'filename': self._safe_id(diff['filename']),
936 'oldline_no': change['new_lineno']
936 'oldline_no': change['new_lineno']
937 }
937 }
938 cond_old = (change['old_lineno'] != '...' and
938 cond_old = (change['old_lineno'] != '...' and
939 change['old_lineno'])
939 change['old_lineno'])
940 cond_new = (change['new_lineno'] != '...' and
940 cond_new = (change['new_lineno'] != '...' and
941 change['new_lineno'])
941 change['new_lineno'])
942 if cond_old:
942 if cond_old:
943 anchor_old_id = 'id="%s"' % anchor_old
943 anchor_old_id = 'id="%s"' % anchor_old
944 if cond_new:
944 if cond_new:
945 anchor_new_id = 'id="%s"' % anchor_new
945 anchor_new_id = 'id="%s"' % anchor_new
946
946
947 if change['action'] != Action.CONTEXT:
947 if change['action'] != Action.CONTEXT:
948 anchor_link = True
948 anchor_link = True
949 else:
949 else:
950 anchor_link = False
950 anchor_link = False
951
951
952 ###########################################################
952 ###########################################################
953 # COMMENT ICONS
953 # COMMENT ICONS
954 ###########################################################
954 ###########################################################
955 _html.append('''\t<td class="add-comment-line"><span class="add-comment-content">''')
955 _html.append('''\t<td class="add-comment-line"><span class="add-comment-content">''')
956
956
957 if enable_comments and change['action'] != Action.CONTEXT:
957 if enable_comments and change['action'] != Action.CONTEXT:
958 _html.append('''<a href="#"><span class="icon-comment-add"></span></a>''')
958 _html.append('''<a href="#"><span class="icon-comment-add"></span></a>''')
959
959
960 _html.append('''</span></td><td class="comment-toggle tooltip" title="Toggle Comment Thread"><i class="icon-comment"></i></td>\n''')
960 _html.append('''</span></td><td class="comment-toggle tooltip" title="Toggle Comment Thread"><i class="icon-comment"></i></td>\n''')
961
961
962 ###########################################################
962 ###########################################################
963 # OLD LINE NUMBER
963 # OLD LINE NUMBER
964 ###########################################################
964 ###########################################################
965 _html.append('''\t<td %(a_id)s class="%(olc)s">''' % {
965 _html.append('''\t<td %(a_id)s class="%(olc)s">''' % {
966 'a_id': anchor_old_id,
966 'a_id': anchor_old_id,
967 'olc': old_lineno_class
967 'olc': old_lineno_class
968 })
968 })
969
969
970 _html.append('''%(link)s''' % {
970 _html.append('''%(link)s''' % {
971 'link': _link_to_if(anchor_link, change['old_lineno'],
971 'link': _link_to_if(anchor_link, change['old_lineno'],
972 '#%s' % anchor_old)
972 '#%s' % anchor_old)
973 })
973 })
974 _html.append('''</td>\n''')
974 _html.append('''</td>\n''')
975 ###########################################################
975 ###########################################################
976 # NEW LINE NUMBER
976 # NEW LINE NUMBER
977 ###########################################################
977 ###########################################################
978
978
979 _html.append('''\t<td %(a_id)s class="%(nlc)s">''' % {
979 _html.append('''\t<td %(a_id)s class="%(nlc)s">''' % {
980 'a_id': anchor_new_id,
980 'a_id': anchor_new_id,
981 'nlc': new_lineno_class
981 'nlc': new_lineno_class
982 })
982 })
983
983
984 _html.append('''%(link)s''' % {
984 _html.append('''%(link)s''' % {
985 'link': _link_to_if(anchor_link, change['new_lineno'],
985 'link': _link_to_if(anchor_link, change['new_lineno'],
986 '#%s' % anchor_new)
986 '#%s' % anchor_new)
987 })
987 })
988 _html.append('''</td>\n''')
988 _html.append('''</td>\n''')
989 ###########################################################
989 ###########################################################
990 # CODE
990 # CODE
991 ###########################################################
991 ###########################################################
992 code_classes = [code_class]
992 code_classes = [code_class]
993 if (not enable_comments or
993 if (not enable_comments or
994 change['action'] == Action.CONTEXT):
994 change['action'] == Action.CONTEXT):
995 code_classes.append('no-comment')
995 code_classes.append('no-comment')
996 _html.append('\t<td class="%s">' % ' '.join(code_classes))
996 _html.append('\t<td class="%s">' % ' '.join(code_classes))
997 _html.append('''\n\t\t<pre>%(code)s</pre>\n''' % {
997 _html.append('''\n\t\t<pre>%(code)s</pre>\n''' % {
998 'code': change['line']
998 'code': change['line']
999 })
999 })
1000
1000
1001 _html.append('''\t</td>''')
1001 _html.append('''\t</td>''')
1002 _html.append('''\n</tr>\n''')
1002 _html.append('''\n</tr>\n''')
1003 _html.append('''</table>''')
1003 _html.append('''</table>''')
1004 if _html_empty:
1004 if _html_empty:
1005 return None
1005 return None
1006 return ''.join(_html)
1006 return ''.join(_html)
1007
1007
1008 def stat(self):
1008 def stat(self):
1009 """
1009 """
1010 Returns tuple of added, and removed lines for this instance
1010 Returns tuple of added, and removed lines for this instance
1011 """
1011 """
1012 return self.adds, self.removes
1012 return self.adds, self.removes
1013
1013
1014 def get_context_of_line(
1014 def get_context_of_line(
1015 self, path, diff_line=None, context_before=3, context_after=3):
1015 self, path, diff_line=None, context_before=3, context_after=3):
1016 """
1016 """
1017 Returns the context lines for the specified diff line.
1017 Returns the context lines for the specified diff line.
1018
1018
1019 :type diff_line: :class:`DiffLineNumber`
1019 :type diff_line: :class:`DiffLineNumber`
1020 """
1020 """
1021 assert self.parsed, "DiffProcessor is not initialized."
1021 assert self.parsed, "DiffProcessor is not initialized."
1022
1022
1023 if None not in diff_line:
1023 if None not in diff_line:
1024 raise ValueError(
1024 raise ValueError(
1025 "Cannot specify both line numbers: {}".format(diff_line))
1025 "Cannot specify both line numbers: {}".format(diff_line))
1026
1026
1027 file_diff = self._get_file_diff(path)
1027 file_diff = self._get_file_diff(path)
1028 chunk, idx = self._find_chunk_line_index(file_diff, diff_line)
1028 chunk, idx = self._find_chunk_line_index(file_diff, diff_line)
1029
1029
1030 first_line_to_include = max(idx - context_before, 0)
1030 first_line_to_include = max(idx - context_before, 0)
1031 first_line_after_context = idx + context_after + 1
1031 first_line_after_context = idx + context_after + 1
1032 context_lines = chunk[first_line_to_include:first_line_after_context]
1032 context_lines = chunk[first_line_to_include:first_line_after_context]
1033
1033
1034 line_contents = [
1034 line_contents = [
1035 _context_line(line) for line in context_lines
1035 _context_line(line) for line in context_lines
1036 if _is_diff_content(line)]
1036 if _is_diff_content(line)]
1037 # TODO: johbo: Interim fixup, the diff chunks drop the final newline.
1037 # TODO: johbo: Interim fixup, the diff chunks drop the final newline.
1038 # Once they are fixed, we can drop this line here.
1038 # Once they are fixed, we can drop this line here.
1039 if line_contents:
1039 if line_contents:
1040 line_contents[-1] = (
1040 line_contents[-1] = (
1041 line_contents[-1][0], line_contents[-1][1].rstrip('\n') + '\n')
1041 line_contents[-1][0], line_contents[-1][1].rstrip('\n') + '\n')
1042 return line_contents
1042 return line_contents
1043
1043
1044 def find_context(self, path, context, offset=0):
1044 def find_context(self, path, context, offset=0):
1045 """
1045 """
1046 Finds the given `context` inside of the diff.
1046 Finds the given `context` inside of the diff.
1047
1047
1048 Use the parameter `offset` to specify which offset the target line has
1048 Use the parameter `offset` to specify which offset the target line has
1049 inside of the given `context`. This way the correct diff line will be
1049 inside of the given `context`. This way the correct diff line will be
1050 returned.
1050 returned.
1051
1051
1052 :param offset: Shall be used to specify the offset of the main line
1052 :param offset: Shall be used to specify the offset of the main line
1053 within the given `context`.
1053 within the given `context`.
1054 """
1054 """
1055 if offset < 0 or offset >= len(context):
1055 if offset < 0 or offset >= len(context):
1056 raise ValueError(
1056 raise ValueError(
1057 "Only positive values up to the length of the context "
1057 "Only positive values up to the length of the context "
1058 "minus one are allowed.")
1058 "minus one are allowed.")
1059
1059
1060 matches = []
1060 matches = []
1061 file_diff = self._get_file_diff(path)
1061 file_diff = self._get_file_diff(path)
1062
1062
1063 for chunk in file_diff['chunks']:
1063 for chunk in file_diff['chunks']:
1064 context_iter = iter(context)
1064 context_iter = iter(context)
1065 for line_idx, line in enumerate(chunk):
1065 for line_idx, line in enumerate(chunk):
1066 try:
1066 try:
1067 if _context_line(line) == context_iter.next():
1067 if _context_line(line) == context_iter.next():
1068 continue
1068 continue
1069 except StopIteration:
1069 except StopIteration:
1070 matches.append((line_idx, chunk))
1070 matches.append((line_idx, chunk))
1071 context_iter = iter(context)
1071 context_iter = iter(context)
1072
1072
1073 # Increment position and triger StopIteration
1073 # Increment position and triger StopIteration
1074 # if we had a match at the end
1074 # if we had a match at the end
1075 line_idx += 1
1075 line_idx += 1
1076 try:
1076 try:
1077 context_iter.next()
1077 context_iter.next()
1078 except StopIteration:
1078 except StopIteration:
1079 matches.append((line_idx, chunk))
1079 matches.append((line_idx, chunk))
1080
1080
1081 effective_offset = len(context) - offset
1081 effective_offset = len(context) - offset
1082 found_at_diff_lines = [
1082 found_at_diff_lines = [
1083 _line_to_diff_line_number(chunk[idx - effective_offset])
1083 _line_to_diff_line_number(chunk[idx - effective_offset])
1084 for idx, chunk in matches]
1084 for idx, chunk in matches]
1085
1085
1086 return found_at_diff_lines
1086 return found_at_diff_lines
1087
1087
1088 def _get_file_diff(self, path):
1088 def _get_file_diff(self, path):
1089 for file_diff in self.parsed_diff:
1089 for file_diff in self.parsed_diff:
1090 if file_diff['filename'] == path:
1090 if file_diff['filename'] == path:
1091 break
1091 break
1092 else:
1092 else:
1093 raise FileNotInDiffException("File {} not in diff".format(path))
1093 raise FileNotInDiffException("File {} not in diff".format(path))
1094 return file_diff
1094 return file_diff
1095
1095
1096 def _find_chunk_line_index(self, file_diff, diff_line):
1096 def _find_chunk_line_index(self, file_diff, diff_line):
1097 for chunk in file_diff['chunks']:
1097 for chunk in file_diff['chunks']:
1098 for idx, line in enumerate(chunk):
1098 for idx, line in enumerate(chunk):
1099 if line['old_lineno'] == diff_line.old:
1099 if line['old_lineno'] == diff_line.old:
1100 return chunk, idx
1100 return chunk, idx
1101 if line['new_lineno'] == diff_line.new:
1101 if line['new_lineno'] == diff_line.new:
1102 return chunk, idx
1102 return chunk, idx
1103 raise LineNotInDiffException(
1103 raise LineNotInDiffException(
1104 "The line {} is not part of the diff.".format(diff_line))
1104 "The line {} is not part of the diff.".format(diff_line))
1105
1105
1106
1106
1107 def _is_diff_content(line):
1107 def _is_diff_content(line):
1108 return line['action'] in (
1108 return line['action'] in (
1109 Action.UNMODIFIED, Action.ADD, Action.DELETE)
1109 Action.UNMODIFIED, Action.ADD, Action.DELETE)
1110
1110
1111
1111
1112 def _context_line(line):
1112 def _context_line(line):
1113 return (line['action'], line['line'])
1113 return (line['action'], line['line'])
1114
1114
1115
1115
1116 DiffLineNumber = collections.namedtuple('DiffLineNumber', ['old', 'new'])
1116 DiffLineNumber = collections.namedtuple('DiffLineNumber', ['old', 'new'])
1117
1117
1118
1118
1119 def _line_to_diff_line_number(line):
1119 def _line_to_diff_line_number(line):
1120 new_line_no = line['new_lineno'] or None
1120 new_line_no = line['new_lineno'] or None
1121 old_line_no = line['old_lineno'] or None
1121 old_line_no = line['old_lineno'] or None
1122 return DiffLineNumber(old=old_line_no, new=new_line_no)
1122 return DiffLineNumber(old=old_line_no, new=new_line_no)
1123
1123
1124
1124
1125 class FileNotInDiffException(Exception):
1125 class FileNotInDiffException(Exception):
1126 """
1126 """
1127 Raised when the context for a missing file is requested.
1127 Raised when the context for a missing file is requested.
1128
1128
1129 If you request the context for a line in a file which is not part of the
1129 If you request the context for a line in a file which is not part of the
1130 given diff, then this exception is raised.
1130 given diff, then this exception is raised.
1131 """
1131 """
1132
1132
1133
1133
1134 class LineNotInDiffException(Exception):
1134 class LineNotInDiffException(Exception):
1135 """
1135 """
1136 Raised when the context for a missing line is requested.
1136 Raised when the context for a missing line is requested.
1137
1137
1138 If you request the context for a line in a file and this line is not
1138 If you request the context for a line in a file and this line is not
1139 part of the given diff, then this exception is raised.
1139 part of the given diff, then this exception is raised.
1140 """
1140 """
1141
1141
1142
1142
1143 class DiffLimitExceeded(Exception):
1143 class DiffLimitExceeded(Exception):
1144 pass
1144 pass
1145
1145
1146
1146
1147 # NOTE(marcink): if diffs.mako change, probably this
1147 # NOTE(marcink): if diffs.mako change, probably this
1148 # needs a bump to next version
1148 # needs a bump to next version
1149 CURRENT_DIFF_VERSION = 'v4'
1149 CURRENT_DIFF_VERSION = 'v4'
1150
1150
1151
1151
1152 def _cleanup_cache_file(cached_diff_file):
1152 def _cleanup_cache_file(cached_diff_file):
1153 # cleanup file to not store it "damaged"
1153 # cleanup file to not store it "damaged"
1154 try:
1154 try:
1155 os.remove(cached_diff_file)
1155 os.remove(cached_diff_file)
1156 except Exception:
1156 except Exception:
1157 log.exception('Failed to cleanup path %s', cached_diff_file)
1157 log.exception('Failed to cleanup path %s', cached_diff_file)
1158
1158
1159
1159
1160 def cache_diff(cached_diff_file, diff, commits):
1160 def cache_diff(cached_diff_file, diff, commits):
1161 mode = 'plain' if 'mode:plain' in cached_diff_file else ''
1161 mode = 'plain' if 'mode:plain' in cached_diff_file else ''
1162
1162
1163 struct = {
1163 struct = {
1164 'version': CURRENT_DIFF_VERSION,
1164 'version': CURRENT_DIFF_VERSION,
1165 'diff': diff,
1165 'diff': diff,
1166 'commits': commits
1166 'commits': commits
1167 }
1167 }
1168
1168
1169 start = time.time()
1169 start = time.time()
1170 try:
1170 try:
1171 if mode == 'plain':
1171 if mode == 'plain':
1172 with open(cached_diff_file, 'wb') as f:
1172 with open(cached_diff_file, 'wb') as f:
1173 pickle.dump(struct, f)
1173 pickle.dump(struct, f)
1174 else:
1174 else:
1175 with bz2.BZ2File(cached_diff_file, 'wb') as f:
1175 with bz2.BZ2File(cached_diff_file, 'wb') as f:
1176 pickle.dump(struct, f)
1176 pickle.dump(struct, f)
1177 except Exception:
1177 except Exception:
1178 log.warn('Failed to save cache', exc_info=True)
1178 log.warn('Failed to save cache', exc_info=True)
1179 _cleanup_cache_file(cached_diff_file)
1179 _cleanup_cache_file(cached_diff_file)
1180
1180
1181 log.debug('Saved diff cache under %s in %.3fs', cached_diff_file, time.time() - start)
1181 log.debug('Saved diff cache under %s in %.4fs', cached_diff_file, time.time() - start)
1182
1182
1183
1183
1184 def load_cached_diff(cached_diff_file):
1184 def load_cached_diff(cached_diff_file):
1185 mode = 'plain' if 'mode:plain' in cached_diff_file else ''
1185 mode = 'plain' if 'mode:plain' in cached_diff_file else ''
1186
1186
1187 default_struct = {
1187 default_struct = {
1188 'version': CURRENT_DIFF_VERSION,
1188 'version': CURRENT_DIFF_VERSION,
1189 'diff': None,
1189 'diff': None,
1190 'commits': None
1190 'commits': None
1191 }
1191 }
1192
1192
1193 has_cache = os.path.isfile(cached_diff_file)
1193 has_cache = os.path.isfile(cached_diff_file)
1194 if not has_cache:
1194 if not has_cache:
1195 log.debug('Reading diff cache file failed %s', cached_diff_file)
1195 log.debug('Reading diff cache file failed %s', cached_diff_file)
1196 return default_struct
1196 return default_struct
1197
1197
1198 data = None
1198 data = None
1199
1199
1200 start = time.time()
1200 start = time.time()
1201 try:
1201 try:
1202 if mode == 'plain':
1202 if mode == 'plain':
1203 with open(cached_diff_file, 'rb') as f:
1203 with open(cached_diff_file, 'rb') as f:
1204 data = pickle.load(f)
1204 data = pickle.load(f)
1205 else:
1205 else:
1206 with bz2.BZ2File(cached_diff_file, 'rb') as f:
1206 with bz2.BZ2File(cached_diff_file, 'rb') as f:
1207 data = pickle.load(f)
1207 data = pickle.load(f)
1208 except Exception:
1208 except Exception:
1209 log.warn('Failed to read diff cache file', exc_info=True)
1209 log.warn('Failed to read diff cache file', exc_info=True)
1210
1210
1211 if not data:
1211 if not data:
1212 data = default_struct
1212 data = default_struct
1213
1213
1214 if not isinstance(data, dict):
1214 if not isinstance(data, dict):
1215 # old version of data ?
1215 # old version of data ?
1216 data = default_struct
1216 data = default_struct
1217
1217
1218 # check version
1218 # check version
1219 if data.get('version') != CURRENT_DIFF_VERSION:
1219 if data.get('version') != CURRENT_DIFF_VERSION:
1220 # purge cache
1220 # purge cache
1221 _cleanup_cache_file(cached_diff_file)
1221 _cleanup_cache_file(cached_diff_file)
1222 return default_struct
1222 return default_struct
1223
1223
1224 log.debug('Loaded diff cache from %s in %.3fs', cached_diff_file, time.time() - start)
1224 log.debug('Loaded diff cache from %s in %.4fs', cached_diff_file, time.time() - start)
1225
1225
1226 return data
1226 return data
1227
1227
1228
1228
1229 def generate_diff_cache_key(*args):
1229 def generate_diff_cache_key(*args):
1230 """
1230 """
1231 Helper to generate a cache key using arguments
1231 Helper to generate a cache key using arguments
1232 """
1232 """
1233 def arg_mapper(input_param):
1233 def arg_mapper(input_param):
1234 input_param = safe_str(input_param)
1234 input_param = safe_str(input_param)
1235 # we cannot allow '/' in arguments since it would allow
1235 # we cannot allow '/' in arguments since it would allow
1236 # subdirectory usage
1236 # subdirectory usage
1237 input_param.replace('/', '_')
1237 input_param.replace('/', '_')
1238 return input_param or None # prevent empty string arguments
1238 return input_param or None # prevent empty string arguments
1239
1239
1240 return '_'.join([
1240 return '_'.join([
1241 '{}' for i in range(len(args))]).format(*map(arg_mapper, args))
1241 '{}' for i in range(len(args))]).format(*map(arg_mapper, args))
1242
1242
1243
1243
1244 def diff_cache_exist(cache_storage, *args):
1244 def diff_cache_exist(cache_storage, *args):
1245 """
1245 """
1246 Based on all generated arguments check and return a cache path
1246 Based on all generated arguments check and return a cache path
1247 """
1247 """
1248 cache_key = generate_diff_cache_key(*args)
1248 cache_key = generate_diff_cache_key(*args)
1249 cache_file_path = os.path.join(cache_storage, cache_key)
1249 cache_file_path = os.path.join(cache_storage, cache_key)
1250 # prevent path traversal attacks using some param that have e.g '../../'
1250 # prevent path traversal attacks using some param that have e.g '../../'
1251 if not os.path.abspath(cache_file_path).startswith(cache_storage):
1251 if not os.path.abspath(cache_file_path).startswith(cache_storage):
1252 raise ValueError('Final path must be within {}'.format(cache_storage))
1252 raise ValueError('Final path must be within {}'.format(cache_storage))
1253
1253
1254 return cache_file_path
1254 return cache_file_path
@@ -1,60 +1,60 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2019 RhodeCode GmbH
3 # Copyright (C) 2016-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21
21
22 import time
22 import time
23 import logging
23 import logging
24
24
25
25
26 from rhodecode.lib.base import get_ip_addr, get_access_path, get_user_agent
26 from rhodecode.lib.base import get_ip_addr, get_access_path, get_user_agent
27 from rhodecode.lib.utils2 import safe_str
27 from rhodecode.lib.utils2 import safe_str
28
28
29
29
30 log = logging.getLogger(__name__)
30 log = logging.getLogger(__name__)
31
31
32
32
33 class RequestWrapperTween(object):
33 class RequestWrapperTween(object):
34 def __init__(self, handler, registry):
34 def __init__(self, handler, registry):
35 self.handler = handler
35 self.handler = handler
36 self.registry = registry
36 self.registry = registry
37
37
38 # one-time configuration code goes here
38 # one-time configuration code goes here
39
39
40 def __call__(self, request):
40 def __call__(self, request):
41 start = time.time()
41 start = time.time()
42 try:
42 try:
43 response = self.handler(request)
43 response = self.handler(request)
44 finally:
44 finally:
45 end = time.time()
45 end = time.time()
46 total = end - start
46 total = end - start
47 log.info(
47 log.info(
48 'IP: %s %s Request to %s time: %.3fs [%s]',
48 'IP: %s %s Request to %s time: %.4fs [%s]',
49 get_ip_addr(request.environ), request.environ.get('REQUEST_METHOD'),
49 get_ip_addr(request.environ), request.environ.get('REQUEST_METHOD'),
50 safe_str(get_access_path(request.environ)), total,
50 safe_str(get_access_path(request.environ)), total,
51 get_user_agent(request. environ)
51 get_user_agent(request. environ)
52 )
52 )
53
53
54 return response
54 return response
55
55
56
56
57 def includeme(config):
57 def includeme(config):
58 config.add_tween(
58 config.add_tween(
59 'rhodecode.lib.middleware.request_wrapper.RequestWrapperTween',
59 'rhodecode.lib.middleware.request_wrapper.RequestWrapperTween',
60 )
60 )
@@ -1,678 +1,678 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2014-2019 RhodeCode GmbH
3 # Copyright (C) 2014-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 SimpleVCS middleware for handling protocol request (push/clone etc.)
22 SimpleVCS middleware for handling protocol request (push/clone etc.)
23 It's implemented with basic auth function
23 It's implemented with basic auth function
24 """
24 """
25
25
26 import os
26 import os
27 import re
27 import re
28 import logging
28 import logging
29 import importlib
29 import importlib
30 from functools import wraps
30 from functools import wraps
31 from StringIO import StringIO
31 from StringIO import StringIO
32 from lxml import etree
32 from lxml import etree
33
33
34 import time
34 import time
35 from paste.httpheaders import REMOTE_USER, AUTH_TYPE
35 from paste.httpheaders import REMOTE_USER, AUTH_TYPE
36
36
37 from pyramid.httpexceptions import (
37 from pyramid.httpexceptions import (
38 HTTPNotFound, HTTPForbidden, HTTPNotAcceptable, HTTPInternalServerError)
38 HTTPNotFound, HTTPForbidden, HTTPNotAcceptable, HTTPInternalServerError)
39 from zope.cachedescriptors.property import Lazy as LazyProperty
39 from zope.cachedescriptors.property import Lazy as LazyProperty
40
40
41 import rhodecode
41 import rhodecode
42 from rhodecode.authentication.base import authenticate, VCS_TYPE, loadplugin
42 from rhodecode.authentication.base import authenticate, VCS_TYPE, loadplugin
43 from rhodecode.lib import rc_cache
43 from rhodecode.lib import rc_cache
44 from rhodecode.lib.auth import AuthUser, HasPermissionAnyMiddleware
44 from rhodecode.lib.auth import AuthUser, HasPermissionAnyMiddleware
45 from rhodecode.lib.base import (
45 from rhodecode.lib.base import (
46 BasicAuth, get_ip_addr, get_user_agent, vcs_operation_context)
46 BasicAuth, get_ip_addr, get_user_agent, vcs_operation_context)
47 from rhodecode.lib.exceptions import (UserCreationError, NotAllowedToCreateUserError)
47 from rhodecode.lib.exceptions import (UserCreationError, NotAllowedToCreateUserError)
48 from rhodecode.lib.hooks_daemon import prepare_callback_daemon
48 from rhodecode.lib.hooks_daemon import prepare_callback_daemon
49 from rhodecode.lib.middleware import appenlight
49 from rhodecode.lib.middleware import appenlight
50 from rhodecode.lib.middleware.utils import scm_app_http
50 from rhodecode.lib.middleware.utils import scm_app_http
51 from rhodecode.lib.utils import is_valid_repo, SLUG_RE
51 from rhodecode.lib.utils import is_valid_repo, SLUG_RE
52 from rhodecode.lib.utils2 import safe_str, fix_PATH, str2bool, safe_unicode
52 from rhodecode.lib.utils2 import safe_str, fix_PATH, str2bool, safe_unicode
53 from rhodecode.lib.vcs.conf import settings as vcs_settings
53 from rhodecode.lib.vcs.conf import settings as vcs_settings
54 from rhodecode.lib.vcs.backends import base
54 from rhodecode.lib.vcs.backends import base
55
55
56 from rhodecode.model import meta
56 from rhodecode.model import meta
57 from rhodecode.model.db import User, Repository, PullRequest
57 from rhodecode.model.db import User, Repository, PullRequest
58 from rhodecode.model.scm import ScmModel
58 from rhodecode.model.scm import ScmModel
59 from rhodecode.model.pull_request import PullRequestModel
59 from rhodecode.model.pull_request import PullRequestModel
60 from rhodecode.model.settings import SettingsModel, VcsSettingsModel
60 from rhodecode.model.settings import SettingsModel, VcsSettingsModel
61
61
62 log = logging.getLogger(__name__)
62 log = logging.getLogger(__name__)
63
63
64
64
65 def extract_svn_txn_id(acl_repo_name, data):
65 def extract_svn_txn_id(acl_repo_name, data):
66 """
66 """
67 Helper method for extraction of svn txn_id from submitted XML data during
67 Helper method for extraction of svn txn_id from submitted XML data during
68 POST operations
68 POST operations
69 """
69 """
70 try:
70 try:
71 root = etree.fromstring(data)
71 root = etree.fromstring(data)
72 pat = re.compile(r'/txn/(?P<txn_id>.*)')
72 pat = re.compile(r'/txn/(?P<txn_id>.*)')
73 for el in root:
73 for el in root:
74 if el.tag == '{DAV:}source':
74 if el.tag == '{DAV:}source':
75 for sub_el in el:
75 for sub_el in el:
76 if sub_el.tag == '{DAV:}href':
76 if sub_el.tag == '{DAV:}href':
77 match = pat.search(sub_el.text)
77 match = pat.search(sub_el.text)
78 if match:
78 if match:
79 svn_tx_id = match.groupdict()['txn_id']
79 svn_tx_id = match.groupdict()['txn_id']
80 txn_id = rc_cache.utils.compute_key_from_params(
80 txn_id = rc_cache.utils.compute_key_from_params(
81 acl_repo_name, svn_tx_id)
81 acl_repo_name, svn_tx_id)
82 return txn_id
82 return txn_id
83 except Exception:
83 except Exception:
84 log.exception('Failed to extract txn_id')
84 log.exception('Failed to extract txn_id')
85
85
86
86
87 def initialize_generator(factory):
87 def initialize_generator(factory):
88 """
88 """
89 Initializes the returned generator by draining its first element.
89 Initializes the returned generator by draining its first element.
90
90
91 This can be used to give a generator an initializer, which is the code
91 This can be used to give a generator an initializer, which is the code
92 up to the first yield statement. This decorator enforces that the first
92 up to the first yield statement. This decorator enforces that the first
93 produced element has the value ``"__init__"`` to make its special
93 produced element has the value ``"__init__"`` to make its special
94 purpose very explicit in the using code.
94 purpose very explicit in the using code.
95 """
95 """
96
96
97 @wraps(factory)
97 @wraps(factory)
98 def wrapper(*args, **kwargs):
98 def wrapper(*args, **kwargs):
99 gen = factory(*args, **kwargs)
99 gen = factory(*args, **kwargs)
100 try:
100 try:
101 init = gen.next()
101 init = gen.next()
102 except StopIteration:
102 except StopIteration:
103 raise ValueError('Generator must yield at least one element.')
103 raise ValueError('Generator must yield at least one element.')
104 if init != "__init__":
104 if init != "__init__":
105 raise ValueError('First yielded element must be "__init__".')
105 raise ValueError('First yielded element must be "__init__".')
106 return gen
106 return gen
107 return wrapper
107 return wrapper
108
108
109
109
110 class SimpleVCS(object):
110 class SimpleVCS(object):
111 """Common functionality for SCM HTTP handlers."""
111 """Common functionality for SCM HTTP handlers."""
112
112
113 SCM = 'unknown'
113 SCM = 'unknown'
114
114
115 acl_repo_name = None
115 acl_repo_name = None
116 url_repo_name = None
116 url_repo_name = None
117 vcs_repo_name = None
117 vcs_repo_name = None
118 rc_extras = {}
118 rc_extras = {}
119
119
120 # We have to handle requests to shadow repositories different than requests
120 # We have to handle requests to shadow repositories different than requests
121 # to normal repositories. Therefore we have to distinguish them. To do this
121 # to normal repositories. Therefore we have to distinguish them. To do this
122 # we use this regex which will match only on URLs pointing to shadow
122 # we use this regex which will match only on URLs pointing to shadow
123 # repositories.
123 # repositories.
124 shadow_repo_re = re.compile(
124 shadow_repo_re = re.compile(
125 '(?P<groups>(?:{slug_pat}/)*)' # repo groups
125 '(?P<groups>(?:{slug_pat}/)*)' # repo groups
126 '(?P<target>{slug_pat})/' # target repo
126 '(?P<target>{slug_pat})/' # target repo
127 'pull-request/(?P<pr_id>\d+)/' # pull request
127 'pull-request/(?P<pr_id>\d+)/' # pull request
128 'repository$' # shadow repo
128 'repository$' # shadow repo
129 .format(slug_pat=SLUG_RE.pattern))
129 .format(slug_pat=SLUG_RE.pattern))
130
130
131 def __init__(self, config, registry):
131 def __init__(self, config, registry):
132 self.registry = registry
132 self.registry = registry
133 self.config = config
133 self.config = config
134 # re-populated by specialized middleware
134 # re-populated by specialized middleware
135 self.repo_vcs_config = base.Config()
135 self.repo_vcs_config = base.Config()
136 self.rhodecode_settings = SettingsModel().get_all_settings(cache=True)
136 self.rhodecode_settings = SettingsModel().get_all_settings(cache=True)
137
137
138 registry.rhodecode_settings = self.rhodecode_settings
138 registry.rhodecode_settings = self.rhodecode_settings
139 # authenticate this VCS request using authfunc
139 # authenticate this VCS request using authfunc
140 auth_ret_code_detection = \
140 auth_ret_code_detection = \
141 str2bool(self.config.get('auth_ret_code_detection', False))
141 str2bool(self.config.get('auth_ret_code_detection', False))
142 self.authenticate = BasicAuth(
142 self.authenticate = BasicAuth(
143 '', authenticate, registry, config.get('auth_ret_code'),
143 '', authenticate, registry, config.get('auth_ret_code'),
144 auth_ret_code_detection)
144 auth_ret_code_detection)
145 self.ip_addr = '0.0.0.0'
145 self.ip_addr = '0.0.0.0'
146
146
147 @LazyProperty
147 @LazyProperty
148 def global_vcs_config(self):
148 def global_vcs_config(self):
149 try:
149 try:
150 return VcsSettingsModel().get_ui_settings_as_config_obj()
150 return VcsSettingsModel().get_ui_settings_as_config_obj()
151 except Exception:
151 except Exception:
152 return base.Config()
152 return base.Config()
153
153
154 @property
154 @property
155 def base_path(self):
155 def base_path(self):
156 settings_path = self.repo_vcs_config.get(*VcsSettingsModel.PATH_SETTING)
156 settings_path = self.repo_vcs_config.get(*VcsSettingsModel.PATH_SETTING)
157
157
158 if not settings_path:
158 if not settings_path:
159 settings_path = self.global_vcs_config.get(*VcsSettingsModel.PATH_SETTING)
159 settings_path = self.global_vcs_config.get(*VcsSettingsModel.PATH_SETTING)
160
160
161 if not settings_path:
161 if not settings_path:
162 # try, maybe we passed in explicitly as config option
162 # try, maybe we passed in explicitly as config option
163 settings_path = self.config.get('base_path')
163 settings_path = self.config.get('base_path')
164
164
165 if not settings_path:
165 if not settings_path:
166 raise ValueError('FATAL: base_path is empty')
166 raise ValueError('FATAL: base_path is empty')
167 return settings_path
167 return settings_path
168
168
169 def set_repo_names(self, environ):
169 def set_repo_names(self, environ):
170 """
170 """
171 This will populate the attributes acl_repo_name, url_repo_name,
171 This will populate the attributes acl_repo_name, url_repo_name,
172 vcs_repo_name and is_shadow_repo. In case of requests to normal (non
172 vcs_repo_name and is_shadow_repo. In case of requests to normal (non
173 shadow) repositories all names are equal. In case of requests to a
173 shadow) repositories all names are equal. In case of requests to a
174 shadow repository the acl-name points to the target repo of the pull
174 shadow repository the acl-name points to the target repo of the pull
175 request and the vcs-name points to the shadow repo file system path.
175 request and the vcs-name points to the shadow repo file system path.
176 The url-name is always the URL used by the vcs client program.
176 The url-name is always the URL used by the vcs client program.
177
177
178 Example in case of a shadow repo:
178 Example in case of a shadow repo:
179 acl_repo_name = RepoGroup/MyRepo
179 acl_repo_name = RepoGroup/MyRepo
180 url_repo_name = RepoGroup/MyRepo/pull-request/3/repository
180 url_repo_name = RepoGroup/MyRepo/pull-request/3/repository
181 vcs_repo_name = /repo/base/path/RepoGroup/.__shadow_MyRepo_pr-3'
181 vcs_repo_name = /repo/base/path/RepoGroup/.__shadow_MyRepo_pr-3'
182 """
182 """
183 # First we set the repo name from URL for all attributes. This is the
183 # First we set the repo name from URL for all attributes. This is the
184 # default if handling normal (non shadow) repo requests.
184 # default if handling normal (non shadow) repo requests.
185 self.url_repo_name = self._get_repository_name(environ)
185 self.url_repo_name = self._get_repository_name(environ)
186 self.acl_repo_name = self.vcs_repo_name = self.url_repo_name
186 self.acl_repo_name = self.vcs_repo_name = self.url_repo_name
187 self.is_shadow_repo = False
187 self.is_shadow_repo = False
188
188
189 # Check if this is a request to a shadow repository.
189 # Check if this is a request to a shadow repository.
190 match = self.shadow_repo_re.match(self.url_repo_name)
190 match = self.shadow_repo_re.match(self.url_repo_name)
191 if match:
191 if match:
192 match_dict = match.groupdict()
192 match_dict = match.groupdict()
193
193
194 # Build acl repo name from regex match.
194 # Build acl repo name from regex match.
195 acl_repo_name = safe_unicode('{groups}{target}'.format(
195 acl_repo_name = safe_unicode('{groups}{target}'.format(
196 groups=match_dict['groups'] or '',
196 groups=match_dict['groups'] or '',
197 target=match_dict['target']))
197 target=match_dict['target']))
198
198
199 # Retrieve pull request instance by ID from regex match.
199 # Retrieve pull request instance by ID from regex match.
200 pull_request = PullRequest.get(match_dict['pr_id'])
200 pull_request = PullRequest.get(match_dict['pr_id'])
201
201
202 # Only proceed if we got a pull request and if acl repo name from
202 # Only proceed if we got a pull request and if acl repo name from
203 # URL equals the target repo name of the pull request.
203 # URL equals the target repo name of the pull request.
204 if pull_request and \
204 if pull_request and \
205 (acl_repo_name == pull_request.target_repo.repo_name):
205 (acl_repo_name == pull_request.target_repo.repo_name):
206 repo_id = pull_request.target_repo.repo_id
206 repo_id = pull_request.target_repo.repo_id
207 # Get file system path to shadow repository.
207 # Get file system path to shadow repository.
208 workspace_id = PullRequestModel()._workspace_id(pull_request)
208 workspace_id = PullRequestModel()._workspace_id(pull_request)
209 target_vcs = pull_request.target_repo.scm_instance()
209 target_vcs = pull_request.target_repo.scm_instance()
210 vcs_repo_name = target_vcs._get_shadow_repository_path(
210 vcs_repo_name = target_vcs._get_shadow_repository_path(
211 repo_id, workspace_id)
211 repo_id, workspace_id)
212
212
213 # Store names for later usage.
213 # Store names for later usage.
214 self.vcs_repo_name = vcs_repo_name
214 self.vcs_repo_name = vcs_repo_name
215 self.acl_repo_name = acl_repo_name
215 self.acl_repo_name = acl_repo_name
216 self.is_shadow_repo = True
216 self.is_shadow_repo = True
217
217
218 log.debug('Setting all VCS repository names: %s', {
218 log.debug('Setting all VCS repository names: %s', {
219 'acl_repo_name': self.acl_repo_name,
219 'acl_repo_name': self.acl_repo_name,
220 'url_repo_name': self.url_repo_name,
220 'url_repo_name': self.url_repo_name,
221 'vcs_repo_name': self.vcs_repo_name,
221 'vcs_repo_name': self.vcs_repo_name,
222 })
222 })
223
223
224 @property
224 @property
225 def scm_app(self):
225 def scm_app(self):
226 custom_implementation = self.config['vcs.scm_app_implementation']
226 custom_implementation = self.config['vcs.scm_app_implementation']
227 if custom_implementation == 'http':
227 if custom_implementation == 'http':
228 log.info('Using HTTP implementation of scm app.')
228 log.info('Using HTTP implementation of scm app.')
229 scm_app_impl = scm_app_http
229 scm_app_impl = scm_app_http
230 else:
230 else:
231 log.info('Using custom implementation of scm_app: "{}"'.format(
231 log.info('Using custom implementation of scm_app: "{}"'.format(
232 custom_implementation))
232 custom_implementation))
233 scm_app_impl = importlib.import_module(custom_implementation)
233 scm_app_impl = importlib.import_module(custom_implementation)
234 return scm_app_impl
234 return scm_app_impl
235
235
236 def _get_by_id(self, repo_name):
236 def _get_by_id(self, repo_name):
237 """
237 """
238 Gets a special pattern _<ID> from clone url and tries to replace it
238 Gets a special pattern _<ID> from clone url and tries to replace it
239 with a repository_name for support of _<ID> non changeable urls
239 with a repository_name for support of _<ID> non changeable urls
240 """
240 """
241
241
242 data = repo_name.split('/')
242 data = repo_name.split('/')
243 if len(data) >= 2:
243 if len(data) >= 2:
244 from rhodecode.model.repo import RepoModel
244 from rhodecode.model.repo import RepoModel
245 by_id_match = RepoModel().get_repo_by_id(repo_name)
245 by_id_match = RepoModel().get_repo_by_id(repo_name)
246 if by_id_match:
246 if by_id_match:
247 data[1] = by_id_match.repo_name
247 data[1] = by_id_match.repo_name
248
248
249 return safe_str('/'.join(data))
249 return safe_str('/'.join(data))
250
250
251 def _invalidate_cache(self, repo_name):
251 def _invalidate_cache(self, repo_name):
252 """
252 """
253 Set's cache for this repository for invalidation on next access
253 Set's cache for this repository for invalidation on next access
254
254
255 :param repo_name: full repo name, also a cache key
255 :param repo_name: full repo name, also a cache key
256 """
256 """
257 ScmModel().mark_for_invalidation(repo_name)
257 ScmModel().mark_for_invalidation(repo_name)
258
258
259 def is_valid_and_existing_repo(self, repo_name, base_path, scm_type):
259 def is_valid_and_existing_repo(self, repo_name, base_path, scm_type):
260 db_repo = Repository.get_by_repo_name(repo_name)
260 db_repo = Repository.get_by_repo_name(repo_name)
261 if not db_repo:
261 if not db_repo:
262 log.debug('Repository `%s` not found inside the database.',
262 log.debug('Repository `%s` not found inside the database.',
263 repo_name)
263 repo_name)
264 return False
264 return False
265
265
266 if db_repo.repo_type != scm_type:
266 if db_repo.repo_type != scm_type:
267 log.warning(
267 log.warning(
268 'Repository `%s` have incorrect scm_type, expected %s got %s',
268 'Repository `%s` have incorrect scm_type, expected %s got %s',
269 repo_name, db_repo.repo_type, scm_type)
269 repo_name, db_repo.repo_type, scm_type)
270 return False
270 return False
271
271
272 config = db_repo._config
272 config = db_repo._config
273 config.set('extensions', 'largefiles', '')
273 config.set('extensions', 'largefiles', '')
274 return is_valid_repo(
274 return is_valid_repo(
275 repo_name, base_path,
275 repo_name, base_path,
276 explicit_scm=scm_type, expect_scm=scm_type, config=config)
276 explicit_scm=scm_type, expect_scm=scm_type, config=config)
277
277
278 def valid_and_active_user(self, user):
278 def valid_and_active_user(self, user):
279 """
279 """
280 Checks if that user is not empty, and if it's actually object it checks
280 Checks if that user is not empty, and if it's actually object it checks
281 if he's active.
281 if he's active.
282
282
283 :param user: user object or None
283 :param user: user object or None
284 :return: boolean
284 :return: boolean
285 """
285 """
286 if user is None:
286 if user is None:
287 return False
287 return False
288
288
289 elif user.active:
289 elif user.active:
290 return True
290 return True
291
291
292 return False
292 return False
293
293
294 @property
294 @property
295 def is_shadow_repo_dir(self):
295 def is_shadow_repo_dir(self):
296 return os.path.isdir(self.vcs_repo_name)
296 return os.path.isdir(self.vcs_repo_name)
297
297
298 def _check_permission(self, action, user, auth_user, repo_name, ip_addr=None,
298 def _check_permission(self, action, user, auth_user, repo_name, ip_addr=None,
299 plugin_id='', plugin_cache_active=False, cache_ttl=0):
299 plugin_id='', plugin_cache_active=False, cache_ttl=0):
300 """
300 """
301 Checks permissions using action (push/pull) user and repository
301 Checks permissions using action (push/pull) user and repository
302 name. If plugin_cache and ttl is set it will use the plugin which
302 name. If plugin_cache and ttl is set it will use the plugin which
303 authenticated the user to store the cached permissions result for N
303 authenticated the user to store the cached permissions result for N
304 amount of seconds as in cache_ttl
304 amount of seconds as in cache_ttl
305
305
306 :param action: push or pull action
306 :param action: push or pull action
307 :param user: user instance
307 :param user: user instance
308 :param repo_name: repository name
308 :param repo_name: repository name
309 """
309 """
310
310
311 log.debug('AUTH_CACHE_TTL for permissions `%s` active: %s (TTL: %s)',
311 log.debug('AUTH_CACHE_TTL for permissions `%s` active: %s (TTL: %s)',
312 plugin_id, plugin_cache_active, cache_ttl)
312 plugin_id, plugin_cache_active, cache_ttl)
313
313
314 user_id = user.user_id
314 user_id = user.user_id
315 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
315 cache_namespace_uid = 'cache_user_auth.{}'.format(user_id)
316 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
316 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
317
317
318 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
318 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid,
319 expiration_time=cache_ttl,
319 expiration_time=cache_ttl,
320 condition=plugin_cache_active)
320 condition=plugin_cache_active)
321 def compute_perm_vcs(
321 def compute_perm_vcs(
322 cache_name, plugin_id, action, user_id, repo_name, ip_addr):
322 cache_name, plugin_id, action, user_id, repo_name, ip_addr):
323
323
324 log.debug('auth: calculating permission access now...')
324 log.debug('auth: calculating permission access now...')
325 # check IP
325 # check IP
326 inherit = user.inherit_default_permissions
326 inherit = user.inherit_default_permissions
327 ip_allowed = AuthUser.check_ip_allowed(
327 ip_allowed = AuthUser.check_ip_allowed(
328 user_id, ip_addr, inherit_from_default=inherit)
328 user_id, ip_addr, inherit_from_default=inherit)
329 if ip_allowed:
329 if ip_allowed:
330 log.info('Access for IP:%s allowed', ip_addr)
330 log.info('Access for IP:%s allowed', ip_addr)
331 else:
331 else:
332 return False
332 return False
333
333
334 if action == 'push':
334 if action == 'push':
335 perms = ('repository.write', 'repository.admin')
335 perms = ('repository.write', 'repository.admin')
336 if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name):
336 if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name):
337 return False
337 return False
338
338
339 else:
339 else:
340 # any other action need at least read permission
340 # any other action need at least read permission
341 perms = (
341 perms = (
342 'repository.read', 'repository.write', 'repository.admin')
342 'repository.read', 'repository.write', 'repository.admin')
343 if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name):
343 if not HasPermissionAnyMiddleware(*perms)(auth_user, repo_name):
344 return False
344 return False
345
345
346 return True
346 return True
347
347
348 start = time.time()
348 start = time.time()
349 log.debug('Running plugin `%s` permissions check', plugin_id)
349 log.debug('Running plugin `%s` permissions check', plugin_id)
350
350
351 # for environ based auth, password can be empty, but then the validation is
351 # for environ based auth, password can be empty, but then the validation is
352 # on the server that fills in the env data needed for authentication
352 # on the server that fills in the env data needed for authentication
353 perm_result = compute_perm_vcs(
353 perm_result = compute_perm_vcs(
354 'vcs_permissions', plugin_id, action, user.user_id, repo_name, ip_addr)
354 'vcs_permissions', plugin_id, action, user.user_id, repo_name, ip_addr)
355
355
356 auth_time = time.time() - start
356 auth_time = time.time() - start
357 log.debug('Permissions for plugin `%s` completed in %.3fs, '
357 log.debug('Permissions for plugin `%s` completed in %.4fs, '
358 'expiration time of fetched cache %.1fs.',
358 'expiration time of fetched cache %.1fs.',
359 plugin_id, auth_time, cache_ttl)
359 plugin_id, auth_time, cache_ttl)
360
360
361 return perm_result
361 return perm_result
362
362
363 def _get_http_scheme(self, environ):
363 def _get_http_scheme(self, environ):
364 try:
364 try:
365 return environ['wsgi.url_scheme']
365 return environ['wsgi.url_scheme']
366 except Exception:
366 except Exception:
367 log.exception('Failed to read http scheme')
367 log.exception('Failed to read http scheme')
368 return 'http'
368 return 'http'
369
369
370 def _check_ssl(self, environ, start_response):
370 def _check_ssl(self, environ, start_response):
371 """
371 """
372 Checks the SSL check flag and returns False if SSL is not present
372 Checks the SSL check flag and returns False if SSL is not present
373 and required True otherwise
373 and required True otherwise
374 """
374 """
375 org_proto = environ['wsgi._org_proto']
375 org_proto = environ['wsgi._org_proto']
376 # check if we have SSL required ! if not it's a bad request !
376 # check if we have SSL required ! if not it's a bad request !
377 require_ssl = str2bool(self.repo_vcs_config.get('web', 'push_ssl'))
377 require_ssl = str2bool(self.repo_vcs_config.get('web', 'push_ssl'))
378 if require_ssl and org_proto == 'http':
378 if require_ssl and org_proto == 'http':
379 log.debug(
379 log.debug(
380 'Bad request: detected protocol is `%s` and '
380 'Bad request: detected protocol is `%s` and '
381 'SSL/HTTPS is required.', org_proto)
381 'SSL/HTTPS is required.', org_proto)
382 return False
382 return False
383 return True
383 return True
384
384
385 def _get_default_cache_ttl(self):
385 def _get_default_cache_ttl(self):
386 # take AUTH_CACHE_TTL from the `rhodecode` auth plugin
386 # take AUTH_CACHE_TTL from the `rhodecode` auth plugin
387 plugin = loadplugin('egg:rhodecode-enterprise-ce#rhodecode')
387 plugin = loadplugin('egg:rhodecode-enterprise-ce#rhodecode')
388 plugin_settings = plugin.get_settings()
388 plugin_settings = plugin.get_settings()
389 plugin_cache_active, cache_ttl = plugin.get_ttl_cache(
389 plugin_cache_active, cache_ttl = plugin.get_ttl_cache(
390 plugin_settings) or (False, 0)
390 plugin_settings) or (False, 0)
391 return plugin_cache_active, cache_ttl
391 return plugin_cache_active, cache_ttl
392
392
393 def __call__(self, environ, start_response):
393 def __call__(self, environ, start_response):
394 try:
394 try:
395 return self._handle_request(environ, start_response)
395 return self._handle_request(environ, start_response)
396 except Exception:
396 except Exception:
397 log.exception("Exception while handling request")
397 log.exception("Exception while handling request")
398 appenlight.track_exception(environ)
398 appenlight.track_exception(environ)
399 return HTTPInternalServerError()(environ, start_response)
399 return HTTPInternalServerError()(environ, start_response)
400 finally:
400 finally:
401 meta.Session.remove()
401 meta.Session.remove()
402
402
403 def _handle_request(self, environ, start_response):
403 def _handle_request(self, environ, start_response):
404 if not self._check_ssl(environ, start_response):
404 if not self._check_ssl(environ, start_response):
405 reason = ('SSL required, while RhodeCode was unable '
405 reason = ('SSL required, while RhodeCode was unable '
406 'to detect this as SSL request')
406 'to detect this as SSL request')
407 log.debug('User not allowed to proceed, %s', reason)
407 log.debug('User not allowed to proceed, %s', reason)
408 return HTTPNotAcceptable(reason)(environ, start_response)
408 return HTTPNotAcceptable(reason)(environ, start_response)
409
409
410 if not self.url_repo_name:
410 if not self.url_repo_name:
411 log.warning('Repository name is empty: %s', self.url_repo_name)
411 log.warning('Repository name is empty: %s', self.url_repo_name)
412 # failed to get repo name, we fail now
412 # failed to get repo name, we fail now
413 return HTTPNotFound()(environ, start_response)
413 return HTTPNotFound()(environ, start_response)
414 log.debug('Extracted repo name is %s', self.url_repo_name)
414 log.debug('Extracted repo name is %s', self.url_repo_name)
415
415
416 ip_addr = get_ip_addr(environ)
416 ip_addr = get_ip_addr(environ)
417 user_agent = get_user_agent(environ)
417 user_agent = get_user_agent(environ)
418 username = None
418 username = None
419
419
420 # skip passing error to error controller
420 # skip passing error to error controller
421 environ['pylons.status_code_redirect'] = True
421 environ['pylons.status_code_redirect'] = True
422
422
423 # ======================================================================
423 # ======================================================================
424 # GET ACTION PULL or PUSH
424 # GET ACTION PULL or PUSH
425 # ======================================================================
425 # ======================================================================
426 action = self._get_action(environ)
426 action = self._get_action(environ)
427
427
428 # ======================================================================
428 # ======================================================================
429 # Check if this is a request to a shadow repository of a pull request.
429 # Check if this is a request to a shadow repository of a pull request.
430 # In this case only pull action is allowed.
430 # In this case only pull action is allowed.
431 # ======================================================================
431 # ======================================================================
432 if self.is_shadow_repo and action != 'pull':
432 if self.is_shadow_repo and action != 'pull':
433 reason = 'Only pull action is allowed for shadow repositories.'
433 reason = 'Only pull action is allowed for shadow repositories.'
434 log.debug('User not allowed to proceed, %s', reason)
434 log.debug('User not allowed to proceed, %s', reason)
435 return HTTPNotAcceptable(reason)(environ, start_response)
435 return HTTPNotAcceptable(reason)(environ, start_response)
436
436
437 # Check if the shadow repo actually exists, in case someone refers
437 # Check if the shadow repo actually exists, in case someone refers
438 # to it, and it has been deleted because of successful merge.
438 # to it, and it has been deleted because of successful merge.
439 if self.is_shadow_repo and not self.is_shadow_repo_dir:
439 if self.is_shadow_repo and not self.is_shadow_repo_dir:
440 log.debug(
440 log.debug(
441 'Shadow repo detected, and shadow repo dir `%s` is missing',
441 'Shadow repo detected, and shadow repo dir `%s` is missing',
442 self.is_shadow_repo_dir)
442 self.is_shadow_repo_dir)
443 return HTTPNotFound()(environ, start_response)
443 return HTTPNotFound()(environ, start_response)
444
444
445 # ======================================================================
445 # ======================================================================
446 # CHECK ANONYMOUS PERMISSION
446 # CHECK ANONYMOUS PERMISSION
447 # ======================================================================
447 # ======================================================================
448 detect_force_push = False
448 detect_force_push = False
449 check_branch_perms = False
449 check_branch_perms = False
450 if action in ['pull', 'push']:
450 if action in ['pull', 'push']:
451 user_obj = anonymous_user = User.get_default_user()
451 user_obj = anonymous_user = User.get_default_user()
452 auth_user = user_obj.AuthUser()
452 auth_user = user_obj.AuthUser()
453 username = anonymous_user.username
453 username = anonymous_user.username
454 if anonymous_user.active:
454 if anonymous_user.active:
455 plugin_cache_active, cache_ttl = self._get_default_cache_ttl()
455 plugin_cache_active, cache_ttl = self._get_default_cache_ttl()
456 # ONLY check permissions if the user is activated
456 # ONLY check permissions if the user is activated
457 anonymous_perm = self._check_permission(
457 anonymous_perm = self._check_permission(
458 action, anonymous_user, auth_user, self.acl_repo_name, ip_addr,
458 action, anonymous_user, auth_user, self.acl_repo_name, ip_addr,
459 plugin_id='anonymous_access',
459 plugin_id='anonymous_access',
460 plugin_cache_active=plugin_cache_active,
460 plugin_cache_active=plugin_cache_active,
461 cache_ttl=cache_ttl,
461 cache_ttl=cache_ttl,
462 )
462 )
463 else:
463 else:
464 anonymous_perm = False
464 anonymous_perm = False
465
465
466 if not anonymous_user.active or not anonymous_perm:
466 if not anonymous_user.active or not anonymous_perm:
467 if not anonymous_user.active:
467 if not anonymous_user.active:
468 log.debug('Anonymous access is disabled, running '
468 log.debug('Anonymous access is disabled, running '
469 'authentication')
469 'authentication')
470
470
471 if not anonymous_perm:
471 if not anonymous_perm:
472 log.debug('Not enough credentials to access this '
472 log.debug('Not enough credentials to access this '
473 'repository as anonymous user')
473 'repository as anonymous user')
474
474
475 username = None
475 username = None
476 # ==============================================================
476 # ==============================================================
477 # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE
477 # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE
478 # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
478 # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
479 # ==============================================================
479 # ==============================================================
480
480
481 # try to auth based on environ, container auth methods
481 # try to auth based on environ, container auth methods
482 log.debug('Running PRE-AUTH for container based authentication')
482 log.debug('Running PRE-AUTH for container based authentication')
483 pre_auth = authenticate(
483 pre_auth = authenticate(
484 '', '', environ, VCS_TYPE, registry=self.registry,
484 '', '', environ, VCS_TYPE, registry=self.registry,
485 acl_repo_name=self.acl_repo_name)
485 acl_repo_name=self.acl_repo_name)
486 if pre_auth and pre_auth.get('username'):
486 if pre_auth and pre_auth.get('username'):
487 username = pre_auth['username']
487 username = pre_auth['username']
488 log.debug('PRE-AUTH got %s as username', username)
488 log.debug('PRE-AUTH got %s as username', username)
489 if pre_auth:
489 if pre_auth:
490 log.debug('PRE-AUTH successful from %s',
490 log.debug('PRE-AUTH successful from %s',
491 pre_auth.get('auth_data', {}).get('_plugin'))
491 pre_auth.get('auth_data', {}).get('_plugin'))
492
492
493 # If not authenticated by the container, running basic auth
493 # If not authenticated by the container, running basic auth
494 # before inject the calling repo_name for special scope checks
494 # before inject the calling repo_name for special scope checks
495 self.authenticate.acl_repo_name = self.acl_repo_name
495 self.authenticate.acl_repo_name = self.acl_repo_name
496
496
497 plugin_cache_active, cache_ttl = False, 0
497 plugin_cache_active, cache_ttl = False, 0
498 plugin = None
498 plugin = None
499 if not username:
499 if not username:
500 self.authenticate.realm = self.authenticate.get_rc_realm()
500 self.authenticate.realm = self.authenticate.get_rc_realm()
501
501
502 try:
502 try:
503 auth_result = self.authenticate(environ)
503 auth_result = self.authenticate(environ)
504 except (UserCreationError, NotAllowedToCreateUserError) as e:
504 except (UserCreationError, NotAllowedToCreateUserError) as e:
505 log.error(e)
505 log.error(e)
506 reason = safe_str(e)
506 reason = safe_str(e)
507 return HTTPNotAcceptable(reason)(environ, start_response)
507 return HTTPNotAcceptable(reason)(environ, start_response)
508
508
509 if isinstance(auth_result, dict):
509 if isinstance(auth_result, dict):
510 AUTH_TYPE.update(environ, 'basic')
510 AUTH_TYPE.update(environ, 'basic')
511 REMOTE_USER.update(environ, auth_result['username'])
511 REMOTE_USER.update(environ, auth_result['username'])
512 username = auth_result['username']
512 username = auth_result['username']
513 plugin = auth_result.get('auth_data', {}).get('_plugin')
513 plugin = auth_result.get('auth_data', {}).get('_plugin')
514 log.info(
514 log.info(
515 'MAIN-AUTH successful for user `%s` from %s plugin',
515 'MAIN-AUTH successful for user `%s` from %s plugin',
516 username, plugin)
516 username, plugin)
517
517
518 plugin_cache_active, cache_ttl = auth_result.get(
518 plugin_cache_active, cache_ttl = auth_result.get(
519 'auth_data', {}).get('_ttl_cache') or (False, 0)
519 'auth_data', {}).get('_ttl_cache') or (False, 0)
520 else:
520 else:
521 return auth_result.wsgi_application(environ, start_response)
521 return auth_result.wsgi_application(environ, start_response)
522
522
523 # ==============================================================
523 # ==============================================================
524 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME
524 # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME
525 # ==============================================================
525 # ==============================================================
526 user = User.get_by_username(username)
526 user = User.get_by_username(username)
527 if not self.valid_and_active_user(user):
527 if not self.valid_and_active_user(user):
528 return HTTPForbidden()(environ, start_response)
528 return HTTPForbidden()(environ, start_response)
529 username = user.username
529 username = user.username
530 user_id = user.user_id
530 user_id = user.user_id
531
531
532 # check user attributes for password change flag
532 # check user attributes for password change flag
533 user_obj = user
533 user_obj = user
534 auth_user = user_obj.AuthUser()
534 auth_user = user_obj.AuthUser()
535 if user_obj and user_obj.username != User.DEFAULT_USER and \
535 if user_obj and user_obj.username != User.DEFAULT_USER and \
536 user_obj.user_data.get('force_password_change'):
536 user_obj.user_data.get('force_password_change'):
537 reason = 'password change required'
537 reason = 'password change required'
538 log.debug('User not allowed to authenticate, %s', reason)
538 log.debug('User not allowed to authenticate, %s', reason)
539 return HTTPNotAcceptable(reason)(environ, start_response)
539 return HTTPNotAcceptable(reason)(environ, start_response)
540
540
541 # check permissions for this repository
541 # check permissions for this repository
542 perm = self._check_permission(
542 perm = self._check_permission(
543 action, user, auth_user, self.acl_repo_name, ip_addr,
543 action, user, auth_user, self.acl_repo_name, ip_addr,
544 plugin, plugin_cache_active, cache_ttl)
544 plugin, plugin_cache_active, cache_ttl)
545 if not perm:
545 if not perm:
546 return HTTPForbidden()(environ, start_response)
546 return HTTPForbidden()(environ, start_response)
547 environ['rc_auth_user_id'] = user_id
547 environ['rc_auth_user_id'] = user_id
548
548
549 if action == 'push':
549 if action == 'push':
550 perms = auth_user.get_branch_permissions(self.acl_repo_name)
550 perms = auth_user.get_branch_permissions(self.acl_repo_name)
551 if perms:
551 if perms:
552 check_branch_perms = True
552 check_branch_perms = True
553 detect_force_push = True
553 detect_force_push = True
554
554
555 # extras are injected into UI object and later available
555 # extras are injected into UI object and later available
556 # in hooks executed by RhodeCode
556 # in hooks executed by RhodeCode
557 check_locking = _should_check_locking(environ.get('QUERY_STRING'))
557 check_locking = _should_check_locking(environ.get('QUERY_STRING'))
558
558
559 extras = vcs_operation_context(
559 extras = vcs_operation_context(
560 environ, repo_name=self.acl_repo_name, username=username,
560 environ, repo_name=self.acl_repo_name, username=username,
561 action=action, scm=self.SCM, check_locking=check_locking,
561 action=action, scm=self.SCM, check_locking=check_locking,
562 is_shadow_repo=self.is_shadow_repo, check_branch_perms=check_branch_perms,
562 is_shadow_repo=self.is_shadow_repo, check_branch_perms=check_branch_perms,
563 detect_force_push=detect_force_push
563 detect_force_push=detect_force_push
564 )
564 )
565
565
566 # ======================================================================
566 # ======================================================================
567 # REQUEST HANDLING
567 # REQUEST HANDLING
568 # ======================================================================
568 # ======================================================================
569 repo_path = os.path.join(
569 repo_path = os.path.join(
570 safe_str(self.base_path), safe_str(self.vcs_repo_name))
570 safe_str(self.base_path), safe_str(self.vcs_repo_name))
571 log.debug('Repository path is %s', repo_path)
571 log.debug('Repository path is %s', repo_path)
572
572
573 fix_PATH()
573 fix_PATH()
574
574
575 log.info(
575 log.info(
576 '%s action on %s repo "%s" by "%s" from %s %s',
576 '%s action on %s repo "%s" by "%s" from %s %s',
577 action, self.SCM, safe_str(self.url_repo_name),
577 action, self.SCM, safe_str(self.url_repo_name),
578 safe_str(username), ip_addr, user_agent)
578 safe_str(username), ip_addr, user_agent)
579
579
580 return self._generate_vcs_response(
580 return self._generate_vcs_response(
581 environ, start_response, repo_path, extras, action)
581 environ, start_response, repo_path, extras, action)
582
582
583 @initialize_generator
583 @initialize_generator
584 def _generate_vcs_response(
584 def _generate_vcs_response(
585 self, environ, start_response, repo_path, extras, action):
585 self, environ, start_response, repo_path, extras, action):
586 """
586 """
587 Returns a generator for the response content.
587 Returns a generator for the response content.
588
588
589 This method is implemented as a generator, so that it can trigger
589 This method is implemented as a generator, so that it can trigger
590 the cache validation after all content sent back to the client. It
590 the cache validation after all content sent back to the client. It
591 also handles the locking exceptions which will be triggered when
591 also handles the locking exceptions which will be triggered when
592 the first chunk is produced by the underlying WSGI application.
592 the first chunk is produced by the underlying WSGI application.
593 """
593 """
594 txn_id = ''
594 txn_id = ''
595 if 'CONTENT_LENGTH' in environ and environ['REQUEST_METHOD'] == 'MERGE':
595 if 'CONTENT_LENGTH' in environ and environ['REQUEST_METHOD'] == 'MERGE':
596 # case for SVN, we want to re-use the callback daemon port
596 # case for SVN, we want to re-use the callback daemon port
597 # so we use the txn_id, for this we peek the body, and still save
597 # so we use the txn_id, for this we peek the body, and still save
598 # it as wsgi.input
598 # it as wsgi.input
599 data = environ['wsgi.input'].read()
599 data = environ['wsgi.input'].read()
600 environ['wsgi.input'] = StringIO(data)
600 environ['wsgi.input'] = StringIO(data)
601 txn_id = extract_svn_txn_id(self.acl_repo_name, data)
601 txn_id = extract_svn_txn_id(self.acl_repo_name, data)
602
602
603 callback_daemon, extras = self._prepare_callback_daemon(
603 callback_daemon, extras = self._prepare_callback_daemon(
604 extras, environ, action, txn_id=txn_id)
604 extras, environ, action, txn_id=txn_id)
605 log.debug('HOOKS extras is %s', extras)
605 log.debug('HOOKS extras is %s', extras)
606
606
607 http_scheme = self._get_http_scheme(environ)
607 http_scheme = self._get_http_scheme(environ)
608
608
609 config = self._create_config(extras, self.acl_repo_name, scheme=http_scheme)
609 config = self._create_config(extras, self.acl_repo_name, scheme=http_scheme)
610 app = self._create_wsgi_app(repo_path, self.url_repo_name, config)
610 app = self._create_wsgi_app(repo_path, self.url_repo_name, config)
611 with callback_daemon:
611 with callback_daemon:
612 app.rc_extras = extras
612 app.rc_extras = extras
613
613
614 try:
614 try:
615 response = app(environ, start_response)
615 response = app(environ, start_response)
616 finally:
616 finally:
617 # This statement works together with the decorator
617 # This statement works together with the decorator
618 # "initialize_generator" above. The decorator ensures that
618 # "initialize_generator" above. The decorator ensures that
619 # we hit the first yield statement before the generator is
619 # we hit the first yield statement before the generator is
620 # returned back to the WSGI server. This is needed to
620 # returned back to the WSGI server. This is needed to
621 # ensure that the call to "app" above triggers the
621 # ensure that the call to "app" above triggers the
622 # needed callback to "start_response" before the
622 # needed callback to "start_response" before the
623 # generator is actually used.
623 # generator is actually used.
624 yield "__init__"
624 yield "__init__"
625
625
626 # iter content
626 # iter content
627 for chunk in response:
627 for chunk in response:
628 yield chunk
628 yield chunk
629
629
630 try:
630 try:
631 # invalidate cache on push
631 # invalidate cache on push
632 if action == 'push':
632 if action == 'push':
633 self._invalidate_cache(self.url_repo_name)
633 self._invalidate_cache(self.url_repo_name)
634 finally:
634 finally:
635 meta.Session.remove()
635 meta.Session.remove()
636
636
637 def _get_repository_name(self, environ):
637 def _get_repository_name(self, environ):
638 """Get repository name out of the environmnent
638 """Get repository name out of the environmnent
639
639
640 :param environ: WSGI environment
640 :param environ: WSGI environment
641 """
641 """
642 raise NotImplementedError()
642 raise NotImplementedError()
643
643
644 def _get_action(self, environ):
644 def _get_action(self, environ):
645 """Map request commands into a pull or push command.
645 """Map request commands into a pull or push command.
646
646
647 :param environ: WSGI environment
647 :param environ: WSGI environment
648 """
648 """
649 raise NotImplementedError()
649 raise NotImplementedError()
650
650
651 def _create_wsgi_app(self, repo_path, repo_name, config):
651 def _create_wsgi_app(self, repo_path, repo_name, config):
652 """Return the WSGI app that will finally handle the request."""
652 """Return the WSGI app that will finally handle the request."""
653 raise NotImplementedError()
653 raise NotImplementedError()
654
654
655 def _create_config(self, extras, repo_name, scheme='http'):
655 def _create_config(self, extras, repo_name, scheme='http'):
656 """Create a safe config representation."""
656 """Create a safe config representation."""
657 raise NotImplementedError()
657 raise NotImplementedError()
658
658
659 def _should_use_callback_daemon(self, extras, environ, action):
659 def _should_use_callback_daemon(self, extras, environ, action):
660 return True
660 return True
661
661
662 def _prepare_callback_daemon(self, extras, environ, action, txn_id=None):
662 def _prepare_callback_daemon(self, extras, environ, action, txn_id=None):
663 direct_calls = vcs_settings.HOOKS_DIRECT_CALLS
663 direct_calls = vcs_settings.HOOKS_DIRECT_CALLS
664 if not self._should_use_callback_daemon(extras, environ, action):
664 if not self._should_use_callback_daemon(extras, environ, action):
665 # disable callback daemon for actions that don't require it
665 # disable callback daemon for actions that don't require it
666 direct_calls = True
666 direct_calls = True
667
667
668 return prepare_callback_daemon(
668 return prepare_callback_daemon(
669 extras, protocol=vcs_settings.HOOKS_PROTOCOL,
669 extras, protocol=vcs_settings.HOOKS_PROTOCOL,
670 host=vcs_settings.HOOKS_HOST, use_direct_calls=direct_calls, txn_id=txn_id)
670 host=vcs_settings.HOOKS_HOST, use_direct_calls=direct_calls, txn_id=txn_id)
671
671
672
672
673 def _should_check_locking(query_string):
673 def _should_check_locking(query_string):
674 # this is kind of hacky, but due to how mercurial handles client-server
674 # this is kind of hacky, but due to how mercurial handles client-server
675 # server see all operation on commit; bookmarks, phases and
675 # server see all operation on commit; bookmarks, phases and
676 # obsolescence marker in different transaction, we don't want to check
676 # obsolescence marker in different transaction, we don't want to check
677 # locking on those
677 # locking on those
678 return query_string not in ['cmd=listkeys']
678 return query_string not in ['cmd=listkeys']
@@ -1,338 +1,339 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2015-2019 RhodeCode GmbH
3 # Copyright (C) 2015-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 import os
20 import os
21 import time
21 import time
22 import logging
22 import logging
23 import functools
23 import functools
24 import threading
24 import threading
25
25
26 from dogpile.cache import CacheRegion
26 from dogpile.cache import CacheRegion
27 from dogpile.cache.util import compat
27 from dogpile.cache.util import compat
28
28
29 import rhodecode
29 import rhodecode
30 from rhodecode.lib.utils import safe_str, sha1
30 from rhodecode.lib.utils import safe_str, sha1
31 from rhodecode.lib.utils2 import safe_unicode, str2bool
31 from rhodecode.lib.utils2 import safe_unicode, str2bool
32 from rhodecode.model.db import Session, CacheKey, IntegrityError
32 from rhodecode.model.db import Session, CacheKey, IntegrityError
33
33
34 from . import region_meta
34 from . import region_meta
35
35
36 log = logging.getLogger(__name__)
36 log = logging.getLogger(__name__)
37
37
38
38
39 class RhodeCodeCacheRegion(CacheRegion):
39 class RhodeCodeCacheRegion(CacheRegion):
40
40
41 def conditional_cache_on_arguments(
41 def conditional_cache_on_arguments(
42 self, namespace=None,
42 self, namespace=None,
43 expiration_time=None,
43 expiration_time=None,
44 should_cache_fn=None,
44 should_cache_fn=None,
45 to_str=compat.string_type,
45 to_str=compat.string_type,
46 function_key_generator=None,
46 function_key_generator=None,
47 condition=True):
47 condition=True):
48 """
48 """
49 Custom conditional decorator, that will not touch any dogpile internals if
49 Custom conditional decorator, that will not touch any dogpile internals if
50 condition isn't meet. This works a bit different than should_cache_fn
50 condition isn't meet. This works a bit different than should_cache_fn
51 And it's faster in cases we don't ever want to compute cached values
51 And it's faster in cases we don't ever want to compute cached values
52 """
52 """
53 expiration_time_is_callable = compat.callable(expiration_time)
53 expiration_time_is_callable = compat.callable(expiration_time)
54
54
55 if function_key_generator is None:
55 if function_key_generator is None:
56 function_key_generator = self.function_key_generator
56 function_key_generator = self.function_key_generator
57
57
58 def decorator(fn):
58 def decorator(fn):
59 if to_str is compat.string_type:
59 if to_str is compat.string_type:
60 # backwards compatible
60 # backwards compatible
61 key_generator = function_key_generator(namespace, fn)
61 key_generator = function_key_generator(namespace, fn)
62 else:
62 else:
63 key_generator = function_key_generator(namespace, fn, to_str=to_str)
63 key_generator = function_key_generator(namespace, fn, to_str=to_str)
64
64
65 @functools.wraps(fn)
65 @functools.wraps(fn)
66 def decorate(*arg, **kw):
66 def decorate(*arg, **kw):
67 key = key_generator(*arg, **kw)
67 key = key_generator(*arg, **kw)
68
68
69 @functools.wraps(fn)
69 @functools.wraps(fn)
70 def creator():
70 def creator():
71 return fn(*arg, **kw)
71 return fn(*arg, **kw)
72
72
73 if not condition:
73 if not condition:
74 return creator()
74 return creator()
75
75
76 timeout = expiration_time() if expiration_time_is_callable \
76 timeout = expiration_time() if expiration_time_is_callable \
77 else expiration_time
77 else expiration_time
78
78
79 return self.get_or_create(key, creator, timeout, should_cache_fn)
79 return self.get_or_create(key, creator, timeout, should_cache_fn)
80
80
81 def invalidate(*arg, **kw):
81 def invalidate(*arg, **kw):
82 key = key_generator(*arg, **kw)
82 key = key_generator(*arg, **kw)
83 self.delete(key)
83 self.delete(key)
84
84
85 def set_(value, *arg, **kw):
85 def set_(value, *arg, **kw):
86 key = key_generator(*arg, **kw)
86 key = key_generator(*arg, **kw)
87 self.set(key, value)
87 self.set(key, value)
88
88
89 def get(*arg, **kw):
89 def get(*arg, **kw):
90 key = key_generator(*arg, **kw)
90 key = key_generator(*arg, **kw)
91 return self.get(key)
91 return self.get(key)
92
92
93 def refresh(*arg, **kw):
93 def refresh(*arg, **kw):
94 key = key_generator(*arg, **kw)
94 key = key_generator(*arg, **kw)
95 value = fn(*arg, **kw)
95 value = fn(*arg, **kw)
96 self.set(key, value)
96 self.set(key, value)
97 return value
97 return value
98
98
99 decorate.set = set_
99 decorate.set = set_
100 decorate.invalidate = invalidate
100 decorate.invalidate = invalidate
101 decorate.refresh = refresh
101 decorate.refresh = refresh
102 decorate.get = get
102 decorate.get = get
103 decorate.original = fn
103 decorate.original = fn
104 decorate.key_generator = key_generator
104 decorate.key_generator = key_generator
105 decorate.__wrapped__ = fn
105 decorate.__wrapped__ = fn
106
106
107 return decorate
107 return decorate
108
108
109 return decorator
109 return decorator
110
110
111
111
112 def make_region(*arg, **kw):
112 def make_region(*arg, **kw):
113 return RhodeCodeCacheRegion(*arg, **kw)
113 return RhodeCodeCacheRegion(*arg, **kw)
114
114
115
115
116 def get_default_cache_settings(settings, prefixes=None):
116 def get_default_cache_settings(settings, prefixes=None):
117 prefixes = prefixes or []
117 prefixes = prefixes or []
118 cache_settings = {}
118 cache_settings = {}
119 for key in settings.keys():
119 for key in settings.keys():
120 for prefix in prefixes:
120 for prefix in prefixes:
121 if key.startswith(prefix):
121 if key.startswith(prefix):
122 name = key.split(prefix)[1].strip()
122 name = key.split(prefix)[1].strip()
123 val = settings[key]
123 val = settings[key]
124 if isinstance(val, compat.string_types):
124 if isinstance(val, compat.string_types):
125 val = val.strip()
125 val = val.strip()
126 cache_settings[name] = val
126 cache_settings[name] = val
127 return cache_settings
127 return cache_settings
128
128
129
129
130 def compute_key_from_params(*args):
130 def compute_key_from_params(*args):
131 """
131 """
132 Helper to compute key from given params to be used in cache manager
132 Helper to compute key from given params to be used in cache manager
133 """
133 """
134 return sha1("_".join(map(safe_str, args)))
134 return sha1("_".join(map(safe_str, args)))
135
135
136
136
137 def backend_key_generator(backend):
137 def backend_key_generator(backend):
138 """
138 """
139 Special wrapper that also sends over the backend to the key generator
139 Special wrapper that also sends over the backend to the key generator
140 """
140 """
141 def wrapper(namespace, fn):
141 def wrapper(namespace, fn):
142 return key_generator(backend, namespace, fn)
142 return key_generator(backend, namespace, fn)
143 return wrapper
143 return wrapper
144
144
145
145
146 def key_generator(backend, namespace, fn):
146 def key_generator(backend, namespace, fn):
147 fname = fn.__name__
147 fname = fn.__name__
148
148
149 def generate_key(*args):
149 def generate_key(*args):
150 backend_prefix = getattr(backend, 'key_prefix', None) or 'backend_prefix'
150 backend_prefix = getattr(backend, 'key_prefix', None) or 'backend_prefix'
151 namespace_pref = namespace or 'default_namespace'
151 namespace_pref = namespace or 'default_namespace'
152 arg_key = compute_key_from_params(*args)
152 arg_key = compute_key_from_params(*args)
153 final_key = "{}:{}:{}_{}".format(backend_prefix, namespace_pref, fname, arg_key)
153 final_key = "{}:{}:{}_{}".format(backend_prefix, namespace_pref, fname, arg_key)
154
154
155 return final_key
155 return final_key
156
156
157 return generate_key
157 return generate_key
158
158
159
159
160 def get_or_create_region(region_name, region_namespace=None):
160 def get_or_create_region(region_name, region_namespace=None):
161 from rhodecode.lib.rc_cache.backends import FileNamespaceBackend
161 from rhodecode.lib.rc_cache.backends import FileNamespaceBackend
162 region_obj = region_meta.dogpile_cache_regions.get(region_name)
162 region_obj = region_meta.dogpile_cache_regions.get(region_name)
163 if not region_obj:
163 if not region_obj:
164 raise EnvironmentError(
164 raise EnvironmentError(
165 'Region `{}` not in configured: {}.'.format(
165 'Region `{}` not in configured: {}.'.format(
166 region_name, region_meta.dogpile_cache_regions.keys()))
166 region_name, region_meta.dogpile_cache_regions.keys()))
167
167
168 region_uid_name = '{}:{}'.format(region_name, region_namespace)
168 region_uid_name = '{}:{}'.format(region_name, region_namespace)
169 if isinstance(region_obj.actual_backend, FileNamespaceBackend):
169 if isinstance(region_obj.actual_backend, FileNamespaceBackend):
170 region_exist = region_meta.dogpile_cache_regions.get(region_namespace)
170 region_exist = region_meta.dogpile_cache_regions.get(region_namespace)
171 if region_exist:
171 if region_exist:
172 log.debug('Using already configured region: %s', region_namespace)
172 log.debug('Using already configured region: %s', region_namespace)
173 return region_exist
173 return region_exist
174 cache_dir = region_meta.dogpile_config_defaults['cache_dir']
174 cache_dir = region_meta.dogpile_config_defaults['cache_dir']
175 expiration_time = region_obj.expiration_time
175 expiration_time = region_obj.expiration_time
176
176
177 if not os.path.isdir(cache_dir):
177 if not os.path.isdir(cache_dir):
178 os.makedirs(cache_dir)
178 os.makedirs(cache_dir)
179 new_region = make_region(
179 new_region = make_region(
180 name=region_uid_name,
180 name=region_uid_name,
181 function_key_generator=backend_key_generator(region_obj.actual_backend)
181 function_key_generator=backend_key_generator(region_obj.actual_backend)
182 )
182 )
183 namespace_filename = os.path.join(
183 namespace_filename = os.path.join(
184 cache_dir, "{}.cache.dbm".format(region_namespace))
184 cache_dir, "{}.cache.dbm".format(region_namespace))
185 # special type that allows 1db per namespace
185 # special type that allows 1db per namespace
186 new_region.configure(
186 new_region.configure(
187 backend='dogpile.cache.rc.file_namespace',
187 backend='dogpile.cache.rc.file_namespace',
188 expiration_time=expiration_time,
188 expiration_time=expiration_time,
189 arguments={"filename": namespace_filename}
189 arguments={"filename": namespace_filename}
190 )
190 )
191
191
192 # create and save in region caches
192 # create and save in region caches
193 log.debug('configuring new region: %s', region_uid_name)
193 log.debug('configuring new region: %s', region_uid_name)
194 region_obj = region_meta.dogpile_cache_regions[region_namespace] = new_region
194 region_obj = region_meta.dogpile_cache_regions[region_namespace] = new_region
195
195
196 return region_obj
196 return region_obj
197
197
198
198
199 def clear_cache_namespace(cache_region, cache_namespace_uid):
199 def clear_cache_namespace(cache_region, cache_namespace_uid):
200 region = get_or_create_region(cache_region, cache_namespace_uid)
200 region = get_or_create_region(cache_region, cache_namespace_uid)
201 cache_keys = region.backend.list_keys(prefix=cache_namespace_uid)
201 cache_keys = region.backend.list_keys(prefix=cache_namespace_uid)
202 num_delete_keys = len(cache_keys)
202 num_delete_keys = len(cache_keys)
203 if num_delete_keys:
203 if num_delete_keys:
204 region.delete_multi(cache_keys)
204 region.delete_multi(cache_keys)
205 return num_delete_keys
205 return num_delete_keys
206
206
207
207
208 class ActiveRegionCache(object):
208 class ActiveRegionCache(object):
209 def __init__(self, context, cache_data):
209 def __init__(self, context, cache_data):
210 self.context = context
210 self.context = context
211 self.cache_data = cache_data
211 self.cache_data = cache_data
212
212
213 def should_invalidate(self):
213 def should_invalidate(self):
214 return False
214 return False
215
215
216
216
217 class FreshRegionCache(object):
217 class FreshRegionCache(object):
218 def __init__(self, context, cache_data):
218 def __init__(self, context, cache_data):
219 self.context = context
219 self.context = context
220 self.cache_data = cache_data
220 self.cache_data = cache_data
221
221
222 def should_invalidate(self):
222 def should_invalidate(self):
223 return True
223 return True
224
224
225
225
226 class InvalidationContext(object):
226 class InvalidationContext(object):
227 """
227 """
228 usage::
228 usage::
229
229
230 from rhodecode.lib import rc_cache
230 from rhodecode.lib import rc_cache
231
231
232 cache_namespace_uid = CacheKey.SOME_NAMESPACE.format(1)
232 cache_namespace_uid = CacheKey.SOME_NAMESPACE.format(1)
233 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
233 region = rc_cache.get_or_create_region('cache_perms', cache_namespace_uid)
234
234
235 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid, condition=True)
235 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid, condition=True)
236 def heavy_compute(cache_name, param1, param2):
236 def heavy_compute(cache_name, param1, param2):
237 print('COMPUTE {}, {}, {}'.format(cache_name, param1, param2))
237 print('COMPUTE {}, {}, {}'.format(cache_name, param1, param2))
238
238
239 # invalidation namespace is shared namespace key for all process caches
239 # invalidation namespace is shared namespace key for all process caches
240 # we use it to send a global signal
240 # we use it to send a global signal
241 invalidation_namespace = 'repo_cache:1'
241 invalidation_namespace = 'repo_cache:1'
242
242
243 inv_context_manager = rc_cache.InvalidationContext(
243 inv_context_manager = rc_cache.InvalidationContext(
244 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace)
244 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace)
245 with inv_context_manager as invalidation_context:
245 with inv_context_manager as invalidation_context:
246 args = ('one', 'two')
246 args = ('one', 'two')
247 # re-compute and store cache if we get invalidate signal
247 # re-compute and store cache if we get invalidate signal
248 if invalidation_context.should_invalidate():
248 if invalidation_context.should_invalidate():
249 result = heavy_compute.refresh(*args)
249 result = heavy_compute.refresh(*args)
250 else:
250 else:
251 result = heavy_compute(*args)
251 result = heavy_compute(*args)
252
252
253 compute_time = inv_context_manager.compute_time
253 compute_time = inv_context_manager.compute_time
254 log.debug('result computed in %.3fs', compute_time)
254 log.debug('result computed in %.4fs', compute_time)
255
255
256 # To send global invalidation signal, simply run
256 # To send global invalidation signal, simply run
257 CacheKey.set_invalidate(invalidation_namespace)
257 CacheKey.set_invalidate(invalidation_namespace)
258
258
259 """
259 """
260
260
261 def __repr__(self):
261 def __repr__(self):
262 return '<InvalidationContext:{}[{}]>'.format(
262 return '<InvalidationContext:{}[{}]>'.format(
263 safe_str(self.cache_key), safe_str(self.uid))
263 safe_str(self.cache_key), safe_str(self.uid))
264
264
265 def __init__(self, uid, invalidation_namespace='',
265 def __init__(self, uid, invalidation_namespace='',
266 raise_exception=False, thread_scoped=None):
266 raise_exception=False, thread_scoped=None):
267 self.uid = uid
267 self.uid = uid
268 self.invalidation_namespace = invalidation_namespace
268 self.invalidation_namespace = invalidation_namespace
269 self.raise_exception = raise_exception
269 self.raise_exception = raise_exception
270 self.proc_id = safe_unicode(rhodecode.CONFIG.get('instance_id') or 'DEFAULT')
270 self.proc_id = safe_unicode(rhodecode.CONFIG.get('instance_id') or 'DEFAULT')
271 self.thread_id = 'global'
271 self.thread_id = 'global'
272
272
273 if thread_scoped is None:
273 if thread_scoped is None:
274 # if we set "default" we can override this via .ini settings
274 # if we set "default" we can override this via .ini settings
275 thread_scoped = str2bool(rhodecode.CONFIG.get('cache_thread_scoped'))
275 thread_scoped = str2bool(rhodecode.CONFIG.get('cache_thread_scoped'))
276
276
277 # Append the thread id to the cache key if this invalidation context
277 # Append the thread id to the cache key if this invalidation context
278 # should be scoped to the current thread.
278 # should be scoped to the current thread.
279 if thread_scoped is True:
279 if thread_scoped is True:
280 self.thread_id = threading.current_thread().ident
280 self.thread_id = threading.current_thread().ident
281
281
282 self.cache_key = compute_key_from_params(uid)
282 self.cache_key = compute_key_from_params(uid)
283 self.cache_key = 'proc:{}|thread:{}|params:{}'.format(
283 self.cache_key = 'proc:{}|thread:{}|params:{}'.format(
284 self.proc_id, self.thread_id, self.cache_key)
284 self.proc_id, self.thread_id, self.cache_key)
285 self.compute_time = 0
285 self.compute_time = 0
286
286
287 def get_or_create_cache_obj(self, uid, invalidation_namespace=''):
287 def get_or_create_cache_obj(self, uid, invalidation_namespace=''):
288 cache_obj = CacheKey.get_active_cache(self.cache_key)
288 cache_obj = CacheKey.get_active_cache(self.cache_key)
289 log.debug('Fetched cache obj %s using %s cache key.', cache_obj, self.cache_key)
289 log.debug('Fetched cache obj %s using %s cache key.', cache_obj, self.cache_key)
290 invalidation_namespace = invalidation_namespace or self.invalidation_namespace
290 invalidation_namespace = invalidation_namespace or self.invalidation_namespace
291 if not cache_obj:
291 if not cache_obj:
292 cache_obj = CacheKey(self.cache_key, cache_args=invalidation_namespace)
292 new_cache_args = invalidation_namespace
293 cache_obj = CacheKey(self.cache_key, cache_args=new_cache_args)
293 return cache_obj
294 return cache_obj
294
295
295 def __enter__(self):
296 def __enter__(self):
296 """
297 """
297 Test if current object is valid, and return CacheRegion function
298 Test if current object is valid, and return CacheRegion function
298 that does invalidation and calculation
299 that does invalidation and calculation
299 """
300 """
300 log.debug('Entering cache invalidation check context: %s', self.invalidation_namespace)
301 log.debug('Entering cache invalidation check context: %s', self.invalidation_namespace)
301 # register or get a new key based on uid
302 # register or get a new key based on uid
302 self.cache_obj = self.get_or_create_cache_obj(uid=self.uid)
303 self.cache_obj = self.get_or_create_cache_obj(uid=self.uid)
303 cache_data = self.cache_obj.get_dict()
304 cache_data = self.cache_obj.get_dict()
304 self._start_time = time.time()
305 self._start_time = time.time()
305 if self.cache_obj.cache_active:
306 if self.cache_obj.cache_active:
306 # means our cache obj is existing and marked as it's
307 # means our cache obj is existing and marked as it's
307 # cache is not outdated, we return ActiveRegionCache
308 # cache is not outdated, we return ActiveRegionCache
308 self.skip_cache_active_change = True
309 self.skip_cache_active_change = True
309
310
310 return ActiveRegionCache(context=self, cache_data=cache_data)
311 return ActiveRegionCache(context=self, cache_data=cache_data)
311
312
312 # the key is either not existing or set to False, we return
313 # the key is either not existing or set to False, we return
313 # the real invalidator which re-computes value. We additionally set
314 # the real invalidator which re-computes value. We additionally set
314 # the flag to actually update the Database objects
315 # the flag to actually update the Database objects
315 self.skip_cache_active_change = False
316 self.skip_cache_active_change = False
316 return FreshRegionCache(context=self, cache_data=cache_data)
317 return FreshRegionCache(context=self, cache_data=cache_data)
317
318
318 def __exit__(self, exc_type, exc_val, exc_tb):
319 def __exit__(self, exc_type, exc_val, exc_tb):
319 # save compute time
320 # save compute time
320 self.compute_time = time.time() - self._start_time
321 self.compute_time = time.time() - self._start_time
321
322
322 if self.skip_cache_active_change:
323 if self.skip_cache_active_change:
323 return
324 return
324
325
325 try:
326 try:
326 self.cache_obj.cache_active = True
327 self.cache_obj.cache_active = True
327 Session().add(self.cache_obj)
328 Session().add(self.cache_obj)
328 Session().commit()
329 Session().commit()
329 except IntegrityError:
330 except IntegrityError:
330 # if we catch integrity error, it means we inserted this object
331 # if we catch integrity error, it means we inserted this object
331 # assumption is that's really an edge race-condition case and
332 # assumption is that's really an edge race-condition case and
332 # it's safe is to skip it
333 # it's safe is to skip it
333 Session().rollback()
334 Session().rollback()
334 except Exception:
335 except Exception:
335 log.exception('Failed to commit on cache key update')
336 log.exception('Failed to commit on cache key update')
336 Session().rollback()
337 Session().rollback()
337 if self.raise_exception:
338 if self.raise_exception:
338 raise
339 raise
@@ -1,506 +1,507 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2014-2019 RhodeCode GmbH
3 # Copyright (C) 2014-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 GIT commit module
22 GIT commit module
23 """
23 """
24
24
25 import re
25 import re
26 import stat
26 import stat
27 from itertools import chain
27 from itertools import chain
28 from StringIO import StringIO
28 from StringIO import StringIO
29
29
30 from zope.cachedescriptors.property import Lazy as LazyProperty
30 from zope.cachedescriptors.property import Lazy as LazyProperty
31
31
32 from rhodecode.lib.datelib import utcdate_fromtimestamp
32 from rhodecode.lib.datelib import utcdate_fromtimestamp
33 from rhodecode.lib.utils import safe_unicode, safe_str
33 from rhodecode.lib.utils import safe_unicode, safe_str
34 from rhodecode.lib.utils2 import safe_int
34 from rhodecode.lib.utils2 import safe_int
35 from rhodecode.lib.vcs.conf import settings
35 from rhodecode.lib.vcs.conf import settings
36 from rhodecode.lib.vcs.backends import base
36 from rhodecode.lib.vcs.backends import base
37 from rhodecode.lib.vcs.exceptions import CommitError, NodeDoesNotExistError
37 from rhodecode.lib.vcs.exceptions import CommitError, NodeDoesNotExistError
38 from rhodecode.lib.vcs.nodes import (
38 from rhodecode.lib.vcs.nodes import (
39 FileNode, DirNode, NodeKind, RootNode, SubModuleNode,
39 FileNode, DirNode, NodeKind, RootNode, SubModuleNode,
40 ChangedFileNodesGenerator, AddedFileNodesGenerator,
40 ChangedFileNodesGenerator, AddedFileNodesGenerator,
41 RemovedFileNodesGenerator, LargeFileNode)
41 RemovedFileNodesGenerator, LargeFileNode)
42 from rhodecode.lib.vcs.compat import configparser
42 from rhodecode.lib.vcs.compat import configparser
43
43
44
44
45 class GitCommit(base.BaseCommit):
45 class GitCommit(base.BaseCommit):
46 """
46 """
47 Represents state of the repository at single commit id.
47 Represents state of the repository at single commit id.
48 """
48 """
49
49
50 _filter_pre_load = [
50 _filter_pre_load = [
51 # done through a more complex tree walk on parents
51 # done through a more complex tree walk on parents
52 "affected_files",
52 "affected_files",
53 # done through subprocess not remote call
53 # done through subprocess not remote call
54 "children",
54 "children",
55 # done through a more complex tree walk on parents
55 # done through a more complex tree walk on parents
56 "status",
56 "status",
57 # mercurial specific property not supported here
57 # mercurial specific property not supported here
58 "_file_paths",
58 "_file_paths",
59 # mercurial specific property not supported here
59 # mercurial specific property not supported here
60 'obsolete',
60 'obsolete',
61 # mercurial specific property not supported here
61 # mercurial specific property not supported here
62 'phase',
62 'phase',
63 # mercurial specific property not supported here
63 # mercurial specific property not supported here
64 'hidden'
64 'hidden'
65 ]
65 ]
66
66
67 def __init__(self, repository, raw_id, idx, pre_load=None):
67 def __init__(self, repository, raw_id, idx, pre_load=None):
68 self.repository = repository
68 self.repository = repository
69 self._remote = repository._remote
69 self._remote = repository._remote
70 # TODO: johbo: Tweak of raw_id should not be necessary
70 # TODO: johbo: Tweak of raw_id should not be necessary
71 self.raw_id = safe_str(raw_id)
71 self.raw_id = safe_str(raw_id)
72 self.idx = idx
72 self.idx = idx
73
73
74 self._set_bulk_properties(pre_load)
74 self._set_bulk_properties(pre_load)
75
75
76 # caches
76 # caches
77 self._stat_modes = {} # stat info for paths
77 self._stat_modes = {} # stat info for paths
78 self._paths = {} # path processed with parse_tree
78 self._paths = {} # path processed with parse_tree
79 self.nodes = {}
79 self.nodes = {}
80 self._submodules = None
80 self._submodules = None
81
81
82 def _set_bulk_properties(self, pre_load):
82 def _set_bulk_properties(self, pre_load):
83
83
84 if not pre_load:
84 if not pre_load:
85 return
85 return
86 pre_load = [entry for entry in pre_load
86 pre_load = [entry for entry in pre_load
87 if entry not in self._filter_pre_load]
87 if entry not in self._filter_pre_load]
88 if not pre_load:
88 if not pre_load:
89 return
89 return
90
90
91 result = self._remote.bulk_request(self.raw_id, pre_load)
91 result = self._remote.bulk_request(self.raw_id, pre_load)
92 for attr, value in result.items():
92 for attr, value in result.items():
93 if attr in ["author", "message"]:
93 if attr in ["author", "message"]:
94 if value:
94 if value:
95 value = safe_unicode(value)
95 value = safe_unicode(value)
96 elif attr == "date":
96 elif attr == "date":
97 value = utcdate_fromtimestamp(*value)
97 value = utcdate_fromtimestamp(*value)
98 elif attr == "parents":
98 elif attr == "parents":
99 value = self._make_commits(value)
99 value = self._make_commits(value)
100 elif attr == "branch":
100 elif attr == "branch":
101 value = value[0] if value else None
101 value = value[0] if value else None
102 self.__dict__[attr] = value
102 self.__dict__[attr] = value
103
103
104 @LazyProperty
104 @LazyProperty
105 def _commit(self):
105 def _commit(self):
106 return self._remote[self.raw_id]
106 return self._remote[self.raw_id]
107
107
108 @LazyProperty
108 @LazyProperty
109 def _tree_id(self):
109 def _tree_id(self):
110 return self._remote[self._commit['tree']]['id']
110 return self._remote[self._commit['tree']]['id']
111
111
112 @LazyProperty
112 @LazyProperty
113 def id(self):
113 def id(self):
114 return self.raw_id
114 return self.raw_id
115
115
116 @LazyProperty
116 @LazyProperty
117 def short_id(self):
117 def short_id(self):
118 return self.raw_id[:12]
118 return self.raw_id[:12]
119
119
120 @LazyProperty
120 @LazyProperty
121 def message(self):
121 def message(self):
122 return safe_unicode(self._remote.message(self.id))
122 return safe_unicode(self._remote.message(self.id))
123
123
124 @LazyProperty
124 @LazyProperty
125 def committer(self):
125 def committer(self):
126 return safe_unicode(self._remote.author(self.id))
126 return safe_unicode(self._remote.author(self.id))
127
127
128 @LazyProperty
128 @LazyProperty
129 def author(self):
129 def author(self):
130 return safe_unicode(self._remote.author(self.id))
130 return safe_unicode(self._remote.author(self.id))
131
131
132 @LazyProperty
132 @LazyProperty
133 def date(self):
133 def date(self):
134 unix_ts, tz = self._remote.date(self.raw_id)
134 unix_ts, tz = self._remote.date(self.raw_id)
135 return utcdate_fromtimestamp(unix_ts, tz)
135 return utcdate_fromtimestamp(unix_ts, tz)
136
136
137 @LazyProperty
137 @LazyProperty
138 def status(self):
138 def status(self):
139 """
139 """
140 Returns modified, added, removed, deleted files for current commit
140 Returns modified, added, removed, deleted files for current commit
141 """
141 """
142 return self.changed, self.added, self.removed
142 return self.changed, self.added, self.removed
143
143
144 @LazyProperty
144 @LazyProperty
145 def tags(self):
145 def tags(self):
146 tags = [safe_unicode(name) for name,
146 tags = [safe_unicode(name) for name,
147 commit_id in self.repository.tags.iteritems()
147 commit_id in self.repository.tags.iteritems()
148 if commit_id == self.raw_id]
148 if commit_id == self.raw_id]
149 return tags
149 return tags
150
150
151 @LazyProperty
151 @LazyProperty
152 def commit_branches(self):
152 def commit_branches(self):
153 branches = []
153 branches = []
154 for name, commit_id in self.repository.branches.iteritems():
154 for name, commit_id in self.repository.branches.iteritems():
155 if commit_id == self.raw_id:
155 if commit_id == self.raw_id:
156 branches.append(name)
156 branches.append(name)
157 return branches
157 return branches
158
158
159 @LazyProperty
159 @LazyProperty
160 def branch(self):
160 def branch(self):
161 branches = safe_unicode(self._remote.branch(self.raw_id))
161 branches = self._remote.branch(self.raw_id)
162
162 if branches:
163 if branches:
163 # actually commit can have multiple branches in git
164 # actually commit can have multiple branches in git
164 return safe_unicode(branches[0])
165 return safe_unicode(branches[0])
165
166
166 def _get_tree_id_for_path(self, path):
167 def _get_tree_id_for_path(self, path):
167 path = safe_str(path)
168 path = safe_str(path)
168 if path in self._paths:
169 if path in self._paths:
169 return self._paths[path]
170 return self._paths[path]
170
171
171 tree_id = self._tree_id
172 tree_id = self._tree_id
172
173
173 path = path.strip('/')
174 path = path.strip('/')
174 if path == '':
175 if path == '':
175 data = [tree_id, "tree"]
176 data = [tree_id, "tree"]
176 self._paths[''] = data
177 self._paths[''] = data
177 return data
178 return data
178
179
179 tree_id, tree_type, tree_mode = \
180 tree_id, tree_type, tree_mode = \
180 self._remote.tree_and_type_for_path(self.raw_id, path)
181 self._remote.tree_and_type_for_path(self.raw_id, path)
181 if tree_id is None:
182 if tree_id is None:
182 raise self.no_node_at_path(path)
183 raise self.no_node_at_path(path)
183
184
184 self._paths[path] = [tree_id, tree_type]
185 self._paths[path] = [tree_id, tree_type]
185 self._stat_modes[path] = tree_mode
186 self._stat_modes[path] = tree_mode
186
187
187 if path not in self._paths:
188 if path not in self._paths:
188 raise self.no_node_at_path(path)
189 raise self.no_node_at_path(path)
189
190
190 return self._paths[path]
191 return self._paths[path]
191
192
192 def _get_kind(self, path):
193 def _get_kind(self, path):
193 tree_id, type_ = self._get_tree_id_for_path(path)
194 tree_id, type_ = self._get_tree_id_for_path(path)
194 if type_ == 'blob':
195 if type_ == 'blob':
195 return NodeKind.FILE
196 return NodeKind.FILE
196 elif type_ == 'tree':
197 elif type_ == 'tree':
197 return NodeKind.DIR
198 return NodeKind.DIR
198 elif type_ == 'link':
199 elif type_ == 'link':
199 return NodeKind.SUBMODULE
200 return NodeKind.SUBMODULE
200 return None
201 return None
201
202
202 def _get_filectx(self, path):
203 def _get_filectx(self, path):
203 path = self._fix_path(path)
204 path = self._fix_path(path)
204 if self._get_kind(path) != NodeKind.FILE:
205 if self._get_kind(path) != NodeKind.FILE:
205 raise CommitError(
206 raise CommitError(
206 "File does not exist for commit %s at '%s'" % (self.raw_id, path))
207 "File does not exist for commit %s at '%s'" % (self.raw_id, path))
207 return path
208 return path
208
209
209 def _get_file_nodes(self):
210 def _get_file_nodes(self):
210 return chain(*(t[2] for t in self.walk()))
211 return chain(*(t[2] for t in self.walk()))
211
212
212 @LazyProperty
213 @LazyProperty
213 def parents(self):
214 def parents(self):
214 """
215 """
215 Returns list of parent commits.
216 Returns list of parent commits.
216 """
217 """
217 parent_ids = self._remote.parents(self.id)
218 parent_ids = self._remote.parents(self.id)
218 return self._make_commits(parent_ids)
219 return self._make_commits(parent_ids)
219
220
220 @LazyProperty
221 @LazyProperty
221 def children(self):
222 def children(self):
222 """
223 """
223 Returns list of child commits.
224 Returns list of child commits.
224 """
225 """
225 rev_filter = settings.GIT_REV_FILTER
226 rev_filter = settings.GIT_REV_FILTER
226 output, __ = self.repository.run_git_command(
227 output, __ = self.repository.run_git_command(
227 ['rev-list', '--children'] + rev_filter)
228 ['rev-list', '--children'] + rev_filter)
228
229
229 child_ids = []
230 child_ids = []
230 pat = re.compile(r'^%s' % self.raw_id)
231 pat = re.compile(r'^%s' % self.raw_id)
231 for l in output.splitlines():
232 for l in output.splitlines():
232 if pat.match(l):
233 if pat.match(l):
233 found_ids = l.split(' ')[1:]
234 found_ids = l.split(' ')[1:]
234 child_ids.extend(found_ids)
235 child_ids.extend(found_ids)
235 return self._make_commits(child_ids)
236 return self._make_commits(child_ids)
236
237
237 def _make_commits(self, commit_ids):
238 def _make_commits(self, commit_ids):
238 def commit_maker(_commit_id):
239 def commit_maker(_commit_id):
239 return self.repository.get_commit(commit_id=commit_id)
240 return self.repository.get_commit(commit_id=commit_id)
240
241
241 return [commit_maker(commit_id) for commit_id in commit_ids]
242 return [commit_maker(commit_id) for commit_id in commit_ids]
242
243
243 def get_file_mode(self, path):
244 def get_file_mode(self, path):
244 """
245 """
245 Returns stat mode of the file at the given `path`.
246 Returns stat mode of the file at the given `path`.
246 """
247 """
247 path = safe_str(path)
248 path = safe_str(path)
248 # ensure path is traversed
249 # ensure path is traversed
249 self._get_tree_id_for_path(path)
250 self._get_tree_id_for_path(path)
250 return self._stat_modes[path]
251 return self._stat_modes[path]
251
252
252 def is_link(self, path):
253 def is_link(self, path):
253 return stat.S_ISLNK(self.get_file_mode(path))
254 return stat.S_ISLNK(self.get_file_mode(path))
254
255
255 def get_file_content(self, path):
256 def get_file_content(self, path):
256 """
257 """
257 Returns content of the file at given `path`.
258 Returns content of the file at given `path`.
258 """
259 """
259 tree_id, _ = self._get_tree_id_for_path(path)
260 tree_id, _ = self._get_tree_id_for_path(path)
260 return self._remote.blob_as_pretty_string(tree_id)
261 return self._remote.blob_as_pretty_string(tree_id)
261
262
262 def get_file_size(self, path):
263 def get_file_size(self, path):
263 """
264 """
264 Returns size of the file at given `path`.
265 Returns size of the file at given `path`.
265 """
266 """
266 tree_id, _ = self._get_tree_id_for_path(path)
267 tree_id, _ = self._get_tree_id_for_path(path)
267 return self._remote.blob_raw_length(tree_id)
268 return self._remote.blob_raw_length(tree_id)
268
269
269 def get_path_history(self, path, limit=None, pre_load=None):
270 def get_path_history(self, path, limit=None, pre_load=None):
270 """
271 """
271 Returns history of file as reversed list of `GitCommit` objects for
272 Returns history of file as reversed list of `GitCommit` objects for
272 which file at given `path` has been modified.
273 which file at given `path` has been modified.
273
274
274 TODO: This function now uses an underlying 'git' command which works
275 TODO: This function now uses an underlying 'git' command which works
275 quickly but ideally we should replace with an algorithm.
276 quickly but ideally we should replace with an algorithm.
276 """
277 """
277 self._get_filectx(path)
278 self._get_filectx(path)
278 f_path = safe_str(path)
279 f_path = safe_str(path)
279
280
280 # optimize for n==1, rev-list is much faster for that use-case
281 # optimize for n==1, rev-list is much faster for that use-case
281 if limit == 1:
282 if limit == 1:
282 cmd = ['rev-list', '-1', self.raw_id, '--', f_path]
283 cmd = ['rev-list', '-1', self.raw_id, '--', f_path]
283 else:
284 else:
284 cmd = ['log']
285 cmd = ['log']
285 if limit:
286 if limit:
286 cmd.extend(['-n', str(safe_int(limit, 0))])
287 cmd.extend(['-n', str(safe_int(limit, 0))])
287 cmd.extend(['--pretty=format: %H', '-s', self.raw_id, '--', f_path])
288 cmd.extend(['--pretty=format: %H', '-s', self.raw_id, '--', f_path])
288
289
289 output, __ = self.repository.run_git_command(cmd)
290 output, __ = self.repository.run_git_command(cmd)
290 commit_ids = re.findall(r'[0-9a-fA-F]{40}', output)
291 commit_ids = re.findall(r'[0-9a-fA-F]{40}', output)
291
292
292 return [
293 return [
293 self.repository.get_commit(commit_id=commit_id, pre_load=pre_load)
294 self.repository.get_commit(commit_id=commit_id, pre_load=pre_load)
294 for commit_id in commit_ids]
295 for commit_id in commit_ids]
295
296
296 def get_file_annotate(self, path, pre_load=None):
297 def get_file_annotate(self, path, pre_load=None):
297 """
298 """
298 Returns a generator of four element tuples with
299 Returns a generator of four element tuples with
299 lineno, commit_id, commit lazy loader and line
300 lineno, commit_id, commit lazy loader and line
300
301
301 TODO: This function now uses os underlying 'git' command which is
302 TODO: This function now uses os underlying 'git' command which is
302 generally not good. Should be replaced with algorithm iterating
303 generally not good. Should be replaced with algorithm iterating
303 commits.
304 commits.
304 """
305 """
305 cmd = ['blame', '-l', '--root', '-r', self.raw_id, '--', path]
306 cmd = ['blame', '-l', '--root', '-r', self.raw_id, '--', path]
306 # -l ==> outputs long shas (and we need all 40 characters)
307 # -l ==> outputs long shas (and we need all 40 characters)
307 # --root ==> doesn't put '^' character for bounderies
308 # --root ==> doesn't put '^' character for bounderies
308 # -r commit_id ==> blames for the given commit
309 # -r commit_id ==> blames for the given commit
309 output, __ = self.repository.run_git_command(cmd)
310 output, __ = self.repository.run_git_command(cmd)
310
311
311 for i, blame_line in enumerate(output.split('\n')[:-1]):
312 for i, blame_line in enumerate(output.split('\n')[:-1]):
312 line_no = i + 1
313 line_no = i + 1
313 commit_id, line = re.split(r' ', blame_line, 1)
314 commit_id, line = re.split(r' ', blame_line, 1)
314 yield (
315 yield (
315 line_no, commit_id,
316 line_no, commit_id,
316 lambda: self.repository.get_commit(commit_id=commit_id,
317 lambda: self.repository.get_commit(commit_id=commit_id,
317 pre_load=pre_load),
318 pre_load=pre_load),
318 line)
319 line)
319
320
320 def get_nodes(self, path):
321 def get_nodes(self, path):
321
322
322 if self._get_kind(path) != NodeKind.DIR:
323 if self._get_kind(path) != NodeKind.DIR:
323 raise CommitError(
324 raise CommitError(
324 "Directory does not exist for commit %s at '%s'" % (self.raw_id, path))
325 "Directory does not exist for commit %s at '%s'" % (self.raw_id, path))
325 path = self._fix_path(path)
326 path = self._fix_path(path)
326
327
327 tree_id, _ = self._get_tree_id_for_path(path)
328 tree_id, _ = self._get_tree_id_for_path(path)
328
329
329 dirnodes = []
330 dirnodes = []
330 filenodes = []
331 filenodes = []
331
332
332 # extracted tree ID gives us our files...
333 # extracted tree ID gives us our files...
333 for name, stat_, id_, type_ in self._remote.tree_items(tree_id):
334 for name, stat_, id_, type_ in self._remote.tree_items(tree_id):
334 if type_ == 'link':
335 if type_ == 'link':
335 url = self._get_submodule_url('/'.join((path, name)))
336 url = self._get_submodule_url('/'.join((path, name)))
336 dirnodes.append(SubModuleNode(
337 dirnodes.append(SubModuleNode(
337 name, url=url, commit=id_, alias=self.repository.alias))
338 name, url=url, commit=id_, alias=self.repository.alias))
338 continue
339 continue
339
340
340 if path != '':
341 if path != '':
341 obj_path = '/'.join((path, name))
342 obj_path = '/'.join((path, name))
342 else:
343 else:
343 obj_path = name
344 obj_path = name
344 if obj_path not in self._stat_modes:
345 if obj_path not in self._stat_modes:
345 self._stat_modes[obj_path] = stat_
346 self._stat_modes[obj_path] = stat_
346
347
347 if type_ == 'tree':
348 if type_ == 'tree':
348 dirnodes.append(DirNode(obj_path, commit=self))
349 dirnodes.append(DirNode(obj_path, commit=self))
349 elif type_ == 'blob':
350 elif type_ == 'blob':
350 filenodes.append(FileNode(obj_path, commit=self, mode=stat_))
351 filenodes.append(FileNode(obj_path, commit=self, mode=stat_))
351 else:
352 else:
352 raise CommitError(
353 raise CommitError(
353 "Requested object should be Tree or Blob, is %s", type_)
354 "Requested object should be Tree or Blob, is %s", type_)
354
355
355 nodes = dirnodes + filenodes
356 nodes = dirnodes + filenodes
356 for node in nodes:
357 for node in nodes:
357 if node.path not in self.nodes:
358 if node.path not in self.nodes:
358 self.nodes[node.path] = node
359 self.nodes[node.path] = node
359 nodes.sort()
360 nodes.sort()
360 return nodes
361 return nodes
361
362
362 def get_node(self, path, pre_load=None):
363 def get_node(self, path, pre_load=None):
363 if isinstance(path, unicode):
364 if isinstance(path, unicode):
364 path = path.encode('utf-8')
365 path = path.encode('utf-8')
365 path = self._fix_path(path)
366 path = self._fix_path(path)
366 if path not in self.nodes:
367 if path not in self.nodes:
367 try:
368 try:
368 tree_id, type_ = self._get_tree_id_for_path(path)
369 tree_id, type_ = self._get_tree_id_for_path(path)
369 except CommitError:
370 except CommitError:
370 raise NodeDoesNotExistError(
371 raise NodeDoesNotExistError(
371 "Cannot find one of parents' directories for a given "
372 "Cannot find one of parents' directories for a given "
372 "path: %s" % path)
373 "path: %s" % path)
373
374
374 if type_ == 'link':
375 if type_ == 'link':
375 url = self._get_submodule_url(path)
376 url = self._get_submodule_url(path)
376 node = SubModuleNode(path, url=url, commit=tree_id,
377 node = SubModuleNode(path, url=url, commit=tree_id,
377 alias=self.repository.alias)
378 alias=self.repository.alias)
378 elif type_ == 'tree':
379 elif type_ == 'tree':
379 if path == '':
380 if path == '':
380 node = RootNode(commit=self)
381 node = RootNode(commit=self)
381 else:
382 else:
382 node = DirNode(path, commit=self)
383 node = DirNode(path, commit=self)
383 elif type_ == 'blob':
384 elif type_ == 'blob':
384 node = FileNode(path, commit=self, pre_load=pre_load)
385 node = FileNode(path, commit=self, pre_load=pre_load)
385 self._stat_modes[path] = node.mode
386 self._stat_modes[path] = node.mode
386 else:
387 else:
387 raise self.no_node_at_path(path)
388 raise self.no_node_at_path(path)
388
389
389 # cache node
390 # cache node
390 self.nodes[path] = node
391 self.nodes[path] = node
391
392
392 return self.nodes[path]
393 return self.nodes[path]
393
394
394 def get_largefile_node(self, path):
395 def get_largefile_node(self, path):
395 tree_id, _ = self._get_tree_id_for_path(path)
396 tree_id, _ = self._get_tree_id_for_path(path)
396 pointer_spec = self._remote.is_large_file(tree_id)
397 pointer_spec = self._remote.is_large_file(tree_id)
397
398
398 if pointer_spec:
399 if pointer_spec:
399 # content of that file regular FileNode is the hash of largefile
400 # content of that file regular FileNode is the hash of largefile
400 file_id = pointer_spec.get('oid_hash')
401 file_id = pointer_spec.get('oid_hash')
401 if self._remote.in_largefiles_store(file_id):
402 if self._remote.in_largefiles_store(file_id):
402 lf_path = self._remote.store_path(file_id)
403 lf_path = self._remote.store_path(file_id)
403 return LargeFileNode(lf_path, commit=self, org_path=path)
404 return LargeFileNode(lf_path, commit=self, org_path=path)
404
405
405 @LazyProperty
406 @LazyProperty
406 def affected_files(self):
407 def affected_files(self):
407 """
408 """
408 Gets a fast accessible file changes for given commit
409 Gets a fast accessible file changes for given commit
409 """
410 """
410 added, modified, deleted = self._changes_cache
411 added, modified, deleted = self._changes_cache
411 return list(added.union(modified).union(deleted))
412 return list(added.union(modified).union(deleted))
412
413
413 @LazyProperty
414 @LazyProperty
414 def _changes_cache(self):
415 def _changes_cache(self):
415 added = set()
416 added = set()
416 modified = set()
417 modified = set()
417 deleted = set()
418 deleted = set()
418 _r = self._remote
419 _r = self._remote
419
420
420 parents = self.parents
421 parents = self.parents
421 if not self.parents:
422 if not self.parents:
422 parents = [base.EmptyCommit()]
423 parents = [base.EmptyCommit()]
423 for parent in parents:
424 for parent in parents:
424 if isinstance(parent, base.EmptyCommit):
425 if isinstance(parent, base.EmptyCommit):
425 oid = None
426 oid = None
426 else:
427 else:
427 oid = parent.raw_id
428 oid = parent.raw_id
428 changes = _r.tree_changes(oid, self.raw_id)
429 changes = _r.tree_changes(oid, self.raw_id)
429 for (oldpath, newpath), (_, _), (_, _) in changes:
430 for (oldpath, newpath), (_, _), (_, _) in changes:
430 if newpath and oldpath:
431 if newpath and oldpath:
431 modified.add(newpath)
432 modified.add(newpath)
432 elif newpath and not oldpath:
433 elif newpath and not oldpath:
433 added.add(newpath)
434 added.add(newpath)
434 elif not newpath and oldpath:
435 elif not newpath and oldpath:
435 deleted.add(oldpath)
436 deleted.add(oldpath)
436 return added, modified, deleted
437 return added, modified, deleted
437
438
438 def _get_paths_for_status(self, status):
439 def _get_paths_for_status(self, status):
439 """
440 """
440 Returns sorted list of paths for given ``status``.
441 Returns sorted list of paths for given ``status``.
441
442
442 :param status: one of: *added*, *modified* or *deleted*
443 :param status: one of: *added*, *modified* or *deleted*
443 """
444 """
444 added, modified, deleted = self._changes_cache
445 added, modified, deleted = self._changes_cache
445 return sorted({
446 return sorted({
446 'added': list(added),
447 'added': list(added),
447 'modified': list(modified),
448 'modified': list(modified),
448 'deleted': list(deleted)}[status]
449 'deleted': list(deleted)}[status]
449 )
450 )
450
451
451 @LazyProperty
452 @LazyProperty
452 def added(self):
453 def added(self):
453 """
454 """
454 Returns list of added ``FileNode`` objects.
455 Returns list of added ``FileNode`` objects.
455 """
456 """
456 if not self.parents:
457 if not self.parents:
457 return list(self._get_file_nodes())
458 return list(self._get_file_nodes())
458 return AddedFileNodesGenerator(
459 return AddedFileNodesGenerator(
459 [n for n in self._get_paths_for_status('added')], self)
460 [n for n in self._get_paths_for_status('added')], self)
460
461
461 @LazyProperty
462 @LazyProperty
462 def changed(self):
463 def changed(self):
463 """
464 """
464 Returns list of modified ``FileNode`` objects.
465 Returns list of modified ``FileNode`` objects.
465 """
466 """
466 if not self.parents:
467 if not self.parents:
467 return []
468 return []
468 return ChangedFileNodesGenerator(
469 return ChangedFileNodesGenerator(
469 [n for n in self._get_paths_for_status('modified')], self)
470 [n for n in self._get_paths_for_status('modified')], self)
470
471
471 @LazyProperty
472 @LazyProperty
472 def removed(self):
473 def removed(self):
473 """
474 """
474 Returns list of removed ``FileNode`` objects.
475 Returns list of removed ``FileNode`` objects.
475 """
476 """
476 if not self.parents:
477 if not self.parents:
477 return []
478 return []
478 return RemovedFileNodesGenerator(
479 return RemovedFileNodesGenerator(
479 [n for n in self._get_paths_for_status('deleted')], self)
480 [n for n in self._get_paths_for_status('deleted')], self)
480
481
481 def _get_submodule_url(self, submodule_path):
482 def _get_submodule_url(self, submodule_path):
482 git_modules_path = '.gitmodules'
483 git_modules_path = '.gitmodules'
483
484
484 if self._submodules is None:
485 if self._submodules is None:
485 self._submodules = {}
486 self._submodules = {}
486
487
487 try:
488 try:
488 submodules_node = self.get_node(git_modules_path)
489 submodules_node = self.get_node(git_modules_path)
489 except NodeDoesNotExistError:
490 except NodeDoesNotExistError:
490 return None
491 return None
491
492
492 content = submodules_node.content
493 content = submodules_node.content
493
494
494 # ConfigParser fails if there are whitespaces
495 # ConfigParser fails if there are whitespaces
495 content = '\n'.join(l.strip() for l in content.split('\n'))
496 content = '\n'.join(l.strip() for l in content.split('\n'))
496
497
497 parser = configparser.ConfigParser()
498 parser = configparser.ConfigParser()
498 parser.readfp(StringIO(content))
499 parser.readfp(StringIO(content))
499
500
500 for section in parser.sections():
501 for section in parser.sections():
501 path = parser.get(section, 'path')
502 path = parser.get(section, 'path')
502 url = parser.get(section, 'url')
503 url = parser.get(section, 'url')
503 if path and url:
504 if path and url:
504 self._submodules[path.strip('/')] = url
505 self._submodules[path.strip('/')] = url
505
506
506 return self._submodules.get(submodule_path.strip('/'))
507 return self._submodules.get(submodule_path.strip('/'))
@@ -1,318 +1,318 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2019 RhodeCode GmbH
3 # Copyright (C) 2016-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Client for the VCSServer implemented based on HTTP.
22 Client for the VCSServer implemented based on HTTP.
23 """
23 """
24
24
25 import copy
25 import copy
26 import logging
26 import logging
27 import threading
27 import threading
28 import time
28 import time
29 import urllib2
29 import urllib2
30 import urlparse
30 import urlparse
31 import uuid
31 import uuid
32 import traceback
32 import traceback
33
33
34 import pycurl
34 import pycurl
35 import msgpack
35 import msgpack
36 import requests
36 import requests
37 from requests.packages.urllib3.util.retry import Retry
37 from requests.packages.urllib3.util.retry import Retry
38
38
39 import rhodecode
39 import rhodecode
40 from rhodecode.lib.system_info import get_cert_path
40 from rhodecode.lib.system_info import get_cert_path
41 from rhodecode.lib.vcs import exceptions, CurlSession
41 from rhodecode.lib.vcs import exceptions, CurlSession
42
42
43 log = logging.getLogger(__name__)
43 log = logging.getLogger(__name__)
44
44
45
45
46 # TODO: mikhail: Keep it in sync with vcsserver's
46 # TODO: mikhail: Keep it in sync with vcsserver's
47 # HTTPApplication.ALLOWED_EXCEPTIONS
47 # HTTPApplication.ALLOWED_EXCEPTIONS
48 EXCEPTIONS_MAP = {
48 EXCEPTIONS_MAP = {
49 'KeyError': KeyError,
49 'KeyError': KeyError,
50 'URLError': urllib2.URLError,
50 'URLError': urllib2.URLError,
51 }
51 }
52
52
53
53
54 class RepoMaker(object):
54 class RepoMaker(object):
55
55
56 def __init__(self, server_and_port, backend_endpoint, backend_type, session_factory):
56 def __init__(self, server_and_port, backend_endpoint, backend_type, session_factory):
57 self.url = urlparse.urljoin('http://%s' % server_and_port, backend_endpoint)
57 self.url = urlparse.urljoin('http://%s' % server_and_port, backend_endpoint)
58 self._session_factory = session_factory
58 self._session_factory = session_factory
59 self.backend_type = backend_type
59 self.backend_type = backend_type
60
60
61 def __call__(self, path, repo_id, config, with_wire=None):
61 def __call__(self, path, repo_id, config, with_wire=None):
62 log.debug('%s RepoMaker call on %s', self.backend_type.upper(), path)
62 log.debug('%s RepoMaker call on %s', self.backend_type.upper(), path)
63 return RemoteRepo(path, repo_id, config, self.url, self._session_factory(),
63 return RemoteRepo(path, repo_id, config, self.url, self._session_factory(),
64 with_wire=with_wire)
64 with_wire=with_wire)
65
65
66 def __getattr__(self, name):
66 def __getattr__(self, name):
67 def f(*args, **kwargs):
67 def f(*args, **kwargs):
68 return self._call(name, *args, **kwargs)
68 return self._call(name, *args, **kwargs)
69 return f
69 return f
70
70
71 @exceptions.map_vcs_exceptions
71 @exceptions.map_vcs_exceptions
72 def _call(self, name, *args, **kwargs):
72 def _call(self, name, *args, **kwargs):
73 payload = {
73 payload = {
74 'id': str(uuid.uuid4()),
74 'id': str(uuid.uuid4()),
75 'method': name,
75 'method': name,
76 'backend': self.backend_type,
76 'backend': self.backend_type,
77 'params': {'args': args, 'kwargs': kwargs}
77 'params': {'args': args, 'kwargs': kwargs}
78 }
78 }
79 return _remote_call(
79 return _remote_call(
80 self.url, payload, EXCEPTIONS_MAP, self._session_factory())
80 self.url, payload, EXCEPTIONS_MAP, self._session_factory())
81
81
82
82
83 class ServiceConnection(object):
83 class ServiceConnection(object):
84 def __init__(self, server_and_port, backend_endpoint, session_factory):
84 def __init__(self, server_and_port, backend_endpoint, session_factory):
85 self.url = urlparse.urljoin('http://%s' % server_and_port, backend_endpoint)
85 self.url = urlparse.urljoin('http://%s' % server_and_port, backend_endpoint)
86 self._session_factory = session_factory
86 self._session_factory = session_factory
87
87
88 def __getattr__(self, name):
88 def __getattr__(self, name):
89 def f(*args, **kwargs):
89 def f(*args, **kwargs):
90 return self._call(name, *args, **kwargs)
90 return self._call(name, *args, **kwargs)
91
91
92 return f
92 return f
93
93
94 @exceptions.map_vcs_exceptions
94 @exceptions.map_vcs_exceptions
95 def _call(self, name, *args, **kwargs):
95 def _call(self, name, *args, **kwargs):
96 payload = {
96 payload = {
97 'id': str(uuid.uuid4()),
97 'id': str(uuid.uuid4()),
98 'method': name,
98 'method': name,
99 'params': {'args': args, 'kwargs': kwargs}
99 'params': {'args': args, 'kwargs': kwargs}
100 }
100 }
101 return _remote_call(
101 return _remote_call(
102 self.url, payload, EXCEPTIONS_MAP, self._session_factory())
102 self.url, payload, EXCEPTIONS_MAP, self._session_factory())
103
103
104
104
105 class RemoteRepo(object):
105 class RemoteRepo(object):
106
106
107 def __init__(self, path, repo_id, config, url, session, with_wire=None):
107 def __init__(self, path, repo_id, config, url, session, with_wire=None):
108 self.url = url
108 self.url = url
109 self._session = session
109 self._session = session
110 with_wire = with_wire or {}
110 with_wire = with_wire or {}
111
111
112 repo_state_uid = with_wire.get('repo_state_uid') or 'state'
112 repo_state_uid = with_wire.get('repo_state_uid') or 'state'
113 self._wire = {
113 self._wire = {
114 "path": path, # repo path
114 "path": path, # repo path
115 "repo_id": repo_id,
115 "repo_id": repo_id,
116 "config": config,
116 "config": config,
117 "repo_state_uid": repo_state_uid,
117 "repo_state_uid": repo_state_uid,
118 "context": self._create_vcs_cache_context(path, repo_state_uid)
118 "context": self._create_vcs_cache_context(path, repo_state_uid)
119 }
119 }
120
120
121 if with_wire:
121 if with_wire:
122 self._wire.update(with_wire)
122 self._wire.update(with_wire)
123
123
124 # NOTE(johbo): Trading complexity for performance. Avoiding the call to
124 # NOTE(johbo): Trading complexity for performance. Avoiding the call to
125 # log.debug brings a few percent gain even if is is not active.
125 # log.debug brings a few percent gain even if is is not active.
126 if log.isEnabledFor(logging.DEBUG):
126 if log.isEnabledFor(logging.DEBUG):
127 self._call_with_logging = True
127 self._call_with_logging = True
128
128
129 self.cert_dir = get_cert_path(rhodecode.CONFIG.get('__file__'))
129 self.cert_dir = get_cert_path(rhodecode.CONFIG.get('__file__'))
130
130
131 def __getattr__(self, name):
131 def __getattr__(self, name):
132 def f(*args, **kwargs):
132 def f(*args, **kwargs):
133 return self._call(name, *args, **kwargs)
133 return self._call(name, *args, **kwargs)
134 return f
134 return f
135
135
136 @exceptions.map_vcs_exceptions
136 @exceptions.map_vcs_exceptions
137 def _call(self, name, *args, **kwargs):
137 def _call(self, name, *args, **kwargs):
138 # TODO: oliver: This is currently necessary pre-call since the
138 # TODO: oliver: This is currently necessary pre-call since the
139 # config object is being changed for hooking scenarios
139 # config object is being changed for hooking scenarios
140 wire = copy.deepcopy(self._wire)
140 wire = copy.deepcopy(self._wire)
141 wire["config"] = wire["config"].serialize()
141 wire["config"] = wire["config"].serialize()
142 wire["config"].append(('vcs', 'ssl_dir', self.cert_dir))
142 wire["config"].append(('vcs', 'ssl_dir', self.cert_dir))
143
143
144 payload = {
144 payload = {
145 'id': str(uuid.uuid4()),
145 'id': str(uuid.uuid4()),
146 'method': name,
146 'method': name,
147 'params': {'wire': wire, 'args': args, 'kwargs': kwargs}
147 'params': {'wire': wire, 'args': args, 'kwargs': kwargs}
148 }
148 }
149
149
150 if self._call_with_logging:
150 if self._call_with_logging:
151 start = time.time()
151 start = time.time()
152 context_uid = wire.get('context')
152 context_uid = wire.get('context')
153 log.debug('Calling %s@%s with args:%.10240r. wire_context: %s',
153 log.debug('Calling %s@%s with args:%.10240r. wire_context: %s',
154 self.url, name, args, context_uid)
154 self.url, name, args, context_uid)
155 result = _remote_call(self.url, payload, EXCEPTIONS_MAP, self._session)
155 result = _remote_call(self.url, payload, EXCEPTIONS_MAP, self._session)
156 if self._call_with_logging:
156 if self._call_with_logging:
157 log.debug('Call %s@%s took: %.3fs. wire_context: %s',
157 log.debug('Call %s@%s took: %.4fs. wire_context: %s',
158 self.url, name, time.time()-start, context_uid)
158 self.url, name, time.time()-start, context_uid)
159 return result
159 return result
160
160
161 def __getitem__(self, key):
161 def __getitem__(self, key):
162 return self.revision(key)
162 return self.revision(key)
163
163
164 def _create_vcs_cache_context(self, *args):
164 def _create_vcs_cache_context(self, *args):
165 """
165 """
166 Creates a unique string which is passed to the VCSServer on every
166 Creates a unique string which is passed to the VCSServer on every
167 remote call. It is used as cache key in the VCSServer.
167 remote call. It is used as cache key in the VCSServer.
168 """
168 """
169 hash_key = '-'.join(map(str, args))
169 hash_key = '-'.join(map(str, args))
170 return str(uuid.uuid5(uuid.NAMESPACE_URL, hash_key))
170 return str(uuid.uuid5(uuid.NAMESPACE_URL, hash_key))
171
171
172 def invalidate_vcs_cache(self):
172 def invalidate_vcs_cache(self):
173 """
173 """
174 This invalidates the context which is sent to the VCSServer on every
174 This invalidates the context which is sent to the VCSServer on every
175 call to a remote method. It forces the VCSServer to create a fresh
175 call to a remote method. It forces the VCSServer to create a fresh
176 repository instance on the next call to a remote method.
176 repository instance on the next call to a remote method.
177 """
177 """
178 self._wire['context'] = str(uuid.uuid4())
178 self._wire['context'] = str(uuid.uuid4())
179
179
180
180
181 class RemoteObject(object):
181 class RemoteObject(object):
182
182
183 def __init__(self, url, session):
183 def __init__(self, url, session):
184 self._url = url
184 self._url = url
185 self._session = session
185 self._session = session
186
186
187 # johbo: Trading complexity for performance. Avoiding the call to
187 # johbo: Trading complexity for performance. Avoiding the call to
188 # log.debug brings a few percent gain even if is is not active.
188 # log.debug brings a few percent gain even if is is not active.
189 if log.isEnabledFor(logging.DEBUG):
189 if log.isEnabledFor(logging.DEBUG):
190 self._call = self._call_with_logging
190 self._call = self._call_with_logging
191
191
192 def __getattr__(self, name):
192 def __getattr__(self, name):
193 def f(*args, **kwargs):
193 def f(*args, **kwargs):
194 return self._call(name, *args, **kwargs)
194 return self._call(name, *args, **kwargs)
195 return f
195 return f
196
196
197 @exceptions.map_vcs_exceptions
197 @exceptions.map_vcs_exceptions
198 def _call(self, name, *args, **kwargs):
198 def _call(self, name, *args, **kwargs):
199 payload = {
199 payload = {
200 'id': str(uuid.uuid4()),
200 'id': str(uuid.uuid4()),
201 'method': name,
201 'method': name,
202 'params': {'args': args, 'kwargs': kwargs}
202 'params': {'args': args, 'kwargs': kwargs}
203 }
203 }
204 return _remote_call(self._url, payload, EXCEPTIONS_MAP, self._session)
204 return _remote_call(self._url, payload, EXCEPTIONS_MAP, self._session)
205
205
206 def _call_with_logging(self, name, *args, **kwargs):
206 def _call_with_logging(self, name, *args, **kwargs):
207 log.debug('Calling %s@%s', self._url, name)
207 log.debug('Calling %s@%s', self._url, name)
208 return RemoteObject._call(self, name, *args, **kwargs)
208 return RemoteObject._call(self, name, *args, **kwargs)
209
209
210
210
211 def _remote_call(url, payload, exceptions_map, session):
211 def _remote_call(url, payload, exceptions_map, session):
212 try:
212 try:
213 response = session.post(url, data=msgpack.packb(payload))
213 response = session.post(url, data=msgpack.packb(payload))
214 except pycurl.error as e:
214 except pycurl.error as e:
215 msg = '{}. \npycurl traceback: {}'.format(e, traceback.format_exc())
215 msg = '{}. \npycurl traceback: {}'.format(e, traceback.format_exc())
216 raise exceptions.HttpVCSCommunicationError(msg)
216 raise exceptions.HttpVCSCommunicationError(msg)
217 except Exception as e:
217 except Exception as e:
218 message = getattr(e, 'message', '')
218 message = getattr(e, 'message', '')
219 if 'Failed to connect' in message:
219 if 'Failed to connect' in message:
220 # gevent doesn't return proper pycurl errors
220 # gevent doesn't return proper pycurl errors
221 raise exceptions.HttpVCSCommunicationError(e)
221 raise exceptions.HttpVCSCommunicationError(e)
222 else:
222 else:
223 raise
223 raise
224
224
225 if response.status_code >= 400:
225 if response.status_code >= 400:
226 log.error('Call to %s returned non 200 HTTP code: %s',
226 log.error('Call to %s returned non 200 HTTP code: %s',
227 url, response.status_code)
227 url, response.status_code)
228 raise exceptions.HttpVCSCommunicationError(repr(response.content))
228 raise exceptions.HttpVCSCommunicationError(repr(response.content))
229
229
230 try:
230 try:
231 response = msgpack.unpackb(response.content)
231 response = msgpack.unpackb(response.content)
232 except Exception:
232 except Exception:
233 log.exception('Failed to decode response %r', response.content)
233 log.exception('Failed to decode response %r', response.content)
234 raise
234 raise
235
235
236 error = response.get('error')
236 error = response.get('error')
237 if error:
237 if error:
238 type_ = error.get('type', 'Exception')
238 type_ = error.get('type', 'Exception')
239 exc = exceptions_map.get(type_, Exception)
239 exc = exceptions_map.get(type_, Exception)
240 exc = exc(error.get('message'))
240 exc = exc(error.get('message'))
241 try:
241 try:
242 exc._vcs_kind = error['_vcs_kind']
242 exc._vcs_kind = error['_vcs_kind']
243 except KeyError:
243 except KeyError:
244 pass
244 pass
245
245
246 try:
246 try:
247 exc._vcs_server_traceback = error['traceback']
247 exc._vcs_server_traceback = error['traceback']
248 exc._vcs_server_org_exc_name = error['org_exc']
248 exc._vcs_server_org_exc_name = error['org_exc']
249 exc._vcs_server_org_exc_tb = error['org_exc_tb']
249 exc._vcs_server_org_exc_tb = error['org_exc_tb']
250 except KeyError:
250 except KeyError:
251 pass
251 pass
252
252
253 raise exc
253 raise exc
254 return response.get('result')
254 return response.get('result')
255
255
256
256
257 class VcsHttpProxy(object):
257 class VcsHttpProxy(object):
258
258
259 CHUNK_SIZE = 16384
259 CHUNK_SIZE = 16384
260
260
261 def __init__(self, server_and_port, backend_endpoint):
261 def __init__(self, server_and_port, backend_endpoint):
262 retries = Retry(total=5, connect=None, read=None, redirect=None)
262 retries = Retry(total=5, connect=None, read=None, redirect=None)
263
263
264 adapter = requests.adapters.HTTPAdapter(max_retries=retries)
264 adapter = requests.adapters.HTTPAdapter(max_retries=retries)
265 self.base_url = urlparse.urljoin('http://%s' % server_and_port, backend_endpoint)
265 self.base_url = urlparse.urljoin('http://%s' % server_and_port, backend_endpoint)
266 self.session = requests.Session()
266 self.session = requests.Session()
267 self.session.mount('http://', adapter)
267 self.session.mount('http://', adapter)
268
268
269 def handle(self, environment, input_data, *args, **kwargs):
269 def handle(self, environment, input_data, *args, **kwargs):
270 data = {
270 data = {
271 'environment': environment,
271 'environment': environment,
272 'input_data': input_data,
272 'input_data': input_data,
273 'args': args,
273 'args': args,
274 'kwargs': kwargs
274 'kwargs': kwargs
275 }
275 }
276 result = self.session.post(
276 result = self.session.post(
277 self.base_url, msgpack.packb(data), stream=True)
277 self.base_url, msgpack.packb(data), stream=True)
278 return self._get_result(result)
278 return self._get_result(result)
279
279
280 def _deserialize_and_raise(self, error):
280 def _deserialize_and_raise(self, error):
281 exception = Exception(error['message'])
281 exception = Exception(error['message'])
282 try:
282 try:
283 exception._vcs_kind = error['_vcs_kind']
283 exception._vcs_kind = error['_vcs_kind']
284 except KeyError:
284 except KeyError:
285 pass
285 pass
286 raise exception
286 raise exception
287
287
288 def _iterate(self, result):
288 def _iterate(self, result):
289 unpacker = msgpack.Unpacker()
289 unpacker = msgpack.Unpacker()
290 for line in result.iter_content(chunk_size=self.CHUNK_SIZE):
290 for line in result.iter_content(chunk_size=self.CHUNK_SIZE):
291 unpacker.feed(line)
291 unpacker.feed(line)
292 for chunk in unpacker:
292 for chunk in unpacker:
293 yield chunk
293 yield chunk
294
294
295 def _get_result(self, result):
295 def _get_result(self, result):
296 iterator = self._iterate(result)
296 iterator = self._iterate(result)
297 error = iterator.next()
297 error = iterator.next()
298 if error:
298 if error:
299 self._deserialize_and_raise(error)
299 self._deserialize_and_raise(error)
300
300
301 status = iterator.next()
301 status = iterator.next()
302 headers = iterator.next()
302 headers = iterator.next()
303
303
304 return iterator, status, headers
304 return iterator, status, headers
305
305
306
306
307 class ThreadlocalSessionFactory(object):
307 class ThreadlocalSessionFactory(object):
308 """
308 """
309 Creates one CurlSession per thread on demand.
309 Creates one CurlSession per thread on demand.
310 """
310 """
311
311
312 def __init__(self):
312 def __init__(self):
313 self._thread_local = threading.local()
313 self._thread_local = threading.local()
314
314
315 def __call__(self):
315 def __call__(self):
316 if not hasattr(self._thread_local, 'curl_session'):
316 if not hasattr(self._thread_local, 'curl_session'):
317 self._thread_local.curl_session = CurlSession()
317 self._thread_local.curl_session = CurlSession()
318 return self._thread_local.curl_session
318 return self._thread_local.curl_session
@@ -1,5185 +1,5185 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import string
28 import string
29 import hashlib
29 import hashlib
30 import logging
30 import logging
31 import datetime
31 import datetime
32 import uuid
32 import uuid
33 import warnings
33 import warnings
34 import ipaddress
34 import ipaddress
35 import functools
35 import functools
36 import traceback
36 import traceback
37 import collections
37 import collections
38
38
39 from sqlalchemy import (
39 from sqlalchemy import (
40 or_, and_, not_, func, TypeDecorator, event,
40 or_, and_, not_, func, TypeDecorator, event,
41 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
41 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
42 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
42 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
43 Text, Float, PickleType)
43 Text, Float, PickleType)
44 from sqlalchemy.sql.expression import true, false, case
44 from sqlalchemy.sql.expression import true, false, case
45 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
45 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
46 from sqlalchemy.orm import (
46 from sqlalchemy.orm import (
47 relationship, joinedload, class_mapper, validates, aliased)
47 relationship, joinedload, class_mapper, validates, aliased)
48 from sqlalchemy.ext.declarative import declared_attr
48 from sqlalchemy.ext.declarative import declared_attr
49 from sqlalchemy.ext.hybrid import hybrid_property
49 from sqlalchemy.ext.hybrid import hybrid_property
50 from sqlalchemy.exc import IntegrityError # pragma: no cover
50 from sqlalchemy.exc import IntegrityError # pragma: no cover
51 from sqlalchemy.dialects.mysql import LONGTEXT
51 from sqlalchemy.dialects.mysql import LONGTEXT
52 from zope.cachedescriptors.property import Lazy as LazyProperty
52 from zope.cachedescriptors.property import Lazy as LazyProperty
53 from pyramid import compat
53 from pyramid import compat
54 from pyramid.threadlocal import get_current_request
54 from pyramid.threadlocal import get_current_request
55 from webhelpers.text import collapse, remove_formatting
55 from webhelpers.text import collapse, remove_formatting
56
56
57 from rhodecode.translation import _
57 from rhodecode.translation import _
58 from rhodecode.lib.vcs import get_vcs_instance
58 from rhodecode.lib.vcs import get_vcs_instance
59 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
59 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
60 from rhodecode.lib.utils2 import (
60 from rhodecode.lib.utils2 import (
61 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
61 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
62 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
62 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
63 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time, OrderedDefaultDict)
63 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time, OrderedDefaultDict)
64 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
64 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
65 JsonRaw
65 JsonRaw
66 from rhodecode.lib.ext_json import json
66 from rhodecode.lib.ext_json import json
67 from rhodecode.lib.caching_query import FromCache
67 from rhodecode.lib.caching_query import FromCache
68 from rhodecode.lib.encrypt import AESCipher, validate_and_get_enc_data
68 from rhodecode.lib.encrypt import AESCipher, validate_and_get_enc_data
69 from rhodecode.lib.encrypt2 import Encryptor
69 from rhodecode.lib.encrypt2 import Encryptor
70 from rhodecode.model.meta import Base, Session
70 from rhodecode.model.meta import Base, Session
71
71
72 URL_SEP = '/'
72 URL_SEP = '/'
73 log = logging.getLogger(__name__)
73 log = logging.getLogger(__name__)
74
74
75 # =============================================================================
75 # =============================================================================
76 # BASE CLASSES
76 # BASE CLASSES
77 # =============================================================================
77 # =============================================================================
78
78
79 # this is propagated from .ini file rhodecode.encrypted_values.secret or
79 # this is propagated from .ini file rhodecode.encrypted_values.secret or
80 # beaker.session.secret if first is not set.
80 # beaker.session.secret if first is not set.
81 # and initialized at environment.py
81 # and initialized at environment.py
82 ENCRYPTION_KEY = None
82 ENCRYPTION_KEY = None
83
83
84 # used to sort permissions by types, '#' used here is not allowed to be in
84 # used to sort permissions by types, '#' used here is not allowed to be in
85 # usernames, and it's very early in sorted string.printable table.
85 # usernames, and it's very early in sorted string.printable table.
86 PERMISSION_TYPE_SORT = {
86 PERMISSION_TYPE_SORT = {
87 'admin': '####',
87 'admin': '####',
88 'write': '###',
88 'write': '###',
89 'read': '##',
89 'read': '##',
90 'none': '#',
90 'none': '#',
91 }
91 }
92
92
93
93
94 def display_user_sort(obj):
94 def display_user_sort(obj):
95 """
95 """
96 Sort function used to sort permissions in .permissions() function of
96 Sort function used to sort permissions in .permissions() function of
97 Repository, RepoGroup, UserGroup. Also it put the default user in front
97 Repository, RepoGroup, UserGroup. Also it put the default user in front
98 of all other resources
98 of all other resources
99 """
99 """
100
100
101 if obj.username == User.DEFAULT_USER:
101 if obj.username == User.DEFAULT_USER:
102 return '#####'
102 return '#####'
103 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
103 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
104 return prefix + obj.username
104 return prefix + obj.username
105
105
106
106
107 def display_user_group_sort(obj):
107 def display_user_group_sort(obj):
108 """
108 """
109 Sort function used to sort permissions in .permissions() function of
109 Sort function used to sort permissions in .permissions() function of
110 Repository, RepoGroup, UserGroup. Also it put the default user in front
110 Repository, RepoGroup, UserGroup. Also it put the default user in front
111 of all other resources
111 of all other resources
112 """
112 """
113
113
114 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
114 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
115 return prefix + obj.users_group_name
115 return prefix + obj.users_group_name
116
116
117
117
118 def _hash_key(k):
118 def _hash_key(k):
119 return sha1_safe(k)
119 return sha1_safe(k)
120
120
121
121
122 def in_filter_generator(qry, items, limit=500):
122 def in_filter_generator(qry, items, limit=500):
123 """
123 """
124 Splits IN() into multiple with OR
124 Splits IN() into multiple with OR
125 e.g.::
125 e.g.::
126 cnt = Repository.query().filter(
126 cnt = Repository.query().filter(
127 or_(
127 or_(
128 *in_filter_generator(Repository.repo_id, range(100000))
128 *in_filter_generator(Repository.repo_id, range(100000))
129 )).count()
129 )).count()
130 """
130 """
131 if not items:
131 if not items:
132 # empty list will cause empty query which might cause security issues
132 # empty list will cause empty query which might cause security issues
133 # this can lead to hidden unpleasant results
133 # this can lead to hidden unpleasant results
134 items = [-1]
134 items = [-1]
135
135
136 parts = []
136 parts = []
137 for chunk in xrange(0, len(items), limit):
137 for chunk in xrange(0, len(items), limit):
138 parts.append(
138 parts.append(
139 qry.in_(items[chunk: chunk + limit])
139 qry.in_(items[chunk: chunk + limit])
140 )
140 )
141
141
142 return parts
142 return parts
143
143
144
144
145 base_table_args = {
145 base_table_args = {
146 'extend_existing': True,
146 'extend_existing': True,
147 'mysql_engine': 'InnoDB',
147 'mysql_engine': 'InnoDB',
148 'mysql_charset': 'utf8',
148 'mysql_charset': 'utf8',
149 'sqlite_autoincrement': True
149 'sqlite_autoincrement': True
150 }
150 }
151
151
152
152
153 class EncryptedTextValue(TypeDecorator):
153 class EncryptedTextValue(TypeDecorator):
154 """
154 """
155 Special column for encrypted long text data, use like::
155 Special column for encrypted long text data, use like::
156
156
157 value = Column("encrypted_value", EncryptedValue(), nullable=False)
157 value = Column("encrypted_value", EncryptedValue(), nullable=False)
158
158
159 This column is intelligent so if value is in unencrypted form it return
159 This column is intelligent so if value is in unencrypted form it return
160 unencrypted form, but on save it always encrypts
160 unencrypted form, but on save it always encrypts
161 """
161 """
162 impl = Text
162 impl = Text
163
163
164 def process_bind_param(self, value, dialect):
164 def process_bind_param(self, value, dialect):
165 """
165 """
166 Setter for storing value
166 Setter for storing value
167 """
167 """
168 import rhodecode
168 import rhodecode
169 if not value:
169 if not value:
170 return value
170 return value
171
171
172 # protect against double encrypting if values is already encrypted
172 # protect against double encrypting if values is already encrypted
173 if value.startswith('enc$aes$') \
173 if value.startswith('enc$aes$') \
174 or value.startswith('enc$aes_hmac$') \
174 or value.startswith('enc$aes_hmac$') \
175 or value.startswith('enc2$'):
175 or value.startswith('enc2$'):
176 raise ValueError('value needs to be in unencrypted format, '
176 raise ValueError('value needs to be in unencrypted format, '
177 'ie. not starting with enc$ or enc2$')
177 'ie. not starting with enc$ or enc2$')
178
178
179 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
179 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
180 if algo == 'aes':
180 if algo == 'aes':
181 return 'enc$aes_hmac$%s' % AESCipher(ENCRYPTION_KEY, hmac=True).encrypt(value)
181 return 'enc$aes_hmac$%s' % AESCipher(ENCRYPTION_KEY, hmac=True).encrypt(value)
182 elif algo == 'fernet':
182 elif algo == 'fernet':
183 return Encryptor(ENCRYPTION_KEY).encrypt(value)
183 return Encryptor(ENCRYPTION_KEY).encrypt(value)
184 else:
184 else:
185 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
185 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
186
186
187 def process_result_value(self, value, dialect):
187 def process_result_value(self, value, dialect):
188 """
188 """
189 Getter for retrieving value
189 Getter for retrieving value
190 """
190 """
191
191
192 import rhodecode
192 import rhodecode
193 if not value:
193 if not value:
194 return value
194 return value
195
195
196 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
196 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
197 enc_strict_mode = str2bool(rhodecode.CONFIG.get('rhodecode.encrypted_values.strict') or True)
197 enc_strict_mode = str2bool(rhodecode.CONFIG.get('rhodecode.encrypted_values.strict') or True)
198 if algo == 'aes':
198 if algo == 'aes':
199 decrypted_data = validate_and_get_enc_data(value, ENCRYPTION_KEY, enc_strict_mode)
199 decrypted_data = validate_and_get_enc_data(value, ENCRYPTION_KEY, enc_strict_mode)
200 elif algo == 'fernet':
200 elif algo == 'fernet':
201 return Encryptor(ENCRYPTION_KEY).decrypt(value)
201 return Encryptor(ENCRYPTION_KEY).decrypt(value)
202 else:
202 else:
203 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
203 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
204 return decrypted_data
204 return decrypted_data
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.iteritems():
232 for k, val in _json_attr.iteritems():
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 get(cls, id_):
257 def get(cls, id_):
258 if id_:
258 if id_:
259 return cls.query().get(id_)
259 return cls.query().get(id_)
260
260
261 @classmethod
261 @classmethod
262 def get_or_404(cls, id_):
262 def get_or_404(cls, id_):
263 from pyramid.httpexceptions import HTTPNotFound
263 from pyramid.httpexceptions import HTTPNotFound
264
264
265 try:
265 try:
266 id_ = int(id_)
266 id_ = int(id_)
267 except (TypeError, ValueError):
267 except (TypeError, ValueError):
268 raise HTTPNotFound()
268 raise HTTPNotFound()
269
269
270 res = cls.query().get(id_)
270 res = cls.query().get(id_)
271 if not res:
271 if not res:
272 raise HTTPNotFound()
272 raise HTTPNotFound()
273 return res
273 return res
274
274
275 @classmethod
275 @classmethod
276 def getAll(cls):
276 def getAll(cls):
277 # deprecated and left for backward compatibility
277 # deprecated and left for backward compatibility
278 return cls.get_all()
278 return cls.get_all()
279
279
280 @classmethod
280 @classmethod
281 def get_all(cls):
281 def get_all(cls):
282 return cls.query().all()
282 return cls.query().all()
283
283
284 @classmethod
284 @classmethod
285 def delete(cls, id_):
285 def delete(cls, id_):
286 obj = cls.query().get(id_)
286 obj = cls.query().get(id_)
287 Session().delete(obj)
287 Session().delete(obj)
288
288
289 @classmethod
289 @classmethod
290 def identity_cache(cls, session, attr_name, value):
290 def identity_cache(cls, session, attr_name, value):
291 exist_in_session = []
291 exist_in_session = []
292 for (item_cls, pkey), instance in session.identity_map.items():
292 for (item_cls, pkey), instance in session.identity_map.items():
293 if cls == item_cls and getattr(instance, attr_name) == value:
293 if cls == item_cls and getattr(instance, attr_name) == value:
294 exist_in_session.append(instance)
294 exist_in_session.append(instance)
295 if exist_in_session:
295 if exist_in_session:
296 if len(exist_in_session) == 1:
296 if len(exist_in_session) == 1:
297 return exist_in_session[0]
297 return exist_in_session[0]
298 log.exception(
298 log.exception(
299 'multiple objects with attr %s and '
299 'multiple objects with attr %s and '
300 'value %s found with same name: %r',
300 'value %s found with same name: %r',
301 attr_name, value, exist_in_session)
301 attr_name, value, exist_in_session)
302
302
303 def __repr__(self):
303 def __repr__(self):
304 if hasattr(self, '__unicode__'):
304 if hasattr(self, '__unicode__'):
305 # python repr needs to return str
305 # python repr needs to return str
306 try:
306 try:
307 return safe_str(self.__unicode__())
307 return safe_str(self.__unicode__())
308 except UnicodeDecodeError:
308 except UnicodeDecodeError:
309 pass
309 pass
310 return '<DB:%s>' % (self.__class__.__name__)
310 return '<DB:%s>' % (self.__class__.__name__)
311
311
312
312
313 class RhodeCodeSetting(Base, BaseModel):
313 class RhodeCodeSetting(Base, BaseModel):
314 __tablename__ = 'rhodecode_settings'
314 __tablename__ = 'rhodecode_settings'
315 __table_args__ = (
315 __table_args__ = (
316 UniqueConstraint('app_settings_name'),
316 UniqueConstraint('app_settings_name'),
317 base_table_args
317 base_table_args
318 )
318 )
319
319
320 SETTINGS_TYPES = {
320 SETTINGS_TYPES = {
321 'str': safe_str,
321 'str': safe_str,
322 'int': safe_int,
322 'int': safe_int,
323 'unicode': safe_unicode,
323 'unicode': safe_unicode,
324 'bool': str2bool,
324 'bool': str2bool,
325 'list': functools.partial(aslist, sep=',')
325 'list': functools.partial(aslist, sep=',')
326 }
326 }
327 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
327 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
328 GLOBAL_CONF_KEY = 'app_settings'
328 GLOBAL_CONF_KEY = 'app_settings'
329
329
330 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
330 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
331 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
331 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
332 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
332 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
333 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
333 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
334
334
335 def __init__(self, key='', val='', type='unicode'):
335 def __init__(self, key='', val='', type='unicode'):
336 self.app_settings_name = key
336 self.app_settings_name = key
337 self.app_settings_type = type
337 self.app_settings_type = type
338 self.app_settings_value = val
338 self.app_settings_value = val
339
339
340 @validates('_app_settings_value')
340 @validates('_app_settings_value')
341 def validate_settings_value(self, key, val):
341 def validate_settings_value(self, key, val):
342 assert type(val) == unicode
342 assert type(val) == unicode
343 return val
343 return val
344
344
345 @hybrid_property
345 @hybrid_property
346 def app_settings_value(self):
346 def app_settings_value(self):
347 v = self._app_settings_value
347 v = self._app_settings_value
348 _type = self.app_settings_type
348 _type = self.app_settings_type
349 if _type:
349 if _type:
350 _type = self.app_settings_type.split('.')[0]
350 _type = self.app_settings_type.split('.')[0]
351 # decode the encrypted value
351 # decode the encrypted value
352 if 'encrypted' in self.app_settings_type:
352 if 'encrypted' in self.app_settings_type:
353 cipher = EncryptedTextValue()
353 cipher = EncryptedTextValue()
354 v = safe_unicode(cipher.process_result_value(v, None))
354 v = safe_unicode(cipher.process_result_value(v, None))
355
355
356 converter = self.SETTINGS_TYPES.get(_type) or \
356 converter = self.SETTINGS_TYPES.get(_type) or \
357 self.SETTINGS_TYPES['unicode']
357 self.SETTINGS_TYPES['unicode']
358 return converter(v)
358 return converter(v)
359
359
360 @app_settings_value.setter
360 @app_settings_value.setter
361 def app_settings_value(self, val):
361 def app_settings_value(self, val):
362 """
362 """
363 Setter that will always make sure we use unicode in app_settings_value
363 Setter that will always make sure we use unicode in app_settings_value
364
364
365 :param val:
365 :param val:
366 """
366 """
367 val = safe_unicode(val)
367 val = safe_unicode(val)
368 # encode the encrypted value
368 # encode the encrypted value
369 if 'encrypted' in self.app_settings_type:
369 if 'encrypted' in self.app_settings_type:
370 cipher = EncryptedTextValue()
370 cipher = EncryptedTextValue()
371 val = safe_unicode(cipher.process_bind_param(val, None))
371 val = safe_unicode(cipher.process_bind_param(val, None))
372 self._app_settings_value = val
372 self._app_settings_value = val
373
373
374 @hybrid_property
374 @hybrid_property
375 def app_settings_type(self):
375 def app_settings_type(self):
376 return self._app_settings_type
376 return self._app_settings_type
377
377
378 @app_settings_type.setter
378 @app_settings_type.setter
379 def app_settings_type(self, val):
379 def app_settings_type(self, val):
380 if val.split('.')[0] not in self.SETTINGS_TYPES:
380 if val.split('.')[0] not in self.SETTINGS_TYPES:
381 raise Exception('type must be one of %s got %s'
381 raise Exception('type must be one of %s got %s'
382 % (self.SETTINGS_TYPES.keys(), val))
382 % (self.SETTINGS_TYPES.keys(), val))
383 self._app_settings_type = val
383 self._app_settings_type = val
384
384
385 @classmethod
385 @classmethod
386 def get_by_prefix(cls, prefix):
386 def get_by_prefix(cls, prefix):
387 return RhodeCodeSetting.query()\
387 return RhodeCodeSetting.query()\
388 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
388 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
389 .all()
389 .all()
390
390
391 def __unicode__(self):
391 def __unicode__(self):
392 return u"<%s('%s:%s[%s]')>" % (
392 return u"<%s('%s:%s[%s]')>" % (
393 self.__class__.__name__,
393 self.__class__.__name__,
394 self.app_settings_name, self.app_settings_value,
394 self.app_settings_name, self.app_settings_value,
395 self.app_settings_type
395 self.app_settings_type
396 )
396 )
397
397
398
398
399 class RhodeCodeUi(Base, BaseModel):
399 class RhodeCodeUi(Base, BaseModel):
400 __tablename__ = 'rhodecode_ui'
400 __tablename__ = 'rhodecode_ui'
401 __table_args__ = (
401 __table_args__ = (
402 UniqueConstraint('ui_key'),
402 UniqueConstraint('ui_key'),
403 base_table_args
403 base_table_args
404 )
404 )
405
405
406 HOOK_REPO_SIZE = 'changegroup.repo_size'
406 HOOK_REPO_SIZE = 'changegroup.repo_size'
407 # HG
407 # HG
408 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
408 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
409 HOOK_PULL = 'outgoing.pull_logger'
409 HOOK_PULL = 'outgoing.pull_logger'
410 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
410 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
411 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
411 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
412 HOOK_PUSH = 'changegroup.push_logger'
412 HOOK_PUSH = 'changegroup.push_logger'
413 HOOK_PUSH_KEY = 'pushkey.key_push'
413 HOOK_PUSH_KEY = 'pushkey.key_push'
414
414
415 HOOKS_BUILTIN = [
415 HOOKS_BUILTIN = [
416 HOOK_PRE_PULL,
416 HOOK_PRE_PULL,
417 HOOK_PULL,
417 HOOK_PULL,
418 HOOK_PRE_PUSH,
418 HOOK_PRE_PUSH,
419 HOOK_PRETX_PUSH,
419 HOOK_PRETX_PUSH,
420 HOOK_PUSH,
420 HOOK_PUSH,
421 HOOK_PUSH_KEY,
421 HOOK_PUSH_KEY,
422 ]
422 ]
423
423
424 # TODO: johbo: Unify way how hooks are configured for git and hg,
424 # TODO: johbo: Unify way how hooks are configured for git and hg,
425 # git part is currently hardcoded.
425 # git part is currently hardcoded.
426
426
427 # SVN PATTERNS
427 # SVN PATTERNS
428 SVN_BRANCH_ID = 'vcs_svn_branch'
428 SVN_BRANCH_ID = 'vcs_svn_branch'
429 SVN_TAG_ID = 'vcs_svn_tag'
429 SVN_TAG_ID = 'vcs_svn_tag'
430
430
431 ui_id = Column(
431 ui_id = Column(
432 "ui_id", Integer(), nullable=False, unique=True, default=None,
432 "ui_id", Integer(), nullable=False, unique=True, default=None,
433 primary_key=True)
433 primary_key=True)
434 ui_section = Column(
434 ui_section = Column(
435 "ui_section", String(255), nullable=True, unique=None, default=None)
435 "ui_section", String(255), nullable=True, unique=None, default=None)
436 ui_key = Column(
436 ui_key = Column(
437 "ui_key", String(255), nullable=True, unique=None, default=None)
437 "ui_key", String(255), nullable=True, unique=None, default=None)
438 ui_value = Column(
438 ui_value = Column(
439 "ui_value", String(255), nullable=True, unique=None, default=None)
439 "ui_value", String(255), nullable=True, unique=None, default=None)
440 ui_active = Column(
440 ui_active = Column(
441 "ui_active", Boolean(), nullable=True, unique=None, default=True)
441 "ui_active", Boolean(), nullable=True, unique=None, default=True)
442
442
443 def __repr__(self):
443 def __repr__(self):
444 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
444 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
445 self.ui_key, self.ui_value)
445 self.ui_key, self.ui_value)
446
446
447
447
448 class RepoRhodeCodeSetting(Base, BaseModel):
448 class RepoRhodeCodeSetting(Base, BaseModel):
449 __tablename__ = 'repo_rhodecode_settings'
449 __tablename__ = 'repo_rhodecode_settings'
450 __table_args__ = (
450 __table_args__ = (
451 UniqueConstraint(
451 UniqueConstraint(
452 'app_settings_name', 'repository_id',
452 'app_settings_name', 'repository_id',
453 name='uq_repo_rhodecode_setting_name_repo_id'),
453 name='uq_repo_rhodecode_setting_name_repo_id'),
454 base_table_args
454 base_table_args
455 )
455 )
456
456
457 repository_id = Column(
457 repository_id = Column(
458 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
458 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
459 nullable=False)
459 nullable=False)
460 app_settings_id = Column(
460 app_settings_id = Column(
461 "app_settings_id", Integer(), nullable=False, unique=True,
461 "app_settings_id", Integer(), nullable=False, unique=True,
462 default=None, primary_key=True)
462 default=None, primary_key=True)
463 app_settings_name = Column(
463 app_settings_name = Column(
464 "app_settings_name", String(255), nullable=True, unique=None,
464 "app_settings_name", String(255), nullable=True, unique=None,
465 default=None)
465 default=None)
466 _app_settings_value = Column(
466 _app_settings_value = Column(
467 "app_settings_value", String(4096), nullable=True, unique=None,
467 "app_settings_value", String(4096), nullable=True, unique=None,
468 default=None)
468 default=None)
469 _app_settings_type = Column(
469 _app_settings_type = Column(
470 "app_settings_type", String(255), nullable=True, unique=None,
470 "app_settings_type", String(255), nullable=True, unique=None,
471 default=None)
471 default=None)
472
472
473 repository = relationship('Repository')
473 repository = relationship('Repository')
474
474
475 def __init__(self, repository_id, key='', val='', type='unicode'):
475 def __init__(self, repository_id, key='', val='', type='unicode'):
476 self.repository_id = repository_id
476 self.repository_id = repository_id
477 self.app_settings_name = key
477 self.app_settings_name = key
478 self.app_settings_type = type
478 self.app_settings_type = type
479 self.app_settings_value = val
479 self.app_settings_value = val
480
480
481 @validates('_app_settings_value')
481 @validates('_app_settings_value')
482 def validate_settings_value(self, key, val):
482 def validate_settings_value(self, key, val):
483 assert type(val) == unicode
483 assert type(val) == unicode
484 return val
484 return val
485
485
486 @hybrid_property
486 @hybrid_property
487 def app_settings_value(self):
487 def app_settings_value(self):
488 v = self._app_settings_value
488 v = self._app_settings_value
489 type_ = self.app_settings_type
489 type_ = self.app_settings_type
490 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
490 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
491 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
491 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
492 return converter(v)
492 return converter(v)
493
493
494 @app_settings_value.setter
494 @app_settings_value.setter
495 def app_settings_value(self, val):
495 def app_settings_value(self, val):
496 """
496 """
497 Setter that will always make sure we use unicode in app_settings_value
497 Setter that will always make sure we use unicode in app_settings_value
498
498
499 :param val:
499 :param val:
500 """
500 """
501 self._app_settings_value = safe_unicode(val)
501 self._app_settings_value = safe_unicode(val)
502
502
503 @hybrid_property
503 @hybrid_property
504 def app_settings_type(self):
504 def app_settings_type(self):
505 return self._app_settings_type
505 return self._app_settings_type
506
506
507 @app_settings_type.setter
507 @app_settings_type.setter
508 def app_settings_type(self, val):
508 def app_settings_type(self, val):
509 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
509 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
510 if val not in SETTINGS_TYPES:
510 if val not in SETTINGS_TYPES:
511 raise Exception('type must be one of %s got %s'
511 raise Exception('type must be one of %s got %s'
512 % (SETTINGS_TYPES.keys(), val))
512 % (SETTINGS_TYPES.keys(), val))
513 self._app_settings_type = val
513 self._app_settings_type = val
514
514
515 def __unicode__(self):
515 def __unicode__(self):
516 return u"<%s('%s:%s:%s[%s]')>" % (
516 return u"<%s('%s:%s:%s[%s]')>" % (
517 self.__class__.__name__, self.repository.repo_name,
517 self.__class__.__name__, self.repository.repo_name,
518 self.app_settings_name, self.app_settings_value,
518 self.app_settings_name, self.app_settings_value,
519 self.app_settings_type
519 self.app_settings_type
520 )
520 )
521
521
522
522
523 class RepoRhodeCodeUi(Base, BaseModel):
523 class RepoRhodeCodeUi(Base, BaseModel):
524 __tablename__ = 'repo_rhodecode_ui'
524 __tablename__ = 'repo_rhodecode_ui'
525 __table_args__ = (
525 __table_args__ = (
526 UniqueConstraint(
526 UniqueConstraint(
527 'repository_id', 'ui_section', 'ui_key',
527 'repository_id', 'ui_section', 'ui_key',
528 name='uq_repo_rhodecode_ui_repository_id_section_key'),
528 name='uq_repo_rhodecode_ui_repository_id_section_key'),
529 base_table_args
529 base_table_args
530 )
530 )
531
531
532 repository_id = Column(
532 repository_id = Column(
533 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
533 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
534 nullable=False)
534 nullable=False)
535 ui_id = Column(
535 ui_id = Column(
536 "ui_id", Integer(), nullable=False, unique=True, default=None,
536 "ui_id", Integer(), nullable=False, unique=True, default=None,
537 primary_key=True)
537 primary_key=True)
538 ui_section = Column(
538 ui_section = Column(
539 "ui_section", String(255), nullable=True, unique=None, default=None)
539 "ui_section", String(255), nullable=True, unique=None, default=None)
540 ui_key = Column(
540 ui_key = Column(
541 "ui_key", String(255), nullable=True, unique=None, default=None)
541 "ui_key", String(255), nullable=True, unique=None, default=None)
542 ui_value = Column(
542 ui_value = Column(
543 "ui_value", String(255), nullable=True, unique=None, default=None)
543 "ui_value", String(255), nullable=True, unique=None, default=None)
544 ui_active = Column(
544 ui_active = Column(
545 "ui_active", Boolean(), nullable=True, unique=None, default=True)
545 "ui_active", Boolean(), nullable=True, unique=None, default=True)
546
546
547 repository = relationship('Repository')
547 repository = relationship('Repository')
548
548
549 def __repr__(self):
549 def __repr__(self):
550 return '<%s[%s:%s]%s=>%s]>' % (
550 return '<%s[%s:%s]%s=>%s]>' % (
551 self.__class__.__name__, self.repository.repo_name,
551 self.__class__.__name__, self.repository.repo_name,
552 self.ui_section, self.ui_key, self.ui_value)
552 self.ui_section, self.ui_key, self.ui_value)
553
553
554
554
555 class User(Base, BaseModel):
555 class User(Base, BaseModel):
556 __tablename__ = 'users'
556 __tablename__ = 'users'
557 __table_args__ = (
557 __table_args__ = (
558 UniqueConstraint('username'), UniqueConstraint('email'),
558 UniqueConstraint('username'), UniqueConstraint('email'),
559 Index('u_username_idx', 'username'),
559 Index('u_username_idx', 'username'),
560 Index('u_email_idx', 'email'),
560 Index('u_email_idx', 'email'),
561 base_table_args
561 base_table_args
562 )
562 )
563
563
564 DEFAULT_USER = 'default'
564 DEFAULT_USER = 'default'
565 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
565 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
566 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
566 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
567
567
568 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
568 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
569 username = Column("username", String(255), nullable=True, unique=None, default=None)
569 username = Column("username", String(255), nullable=True, unique=None, default=None)
570 password = Column("password", String(255), nullable=True, unique=None, default=None)
570 password = Column("password", String(255), nullable=True, unique=None, default=None)
571 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
571 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
572 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
572 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
573 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
573 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
574 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
574 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
575 _email = Column("email", String(255), nullable=True, unique=None, default=None)
575 _email = Column("email", String(255), nullable=True, unique=None, default=None)
576 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
576 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
577 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
577 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
578
578
579 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
579 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
580 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
580 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
581 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
581 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
582 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
582 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
583 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
583 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
584 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
584 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
585
585
586 user_log = relationship('UserLog')
586 user_log = relationship('UserLog')
587 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
587 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
588
588
589 repositories = relationship('Repository')
589 repositories = relationship('Repository')
590 repository_groups = relationship('RepoGroup')
590 repository_groups = relationship('RepoGroup')
591 user_groups = relationship('UserGroup')
591 user_groups = relationship('UserGroup')
592
592
593 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
593 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
594 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
594 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
595
595
596 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
596 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
597 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
597 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
598 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
598 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
599
599
600 group_member = relationship('UserGroupMember', cascade='all')
600 group_member = relationship('UserGroupMember', cascade='all')
601
601
602 notifications = relationship('UserNotification', cascade='all')
602 notifications = relationship('UserNotification', cascade='all')
603 # notifications assigned to this user
603 # notifications assigned to this user
604 user_created_notifications = relationship('Notification', cascade='all')
604 user_created_notifications = relationship('Notification', cascade='all')
605 # comments created by this user
605 # comments created by this user
606 user_comments = relationship('ChangesetComment', cascade='all')
606 user_comments = relationship('ChangesetComment', cascade='all')
607 # user profile extra info
607 # user profile extra info
608 user_emails = relationship('UserEmailMap', cascade='all')
608 user_emails = relationship('UserEmailMap', cascade='all')
609 user_ip_map = relationship('UserIpMap', cascade='all')
609 user_ip_map = relationship('UserIpMap', cascade='all')
610 user_auth_tokens = relationship('UserApiKeys', cascade='all')
610 user_auth_tokens = relationship('UserApiKeys', cascade='all')
611 user_ssh_keys = relationship('UserSshKeys', cascade='all')
611 user_ssh_keys = relationship('UserSshKeys', cascade='all')
612
612
613 # gists
613 # gists
614 user_gists = relationship('Gist', cascade='all')
614 user_gists = relationship('Gist', cascade='all')
615 # user pull requests
615 # user pull requests
616 user_pull_requests = relationship('PullRequest', cascade='all')
616 user_pull_requests = relationship('PullRequest', cascade='all')
617 # external identities
617 # external identities
618 extenal_identities = relationship(
618 extenal_identities = relationship(
619 'ExternalIdentity',
619 'ExternalIdentity',
620 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
620 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
621 cascade='all')
621 cascade='all')
622 # review rules
622 # review rules
623 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
623 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
624
624
625 def __unicode__(self):
625 def __unicode__(self):
626 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
626 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
627 self.user_id, self.username)
627 self.user_id, self.username)
628
628
629 @hybrid_property
629 @hybrid_property
630 def email(self):
630 def email(self):
631 return self._email
631 return self._email
632
632
633 @email.setter
633 @email.setter
634 def email(self, val):
634 def email(self, val):
635 self._email = val.lower() if val else None
635 self._email = val.lower() if val else None
636
636
637 @hybrid_property
637 @hybrid_property
638 def first_name(self):
638 def first_name(self):
639 from rhodecode.lib import helpers as h
639 from rhodecode.lib import helpers as h
640 if self.name:
640 if self.name:
641 return h.escape(self.name)
641 return h.escape(self.name)
642 return self.name
642 return self.name
643
643
644 @hybrid_property
644 @hybrid_property
645 def last_name(self):
645 def last_name(self):
646 from rhodecode.lib import helpers as h
646 from rhodecode.lib import helpers as h
647 if self.lastname:
647 if self.lastname:
648 return h.escape(self.lastname)
648 return h.escape(self.lastname)
649 return self.lastname
649 return self.lastname
650
650
651 @hybrid_property
651 @hybrid_property
652 def api_key(self):
652 def api_key(self):
653 """
653 """
654 Fetch if exist an auth-token with role ALL connected to this user
654 Fetch if exist an auth-token with role ALL connected to this user
655 """
655 """
656 user_auth_token = UserApiKeys.query()\
656 user_auth_token = UserApiKeys.query()\
657 .filter(UserApiKeys.user_id == self.user_id)\
657 .filter(UserApiKeys.user_id == self.user_id)\
658 .filter(or_(UserApiKeys.expires == -1,
658 .filter(or_(UserApiKeys.expires == -1,
659 UserApiKeys.expires >= time.time()))\
659 UserApiKeys.expires >= time.time()))\
660 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
660 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
661 if user_auth_token:
661 if user_auth_token:
662 user_auth_token = user_auth_token.api_key
662 user_auth_token = user_auth_token.api_key
663
663
664 return user_auth_token
664 return user_auth_token
665
665
666 @api_key.setter
666 @api_key.setter
667 def api_key(self, val):
667 def api_key(self, val):
668 # don't allow to set API key this is deprecated for now
668 # don't allow to set API key this is deprecated for now
669 self._api_key = None
669 self._api_key = None
670
670
671 @property
671 @property
672 def reviewer_pull_requests(self):
672 def reviewer_pull_requests(self):
673 return PullRequestReviewers.query() \
673 return PullRequestReviewers.query() \
674 .options(joinedload(PullRequestReviewers.pull_request)) \
674 .options(joinedload(PullRequestReviewers.pull_request)) \
675 .filter(PullRequestReviewers.user_id == self.user_id) \
675 .filter(PullRequestReviewers.user_id == self.user_id) \
676 .all()
676 .all()
677
677
678 @property
678 @property
679 def firstname(self):
679 def firstname(self):
680 # alias for future
680 # alias for future
681 return self.name
681 return self.name
682
682
683 @property
683 @property
684 def emails(self):
684 def emails(self):
685 other = UserEmailMap.query()\
685 other = UserEmailMap.query()\
686 .filter(UserEmailMap.user == self) \
686 .filter(UserEmailMap.user == self) \
687 .order_by(UserEmailMap.email_id.asc()) \
687 .order_by(UserEmailMap.email_id.asc()) \
688 .all()
688 .all()
689 return [self.email] + [x.email for x in other]
689 return [self.email] + [x.email for x in other]
690
690
691 @property
691 @property
692 def auth_tokens(self):
692 def auth_tokens(self):
693 auth_tokens = self.get_auth_tokens()
693 auth_tokens = self.get_auth_tokens()
694 return [x.api_key for x in auth_tokens]
694 return [x.api_key for x in auth_tokens]
695
695
696 def get_auth_tokens(self):
696 def get_auth_tokens(self):
697 return UserApiKeys.query()\
697 return UserApiKeys.query()\
698 .filter(UserApiKeys.user == self)\
698 .filter(UserApiKeys.user == self)\
699 .order_by(UserApiKeys.user_api_key_id.asc())\
699 .order_by(UserApiKeys.user_api_key_id.asc())\
700 .all()
700 .all()
701
701
702 @LazyProperty
702 @LazyProperty
703 def feed_token(self):
703 def feed_token(self):
704 return self.get_feed_token()
704 return self.get_feed_token()
705
705
706 def get_feed_token(self, cache=True):
706 def get_feed_token(self, cache=True):
707 feed_tokens = UserApiKeys.query()\
707 feed_tokens = UserApiKeys.query()\
708 .filter(UserApiKeys.user == self)\
708 .filter(UserApiKeys.user == self)\
709 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
709 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
710 if cache:
710 if cache:
711 feed_tokens = feed_tokens.options(
711 feed_tokens = feed_tokens.options(
712 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
712 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
713
713
714 feed_tokens = feed_tokens.all()
714 feed_tokens = feed_tokens.all()
715 if feed_tokens:
715 if feed_tokens:
716 return feed_tokens[0].api_key
716 return feed_tokens[0].api_key
717 return 'NO_FEED_TOKEN_AVAILABLE'
717 return 'NO_FEED_TOKEN_AVAILABLE'
718
718
719 @classmethod
719 @classmethod
720 def get(cls, user_id, cache=False):
720 def get(cls, user_id, cache=False):
721 if not user_id:
721 if not user_id:
722 return
722 return
723
723
724 user = cls.query()
724 user = cls.query()
725 if cache:
725 if cache:
726 user = user.options(
726 user = user.options(
727 FromCache("sql_cache_short", "get_users_%s" % user_id))
727 FromCache("sql_cache_short", "get_users_%s" % user_id))
728 return user.get(user_id)
728 return user.get(user_id)
729
729
730 @classmethod
730 @classmethod
731 def extra_valid_auth_tokens(cls, user, role=None):
731 def extra_valid_auth_tokens(cls, user, role=None):
732 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
732 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
733 .filter(or_(UserApiKeys.expires == -1,
733 .filter(or_(UserApiKeys.expires == -1,
734 UserApiKeys.expires >= time.time()))
734 UserApiKeys.expires >= time.time()))
735 if role:
735 if role:
736 tokens = tokens.filter(or_(UserApiKeys.role == role,
736 tokens = tokens.filter(or_(UserApiKeys.role == role,
737 UserApiKeys.role == UserApiKeys.ROLE_ALL))
737 UserApiKeys.role == UserApiKeys.ROLE_ALL))
738 return tokens.all()
738 return tokens.all()
739
739
740 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
740 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
741 from rhodecode.lib import auth
741 from rhodecode.lib import auth
742
742
743 log.debug('Trying to authenticate user: %s via auth-token, '
743 log.debug('Trying to authenticate user: %s via auth-token, '
744 'and roles: %s', self, roles)
744 'and roles: %s', self, roles)
745
745
746 if not auth_token:
746 if not auth_token:
747 return False
747 return False
748
748
749 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
749 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
750 tokens_q = UserApiKeys.query()\
750 tokens_q = UserApiKeys.query()\
751 .filter(UserApiKeys.user_id == self.user_id)\
751 .filter(UserApiKeys.user_id == self.user_id)\
752 .filter(or_(UserApiKeys.expires == -1,
752 .filter(or_(UserApiKeys.expires == -1,
753 UserApiKeys.expires >= time.time()))
753 UserApiKeys.expires >= time.time()))
754
754
755 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
755 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
756
756
757 crypto_backend = auth.crypto_backend()
757 crypto_backend = auth.crypto_backend()
758 enc_token_map = {}
758 enc_token_map = {}
759 plain_token_map = {}
759 plain_token_map = {}
760 for token in tokens_q:
760 for token in tokens_q:
761 if token.api_key.startswith(crypto_backend.ENC_PREF):
761 if token.api_key.startswith(crypto_backend.ENC_PREF):
762 enc_token_map[token.api_key] = token
762 enc_token_map[token.api_key] = token
763 else:
763 else:
764 plain_token_map[token.api_key] = token
764 plain_token_map[token.api_key] = token
765 log.debug(
765 log.debug(
766 'Found %s plain and %s encrypted user tokens to check for authentication',
766 'Found %s plain and %s encrypted user tokens to check for authentication',
767 len(plain_token_map), len(enc_token_map))
767 len(plain_token_map), len(enc_token_map))
768
768
769 # plain token match comes first
769 # plain token match comes first
770 match = plain_token_map.get(auth_token)
770 match = plain_token_map.get(auth_token)
771
771
772 # check encrypted tokens now
772 # check encrypted tokens now
773 if not match:
773 if not match:
774 for token_hash, token in enc_token_map.items():
774 for token_hash, token in enc_token_map.items():
775 # NOTE(marcink): this is expensive to calculate, but most secure
775 # NOTE(marcink): this is expensive to calculate, but most secure
776 if crypto_backend.hash_check(auth_token, token_hash):
776 if crypto_backend.hash_check(auth_token, token_hash):
777 match = token
777 match = token
778 break
778 break
779
779
780 if match:
780 if match:
781 log.debug('Found matching token %s', match)
781 log.debug('Found matching token %s', match)
782 if match.repo_id:
782 if match.repo_id:
783 log.debug('Found scope, checking for scope match of token %s', match)
783 log.debug('Found scope, checking for scope match of token %s', match)
784 if match.repo_id == scope_repo_id:
784 if match.repo_id == scope_repo_id:
785 return True
785 return True
786 else:
786 else:
787 log.debug(
787 log.debug(
788 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
788 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
789 'and calling scope is:%s, skipping further checks',
789 'and calling scope is:%s, skipping further checks',
790 match.repo, scope_repo_id)
790 match.repo, scope_repo_id)
791 return False
791 return False
792 else:
792 else:
793 return True
793 return True
794
794
795 return False
795 return False
796
796
797 @property
797 @property
798 def ip_addresses(self):
798 def ip_addresses(self):
799 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
799 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
800 return [x.ip_addr for x in ret]
800 return [x.ip_addr for x in ret]
801
801
802 @property
802 @property
803 def username_and_name(self):
803 def username_and_name(self):
804 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
804 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
805
805
806 @property
806 @property
807 def username_or_name_or_email(self):
807 def username_or_name_or_email(self):
808 full_name = self.full_name if self.full_name is not ' ' else None
808 full_name = self.full_name if self.full_name is not ' ' else None
809 return self.username or full_name or self.email
809 return self.username or full_name or self.email
810
810
811 @property
811 @property
812 def full_name(self):
812 def full_name(self):
813 return '%s %s' % (self.first_name, self.last_name)
813 return '%s %s' % (self.first_name, self.last_name)
814
814
815 @property
815 @property
816 def full_name_or_username(self):
816 def full_name_or_username(self):
817 return ('%s %s' % (self.first_name, self.last_name)
817 return ('%s %s' % (self.first_name, self.last_name)
818 if (self.first_name and self.last_name) else self.username)
818 if (self.first_name and self.last_name) else self.username)
819
819
820 @property
820 @property
821 def full_contact(self):
821 def full_contact(self):
822 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
822 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
823
823
824 @property
824 @property
825 def short_contact(self):
825 def short_contact(self):
826 return '%s %s' % (self.first_name, self.last_name)
826 return '%s %s' % (self.first_name, self.last_name)
827
827
828 @property
828 @property
829 def is_admin(self):
829 def is_admin(self):
830 return self.admin
830 return self.admin
831
831
832 def AuthUser(self, **kwargs):
832 def AuthUser(self, **kwargs):
833 """
833 """
834 Returns instance of AuthUser for this user
834 Returns instance of AuthUser for this user
835 """
835 """
836 from rhodecode.lib.auth import AuthUser
836 from rhodecode.lib.auth import AuthUser
837 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
837 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
838
838
839 @hybrid_property
839 @hybrid_property
840 def user_data(self):
840 def user_data(self):
841 if not self._user_data:
841 if not self._user_data:
842 return {}
842 return {}
843
843
844 try:
844 try:
845 return json.loads(self._user_data)
845 return json.loads(self._user_data)
846 except TypeError:
846 except TypeError:
847 return {}
847 return {}
848
848
849 @user_data.setter
849 @user_data.setter
850 def user_data(self, val):
850 def user_data(self, val):
851 if not isinstance(val, dict):
851 if not isinstance(val, dict):
852 raise Exception('user_data must be dict, got %s' % type(val))
852 raise Exception('user_data must be dict, got %s' % type(val))
853 try:
853 try:
854 self._user_data = json.dumps(val)
854 self._user_data = json.dumps(val)
855 except Exception:
855 except Exception:
856 log.error(traceback.format_exc())
856 log.error(traceback.format_exc())
857
857
858 @classmethod
858 @classmethod
859 def get_by_username(cls, username, case_insensitive=False,
859 def get_by_username(cls, username, case_insensitive=False,
860 cache=False, identity_cache=False):
860 cache=False, identity_cache=False):
861 session = Session()
861 session = Session()
862
862
863 if case_insensitive:
863 if case_insensitive:
864 q = cls.query().filter(
864 q = cls.query().filter(
865 func.lower(cls.username) == func.lower(username))
865 func.lower(cls.username) == func.lower(username))
866 else:
866 else:
867 q = cls.query().filter(cls.username == username)
867 q = cls.query().filter(cls.username == username)
868
868
869 if cache:
869 if cache:
870 if identity_cache:
870 if identity_cache:
871 val = cls.identity_cache(session, 'username', username)
871 val = cls.identity_cache(session, 'username', username)
872 if val:
872 if val:
873 return val
873 return val
874 else:
874 else:
875 cache_key = "get_user_by_name_%s" % _hash_key(username)
875 cache_key = "get_user_by_name_%s" % _hash_key(username)
876 q = q.options(
876 q = q.options(
877 FromCache("sql_cache_short", cache_key))
877 FromCache("sql_cache_short", cache_key))
878
878
879 return q.scalar()
879 return q.scalar()
880
880
881 @classmethod
881 @classmethod
882 def get_by_auth_token(cls, auth_token, cache=False):
882 def get_by_auth_token(cls, auth_token, cache=False):
883 q = UserApiKeys.query()\
883 q = UserApiKeys.query()\
884 .filter(UserApiKeys.api_key == auth_token)\
884 .filter(UserApiKeys.api_key == auth_token)\
885 .filter(or_(UserApiKeys.expires == -1,
885 .filter(or_(UserApiKeys.expires == -1,
886 UserApiKeys.expires >= time.time()))
886 UserApiKeys.expires >= time.time()))
887 if cache:
887 if cache:
888 q = q.options(
888 q = q.options(
889 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
889 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
890
890
891 match = q.first()
891 match = q.first()
892 if match:
892 if match:
893 return match.user
893 return match.user
894
894
895 @classmethod
895 @classmethod
896 def get_by_email(cls, email, case_insensitive=False, cache=False):
896 def get_by_email(cls, email, case_insensitive=False, cache=False):
897
897
898 if case_insensitive:
898 if case_insensitive:
899 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
899 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
900
900
901 else:
901 else:
902 q = cls.query().filter(cls.email == email)
902 q = cls.query().filter(cls.email == email)
903
903
904 email_key = _hash_key(email)
904 email_key = _hash_key(email)
905 if cache:
905 if cache:
906 q = q.options(
906 q = q.options(
907 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
907 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
908
908
909 ret = q.scalar()
909 ret = q.scalar()
910 if ret is None:
910 if ret is None:
911 q = UserEmailMap.query()
911 q = UserEmailMap.query()
912 # try fetching in alternate email map
912 # try fetching in alternate email map
913 if case_insensitive:
913 if case_insensitive:
914 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
914 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
915 else:
915 else:
916 q = q.filter(UserEmailMap.email == email)
916 q = q.filter(UserEmailMap.email == email)
917 q = q.options(joinedload(UserEmailMap.user))
917 q = q.options(joinedload(UserEmailMap.user))
918 if cache:
918 if cache:
919 q = q.options(
919 q = q.options(
920 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
920 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
921 ret = getattr(q.scalar(), 'user', None)
921 ret = getattr(q.scalar(), 'user', None)
922
922
923 return ret
923 return ret
924
924
925 @classmethod
925 @classmethod
926 def get_from_cs_author(cls, author):
926 def get_from_cs_author(cls, author):
927 """
927 """
928 Tries to get User objects out of commit author string
928 Tries to get User objects out of commit author string
929
929
930 :param author:
930 :param author:
931 """
931 """
932 from rhodecode.lib.helpers import email, author_name
932 from rhodecode.lib.helpers import email, author_name
933 # Valid email in the attribute passed, see if they're in the system
933 # Valid email in the attribute passed, see if they're in the system
934 _email = email(author)
934 _email = email(author)
935 if _email:
935 if _email:
936 user = cls.get_by_email(_email, case_insensitive=True)
936 user = cls.get_by_email(_email, case_insensitive=True)
937 if user:
937 if user:
938 return user
938 return user
939 # Maybe we can match by username?
939 # Maybe we can match by username?
940 _author = author_name(author)
940 _author = author_name(author)
941 user = cls.get_by_username(_author, case_insensitive=True)
941 user = cls.get_by_username(_author, case_insensitive=True)
942 if user:
942 if user:
943 return user
943 return user
944
944
945 def update_userdata(self, **kwargs):
945 def update_userdata(self, **kwargs):
946 usr = self
946 usr = self
947 old = usr.user_data
947 old = usr.user_data
948 old.update(**kwargs)
948 old.update(**kwargs)
949 usr.user_data = old
949 usr.user_data = old
950 Session().add(usr)
950 Session().add(usr)
951 log.debug('updated userdata with ', kwargs)
951 log.debug('updated userdata with ', kwargs)
952
952
953 def update_lastlogin(self):
953 def update_lastlogin(self):
954 """Update user lastlogin"""
954 """Update user lastlogin"""
955 self.last_login = datetime.datetime.now()
955 self.last_login = datetime.datetime.now()
956 Session().add(self)
956 Session().add(self)
957 log.debug('updated user %s lastlogin', self.username)
957 log.debug('updated user %s lastlogin', self.username)
958
958
959 def update_password(self, new_password):
959 def update_password(self, new_password):
960 from rhodecode.lib.auth import get_crypt_password
960 from rhodecode.lib.auth import get_crypt_password
961
961
962 self.password = get_crypt_password(new_password)
962 self.password = get_crypt_password(new_password)
963 Session().add(self)
963 Session().add(self)
964
964
965 @classmethod
965 @classmethod
966 def get_first_super_admin(cls):
966 def get_first_super_admin(cls):
967 user = User.query()\
967 user = User.query()\
968 .filter(User.admin == true()) \
968 .filter(User.admin == true()) \
969 .order_by(User.user_id.asc()) \
969 .order_by(User.user_id.asc()) \
970 .first()
970 .first()
971
971
972 if user is None:
972 if user is None:
973 raise Exception('FATAL: Missing administrative account!')
973 raise Exception('FATAL: Missing administrative account!')
974 return user
974 return user
975
975
976 @classmethod
976 @classmethod
977 def get_all_super_admins(cls, only_active=False):
977 def get_all_super_admins(cls, only_active=False):
978 """
978 """
979 Returns all admin accounts sorted by username
979 Returns all admin accounts sorted by username
980 """
980 """
981 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
981 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
982 if only_active:
982 if only_active:
983 qry = qry.filter(User.active == true())
983 qry = qry.filter(User.active == true())
984 return qry.all()
984 return qry.all()
985
985
986 @classmethod
986 @classmethod
987 def get_default_user(cls, cache=False, refresh=False):
987 def get_default_user(cls, cache=False, refresh=False):
988 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
988 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
989 if user is None:
989 if user is None:
990 raise Exception('FATAL: Missing default account!')
990 raise Exception('FATAL: Missing default account!')
991 if refresh:
991 if refresh:
992 # The default user might be based on outdated state which
992 # The default user might be based on outdated state which
993 # has been loaded from the cache.
993 # has been loaded from the cache.
994 # A call to refresh() ensures that the
994 # A call to refresh() ensures that the
995 # latest state from the database is used.
995 # latest state from the database is used.
996 Session().refresh(user)
996 Session().refresh(user)
997 return user
997 return user
998
998
999 def _get_default_perms(self, user, suffix=''):
999 def _get_default_perms(self, user, suffix=''):
1000 from rhodecode.model.permission import PermissionModel
1000 from rhodecode.model.permission import PermissionModel
1001 return PermissionModel().get_default_perms(user.user_perms, suffix)
1001 return PermissionModel().get_default_perms(user.user_perms, suffix)
1002
1002
1003 def get_default_perms(self, suffix=''):
1003 def get_default_perms(self, suffix=''):
1004 return self._get_default_perms(self, suffix)
1004 return self._get_default_perms(self, suffix)
1005
1005
1006 def get_api_data(self, include_secrets=False, details='full'):
1006 def get_api_data(self, include_secrets=False, details='full'):
1007 """
1007 """
1008 Common function for generating user related data for API
1008 Common function for generating user related data for API
1009
1009
1010 :param include_secrets: By default secrets in the API data will be replaced
1010 :param include_secrets: By default secrets in the API data will be replaced
1011 by a placeholder value to prevent exposing this data by accident. In case
1011 by a placeholder value to prevent exposing this data by accident. In case
1012 this data shall be exposed, set this flag to ``True``.
1012 this data shall be exposed, set this flag to ``True``.
1013
1013
1014 :param details: details can be 'basic|full' basic gives only a subset of
1014 :param details: details can be 'basic|full' basic gives only a subset of
1015 the available user information that includes user_id, name and emails.
1015 the available user information that includes user_id, name and emails.
1016 """
1016 """
1017 user = self
1017 user = self
1018 user_data = self.user_data
1018 user_data = self.user_data
1019 data = {
1019 data = {
1020 'user_id': user.user_id,
1020 'user_id': user.user_id,
1021 'username': user.username,
1021 'username': user.username,
1022 'firstname': user.name,
1022 'firstname': user.name,
1023 'lastname': user.lastname,
1023 'lastname': user.lastname,
1024 'email': user.email,
1024 'email': user.email,
1025 'emails': user.emails,
1025 'emails': user.emails,
1026 }
1026 }
1027 if details == 'basic':
1027 if details == 'basic':
1028 return data
1028 return data
1029
1029
1030 auth_token_length = 40
1030 auth_token_length = 40
1031 auth_token_replacement = '*' * auth_token_length
1031 auth_token_replacement = '*' * auth_token_length
1032
1032
1033 extras = {
1033 extras = {
1034 'auth_tokens': [auth_token_replacement],
1034 'auth_tokens': [auth_token_replacement],
1035 'active': user.active,
1035 'active': user.active,
1036 'admin': user.admin,
1036 'admin': user.admin,
1037 'extern_type': user.extern_type,
1037 'extern_type': user.extern_type,
1038 'extern_name': user.extern_name,
1038 'extern_name': user.extern_name,
1039 'last_login': user.last_login,
1039 'last_login': user.last_login,
1040 'last_activity': user.last_activity,
1040 'last_activity': user.last_activity,
1041 'ip_addresses': user.ip_addresses,
1041 'ip_addresses': user.ip_addresses,
1042 'language': user_data.get('language')
1042 'language': user_data.get('language')
1043 }
1043 }
1044 data.update(extras)
1044 data.update(extras)
1045
1045
1046 if include_secrets:
1046 if include_secrets:
1047 data['auth_tokens'] = user.auth_tokens
1047 data['auth_tokens'] = user.auth_tokens
1048 return data
1048 return data
1049
1049
1050 def __json__(self):
1050 def __json__(self):
1051 data = {
1051 data = {
1052 'full_name': self.full_name,
1052 'full_name': self.full_name,
1053 'full_name_or_username': self.full_name_or_username,
1053 'full_name_or_username': self.full_name_or_username,
1054 'short_contact': self.short_contact,
1054 'short_contact': self.short_contact,
1055 'full_contact': self.full_contact,
1055 'full_contact': self.full_contact,
1056 }
1056 }
1057 data.update(self.get_api_data())
1057 data.update(self.get_api_data())
1058 return data
1058 return data
1059
1059
1060
1060
1061 class UserApiKeys(Base, BaseModel):
1061 class UserApiKeys(Base, BaseModel):
1062 __tablename__ = 'user_api_keys'
1062 __tablename__ = 'user_api_keys'
1063 __table_args__ = (
1063 __table_args__ = (
1064 Index('uak_api_key_idx', 'api_key', unique=True),
1064 Index('uak_api_key_idx', 'api_key', unique=True),
1065 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1065 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1066 base_table_args
1066 base_table_args
1067 )
1067 )
1068 __mapper_args__ = {}
1068 __mapper_args__ = {}
1069
1069
1070 # ApiKey role
1070 # ApiKey role
1071 ROLE_ALL = 'token_role_all'
1071 ROLE_ALL = 'token_role_all'
1072 ROLE_HTTP = 'token_role_http'
1072 ROLE_HTTP = 'token_role_http'
1073 ROLE_VCS = 'token_role_vcs'
1073 ROLE_VCS = 'token_role_vcs'
1074 ROLE_API = 'token_role_api'
1074 ROLE_API = 'token_role_api'
1075 ROLE_FEED = 'token_role_feed'
1075 ROLE_FEED = 'token_role_feed'
1076 ROLE_PASSWORD_RESET = 'token_password_reset'
1076 ROLE_PASSWORD_RESET = 'token_password_reset'
1077
1077
1078 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1078 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1079
1079
1080 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1080 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1081 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1081 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1082 api_key = Column("api_key", String(255), nullable=False, unique=True)
1082 api_key = Column("api_key", String(255), nullable=False, unique=True)
1083 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1083 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1084 expires = Column('expires', Float(53), nullable=False)
1084 expires = Column('expires', Float(53), nullable=False)
1085 role = Column('role', String(255), nullable=True)
1085 role = Column('role', String(255), nullable=True)
1086 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1086 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1087
1087
1088 # scope columns
1088 # scope columns
1089 repo_id = Column(
1089 repo_id = Column(
1090 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1090 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1091 nullable=True, unique=None, default=None)
1091 nullable=True, unique=None, default=None)
1092 repo = relationship('Repository', lazy='joined')
1092 repo = relationship('Repository', lazy='joined')
1093
1093
1094 repo_group_id = Column(
1094 repo_group_id = Column(
1095 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1095 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1096 nullable=True, unique=None, default=None)
1096 nullable=True, unique=None, default=None)
1097 repo_group = relationship('RepoGroup', lazy='joined')
1097 repo_group = relationship('RepoGroup', lazy='joined')
1098
1098
1099 user = relationship('User', lazy='joined')
1099 user = relationship('User', lazy='joined')
1100
1100
1101 def __unicode__(self):
1101 def __unicode__(self):
1102 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1102 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1103
1103
1104 def __json__(self):
1104 def __json__(self):
1105 data = {
1105 data = {
1106 'auth_token': self.api_key,
1106 'auth_token': self.api_key,
1107 'role': self.role,
1107 'role': self.role,
1108 'scope': self.scope_humanized,
1108 'scope': self.scope_humanized,
1109 'expired': self.expired
1109 'expired': self.expired
1110 }
1110 }
1111 return data
1111 return data
1112
1112
1113 def get_api_data(self, include_secrets=False):
1113 def get_api_data(self, include_secrets=False):
1114 data = self.__json__()
1114 data = self.__json__()
1115 if include_secrets:
1115 if include_secrets:
1116 return data
1116 return data
1117 else:
1117 else:
1118 data['auth_token'] = self.token_obfuscated
1118 data['auth_token'] = self.token_obfuscated
1119 return data
1119 return data
1120
1120
1121 @hybrid_property
1121 @hybrid_property
1122 def description_safe(self):
1122 def description_safe(self):
1123 from rhodecode.lib import helpers as h
1123 from rhodecode.lib import helpers as h
1124 return h.escape(self.description)
1124 return h.escape(self.description)
1125
1125
1126 @property
1126 @property
1127 def expired(self):
1127 def expired(self):
1128 if self.expires == -1:
1128 if self.expires == -1:
1129 return False
1129 return False
1130 return time.time() > self.expires
1130 return time.time() > self.expires
1131
1131
1132 @classmethod
1132 @classmethod
1133 def _get_role_name(cls, role):
1133 def _get_role_name(cls, role):
1134 return {
1134 return {
1135 cls.ROLE_ALL: _('all'),
1135 cls.ROLE_ALL: _('all'),
1136 cls.ROLE_HTTP: _('http/web interface'),
1136 cls.ROLE_HTTP: _('http/web interface'),
1137 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1137 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1138 cls.ROLE_API: _('api calls'),
1138 cls.ROLE_API: _('api calls'),
1139 cls.ROLE_FEED: _('feed access'),
1139 cls.ROLE_FEED: _('feed access'),
1140 }.get(role, role)
1140 }.get(role, role)
1141
1141
1142 @property
1142 @property
1143 def role_humanized(self):
1143 def role_humanized(self):
1144 return self._get_role_name(self.role)
1144 return self._get_role_name(self.role)
1145
1145
1146 def _get_scope(self):
1146 def _get_scope(self):
1147 if self.repo:
1147 if self.repo:
1148 return 'Repository: {}'.format(self.repo.repo_name)
1148 return 'Repository: {}'.format(self.repo.repo_name)
1149 if self.repo_group:
1149 if self.repo_group:
1150 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1150 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1151 return 'Global'
1151 return 'Global'
1152
1152
1153 @property
1153 @property
1154 def scope_humanized(self):
1154 def scope_humanized(self):
1155 return self._get_scope()
1155 return self._get_scope()
1156
1156
1157 @property
1157 @property
1158 def token_obfuscated(self):
1158 def token_obfuscated(self):
1159 if self.api_key:
1159 if self.api_key:
1160 return self.api_key[:4] + "****"
1160 return self.api_key[:4] + "****"
1161
1161
1162
1162
1163 class UserEmailMap(Base, BaseModel):
1163 class UserEmailMap(Base, BaseModel):
1164 __tablename__ = 'user_email_map'
1164 __tablename__ = 'user_email_map'
1165 __table_args__ = (
1165 __table_args__ = (
1166 Index('uem_email_idx', 'email'),
1166 Index('uem_email_idx', 'email'),
1167 UniqueConstraint('email'),
1167 UniqueConstraint('email'),
1168 base_table_args
1168 base_table_args
1169 )
1169 )
1170 __mapper_args__ = {}
1170 __mapper_args__ = {}
1171
1171
1172 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1172 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1173 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1173 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1174 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1174 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1175 user = relationship('User', lazy='joined')
1175 user = relationship('User', lazy='joined')
1176
1176
1177 @validates('_email')
1177 @validates('_email')
1178 def validate_email(self, key, email):
1178 def validate_email(self, key, email):
1179 # check if this email is not main one
1179 # check if this email is not main one
1180 main_email = Session().query(User).filter(User.email == email).scalar()
1180 main_email = Session().query(User).filter(User.email == email).scalar()
1181 if main_email is not None:
1181 if main_email is not None:
1182 raise AttributeError('email %s is present is user table' % email)
1182 raise AttributeError('email %s is present is user table' % email)
1183 return email
1183 return email
1184
1184
1185 @hybrid_property
1185 @hybrid_property
1186 def email(self):
1186 def email(self):
1187 return self._email
1187 return self._email
1188
1188
1189 @email.setter
1189 @email.setter
1190 def email(self, val):
1190 def email(self, val):
1191 self._email = val.lower() if val else None
1191 self._email = val.lower() if val else None
1192
1192
1193
1193
1194 class UserIpMap(Base, BaseModel):
1194 class UserIpMap(Base, BaseModel):
1195 __tablename__ = 'user_ip_map'
1195 __tablename__ = 'user_ip_map'
1196 __table_args__ = (
1196 __table_args__ = (
1197 UniqueConstraint('user_id', 'ip_addr'),
1197 UniqueConstraint('user_id', 'ip_addr'),
1198 base_table_args
1198 base_table_args
1199 )
1199 )
1200 __mapper_args__ = {}
1200 __mapper_args__ = {}
1201
1201
1202 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1202 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1203 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1203 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1204 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1204 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1205 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1205 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1206 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1206 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1207 user = relationship('User', lazy='joined')
1207 user = relationship('User', lazy='joined')
1208
1208
1209 @hybrid_property
1209 @hybrid_property
1210 def description_safe(self):
1210 def description_safe(self):
1211 from rhodecode.lib import helpers as h
1211 from rhodecode.lib import helpers as h
1212 return h.escape(self.description)
1212 return h.escape(self.description)
1213
1213
1214 @classmethod
1214 @classmethod
1215 def _get_ip_range(cls, ip_addr):
1215 def _get_ip_range(cls, ip_addr):
1216 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1216 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1217 return [str(net.network_address), str(net.broadcast_address)]
1217 return [str(net.network_address), str(net.broadcast_address)]
1218
1218
1219 def __json__(self):
1219 def __json__(self):
1220 return {
1220 return {
1221 'ip_addr': self.ip_addr,
1221 'ip_addr': self.ip_addr,
1222 'ip_range': self._get_ip_range(self.ip_addr),
1222 'ip_range': self._get_ip_range(self.ip_addr),
1223 }
1223 }
1224
1224
1225 def __unicode__(self):
1225 def __unicode__(self):
1226 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1226 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1227 self.user_id, self.ip_addr)
1227 self.user_id, self.ip_addr)
1228
1228
1229
1229
1230 class UserSshKeys(Base, BaseModel):
1230 class UserSshKeys(Base, BaseModel):
1231 __tablename__ = 'user_ssh_keys'
1231 __tablename__ = 'user_ssh_keys'
1232 __table_args__ = (
1232 __table_args__ = (
1233 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1233 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1234
1234
1235 UniqueConstraint('ssh_key_fingerprint'),
1235 UniqueConstraint('ssh_key_fingerprint'),
1236
1236
1237 base_table_args
1237 base_table_args
1238 )
1238 )
1239 __mapper_args__ = {}
1239 __mapper_args__ = {}
1240
1240
1241 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1241 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1242 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1242 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1243 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1243 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1244
1244
1245 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1245 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1246
1246
1247 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1247 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1248 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1248 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1249 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1249 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1250
1250
1251 user = relationship('User', lazy='joined')
1251 user = relationship('User', lazy='joined')
1252
1252
1253 def __json__(self):
1253 def __json__(self):
1254 data = {
1254 data = {
1255 'ssh_fingerprint': self.ssh_key_fingerprint,
1255 'ssh_fingerprint': self.ssh_key_fingerprint,
1256 'description': self.description,
1256 'description': self.description,
1257 'created_on': self.created_on
1257 'created_on': self.created_on
1258 }
1258 }
1259 return data
1259 return data
1260
1260
1261 def get_api_data(self):
1261 def get_api_data(self):
1262 data = self.__json__()
1262 data = self.__json__()
1263 return data
1263 return data
1264
1264
1265
1265
1266 class UserLog(Base, BaseModel):
1266 class UserLog(Base, BaseModel):
1267 __tablename__ = 'user_logs'
1267 __tablename__ = 'user_logs'
1268 __table_args__ = (
1268 __table_args__ = (
1269 base_table_args,
1269 base_table_args,
1270 )
1270 )
1271
1271
1272 VERSION_1 = 'v1'
1272 VERSION_1 = 'v1'
1273 VERSION_2 = 'v2'
1273 VERSION_2 = 'v2'
1274 VERSIONS = [VERSION_1, VERSION_2]
1274 VERSIONS = [VERSION_1, VERSION_2]
1275
1275
1276 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1276 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1277 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1277 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1278 username = Column("username", String(255), nullable=True, unique=None, default=None)
1278 username = Column("username", String(255), nullable=True, unique=None, default=None)
1279 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1279 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1280 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1280 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1281 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1281 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1282 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1282 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1283 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1283 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1284
1284
1285 version = Column("version", String(255), nullable=True, default=VERSION_1)
1285 version = Column("version", String(255), nullable=True, default=VERSION_1)
1286 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1286 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1287 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1287 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1288
1288
1289 def __unicode__(self):
1289 def __unicode__(self):
1290 return u"<%s('id:%s:%s')>" % (
1290 return u"<%s('id:%s:%s')>" % (
1291 self.__class__.__name__, self.repository_name, self.action)
1291 self.__class__.__name__, self.repository_name, self.action)
1292
1292
1293 def __json__(self):
1293 def __json__(self):
1294 return {
1294 return {
1295 'user_id': self.user_id,
1295 'user_id': self.user_id,
1296 'username': self.username,
1296 'username': self.username,
1297 'repository_id': self.repository_id,
1297 'repository_id': self.repository_id,
1298 'repository_name': self.repository_name,
1298 'repository_name': self.repository_name,
1299 'user_ip': self.user_ip,
1299 'user_ip': self.user_ip,
1300 'action_date': self.action_date,
1300 'action_date': self.action_date,
1301 'action': self.action,
1301 'action': self.action,
1302 }
1302 }
1303
1303
1304 @hybrid_property
1304 @hybrid_property
1305 def entry_id(self):
1305 def entry_id(self):
1306 return self.user_log_id
1306 return self.user_log_id
1307
1307
1308 @property
1308 @property
1309 def action_as_day(self):
1309 def action_as_day(self):
1310 return datetime.date(*self.action_date.timetuple()[:3])
1310 return datetime.date(*self.action_date.timetuple()[:3])
1311
1311
1312 user = relationship('User')
1312 user = relationship('User')
1313 repository = relationship('Repository', cascade='')
1313 repository = relationship('Repository', cascade='')
1314
1314
1315
1315
1316 class UserGroup(Base, BaseModel):
1316 class UserGroup(Base, BaseModel):
1317 __tablename__ = 'users_groups'
1317 __tablename__ = 'users_groups'
1318 __table_args__ = (
1318 __table_args__ = (
1319 base_table_args,
1319 base_table_args,
1320 )
1320 )
1321
1321
1322 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1322 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1323 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1323 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1324 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1324 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1325 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1325 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1326 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1326 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1327 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1327 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1328 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1328 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1329 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1329 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1330
1330
1331 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1331 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1332 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1332 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1333 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1333 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1334 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1334 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1335 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1335 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1336 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1336 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1337
1337
1338 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1338 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1339 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1339 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1340
1340
1341 @classmethod
1341 @classmethod
1342 def _load_group_data(cls, column):
1342 def _load_group_data(cls, column):
1343 if not column:
1343 if not column:
1344 return {}
1344 return {}
1345
1345
1346 try:
1346 try:
1347 return json.loads(column) or {}
1347 return json.loads(column) or {}
1348 except TypeError:
1348 except TypeError:
1349 return {}
1349 return {}
1350
1350
1351 @hybrid_property
1351 @hybrid_property
1352 def description_safe(self):
1352 def description_safe(self):
1353 from rhodecode.lib import helpers as h
1353 from rhodecode.lib import helpers as h
1354 return h.escape(self.user_group_description)
1354 return h.escape(self.user_group_description)
1355
1355
1356 @hybrid_property
1356 @hybrid_property
1357 def group_data(self):
1357 def group_data(self):
1358 return self._load_group_data(self._group_data)
1358 return self._load_group_data(self._group_data)
1359
1359
1360 @group_data.expression
1360 @group_data.expression
1361 def group_data(self, **kwargs):
1361 def group_data(self, **kwargs):
1362 return self._group_data
1362 return self._group_data
1363
1363
1364 @group_data.setter
1364 @group_data.setter
1365 def group_data(self, val):
1365 def group_data(self, val):
1366 try:
1366 try:
1367 self._group_data = json.dumps(val)
1367 self._group_data = json.dumps(val)
1368 except Exception:
1368 except Exception:
1369 log.error(traceback.format_exc())
1369 log.error(traceback.format_exc())
1370
1370
1371 @classmethod
1371 @classmethod
1372 def _load_sync(cls, group_data):
1372 def _load_sync(cls, group_data):
1373 if group_data:
1373 if group_data:
1374 return group_data.get('extern_type')
1374 return group_data.get('extern_type')
1375
1375
1376 @property
1376 @property
1377 def sync(self):
1377 def sync(self):
1378 return self._load_sync(self.group_data)
1378 return self._load_sync(self.group_data)
1379
1379
1380 def __unicode__(self):
1380 def __unicode__(self):
1381 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1381 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1382 self.users_group_id,
1382 self.users_group_id,
1383 self.users_group_name)
1383 self.users_group_name)
1384
1384
1385 @classmethod
1385 @classmethod
1386 def get_by_group_name(cls, group_name, cache=False,
1386 def get_by_group_name(cls, group_name, cache=False,
1387 case_insensitive=False):
1387 case_insensitive=False):
1388 if case_insensitive:
1388 if case_insensitive:
1389 q = cls.query().filter(func.lower(cls.users_group_name) ==
1389 q = cls.query().filter(func.lower(cls.users_group_name) ==
1390 func.lower(group_name))
1390 func.lower(group_name))
1391
1391
1392 else:
1392 else:
1393 q = cls.query().filter(cls.users_group_name == group_name)
1393 q = cls.query().filter(cls.users_group_name == group_name)
1394 if cache:
1394 if cache:
1395 q = q.options(
1395 q = q.options(
1396 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1396 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1397 return q.scalar()
1397 return q.scalar()
1398
1398
1399 @classmethod
1399 @classmethod
1400 def get(cls, user_group_id, cache=False):
1400 def get(cls, user_group_id, cache=False):
1401 if not user_group_id:
1401 if not user_group_id:
1402 return
1402 return
1403
1403
1404 user_group = cls.query()
1404 user_group = cls.query()
1405 if cache:
1405 if cache:
1406 user_group = user_group.options(
1406 user_group = user_group.options(
1407 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1407 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1408 return user_group.get(user_group_id)
1408 return user_group.get(user_group_id)
1409
1409
1410 def permissions(self, with_admins=True, with_owner=True,
1410 def permissions(self, with_admins=True, with_owner=True,
1411 expand_from_user_groups=False):
1411 expand_from_user_groups=False):
1412 """
1412 """
1413 Permissions for user groups
1413 Permissions for user groups
1414 """
1414 """
1415 _admin_perm = 'usergroup.admin'
1415 _admin_perm = 'usergroup.admin'
1416
1416
1417 owner_row = []
1417 owner_row = []
1418 if with_owner:
1418 if with_owner:
1419 usr = AttributeDict(self.user.get_dict())
1419 usr = AttributeDict(self.user.get_dict())
1420 usr.owner_row = True
1420 usr.owner_row = True
1421 usr.permission = _admin_perm
1421 usr.permission = _admin_perm
1422 owner_row.append(usr)
1422 owner_row.append(usr)
1423
1423
1424 super_admin_ids = []
1424 super_admin_ids = []
1425 super_admin_rows = []
1425 super_admin_rows = []
1426 if with_admins:
1426 if with_admins:
1427 for usr in User.get_all_super_admins():
1427 for usr in User.get_all_super_admins():
1428 super_admin_ids.append(usr.user_id)
1428 super_admin_ids.append(usr.user_id)
1429 # if this admin is also owner, don't double the record
1429 # if this admin is also owner, don't double the record
1430 if usr.user_id == owner_row[0].user_id:
1430 if usr.user_id == owner_row[0].user_id:
1431 owner_row[0].admin_row = True
1431 owner_row[0].admin_row = True
1432 else:
1432 else:
1433 usr = AttributeDict(usr.get_dict())
1433 usr = AttributeDict(usr.get_dict())
1434 usr.admin_row = True
1434 usr.admin_row = True
1435 usr.permission = _admin_perm
1435 usr.permission = _admin_perm
1436 super_admin_rows.append(usr)
1436 super_admin_rows.append(usr)
1437
1437
1438 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1438 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1439 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1439 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1440 joinedload(UserUserGroupToPerm.user),
1440 joinedload(UserUserGroupToPerm.user),
1441 joinedload(UserUserGroupToPerm.permission),)
1441 joinedload(UserUserGroupToPerm.permission),)
1442
1442
1443 # get owners and admins and permissions. We do a trick of re-writing
1443 # get owners and admins and permissions. We do a trick of re-writing
1444 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1444 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1445 # has a global reference and changing one object propagates to all
1445 # has a global reference and changing one object propagates to all
1446 # others. This means if admin is also an owner admin_row that change
1446 # others. This means if admin is also an owner admin_row that change
1447 # would propagate to both objects
1447 # would propagate to both objects
1448 perm_rows = []
1448 perm_rows = []
1449 for _usr in q.all():
1449 for _usr in q.all():
1450 usr = AttributeDict(_usr.user.get_dict())
1450 usr = AttributeDict(_usr.user.get_dict())
1451 # if this user is also owner/admin, mark as duplicate record
1451 # if this user is also owner/admin, mark as duplicate record
1452 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1452 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1453 usr.duplicate_perm = True
1453 usr.duplicate_perm = True
1454 usr.permission = _usr.permission.permission_name
1454 usr.permission = _usr.permission.permission_name
1455 perm_rows.append(usr)
1455 perm_rows.append(usr)
1456
1456
1457 # filter the perm rows by 'default' first and then sort them by
1457 # filter the perm rows by 'default' first and then sort them by
1458 # admin,write,read,none permissions sorted again alphabetically in
1458 # admin,write,read,none permissions sorted again alphabetically in
1459 # each group
1459 # each group
1460 perm_rows = sorted(perm_rows, key=display_user_sort)
1460 perm_rows = sorted(perm_rows, key=display_user_sort)
1461
1461
1462 user_groups_rows = []
1462 user_groups_rows = []
1463 if expand_from_user_groups:
1463 if expand_from_user_groups:
1464 for ug in self.permission_user_groups(with_members=True):
1464 for ug in self.permission_user_groups(with_members=True):
1465 for user_data in ug.members:
1465 for user_data in ug.members:
1466 user_groups_rows.append(user_data)
1466 user_groups_rows.append(user_data)
1467
1467
1468 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1468 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1469
1469
1470 def permission_user_groups(self, with_members=False):
1470 def permission_user_groups(self, with_members=False):
1471 q = UserGroupUserGroupToPerm.query()\
1471 q = UserGroupUserGroupToPerm.query()\
1472 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1472 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1473 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1473 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1474 joinedload(UserGroupUserGroupToPerm.target_user_group),
1474 joinedload(UserGroupUserGroupToPerm.target_user_group),
1475 joinedload(UserGroupUserGroupToPerm.permission),)
1475 joinedload(UserGroupUserGroupToPerm.permission),)
1476
1476
1477 perm_rows = []
1477 perm_rows = []
1478 for _user_group in q.all():
1478 for _user_group in q.all():
1479 entry = AttributeDict(_user_group.user_group.get_dict())
1479 entry = AttributeDict(_user_group.user_group.get_dict())
1480 entry.permission = _user_group.permission.permission_name
1480 entry.permission = _user_group.permission.permission_name
1481 if with_members:
1481 if with_members:
1482 entry.members = [x.user.get_dict()
1482 entry.members = [x.user.get_dict()
1483 for x in _user_group.user_group.members]
1483 for x in _user_group.user_group.members]
1484 perm_rows.append(entry)
1484 perm_rows.append(entry)
1485
1485
1486 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1486 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1487 return perm_rows
1487 return perm_rows
1488
1488
1489 def _get_default_perms(self, user_group, suffix=''):
1489 def _get_default_perms(self, user_group, suffix=''):
1490 from rhodecode.model.permission import PermissionModel
1490 from rhodecode.model.permission import PermissionModel
1491 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1491 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1492
1492
1493 def get_default_perms(self, suffix=''):
1493 def get_default_perms(self, suffix=''):
1494 return self._get_default_perms(self, suffix)
1494 return self._get_default_perms(self, suffix)
1495
1495
1496 def get_api_data(self, with_group_members=True, include_secrets=False):
1496 def get_api_data(self, with_group_members=True, include_secrets=False):
1497 """
1497 """
1498 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1498 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1499 basically forwarded.
1499 basically forwarded.
1500
1500
1501 """
1501 """
1502 user_group = self
1502 user_group = self
1503 data = {
1503 data = {
1504 'users_group_id': user_group.users_group_id,
1504 'users_group_id': user_group.users_group_id,
1505 'group_name': user_group.users_group_name,
1505 'group_name': user_group.users_group_name,
1506 'group_description': user_group.user_group_description,
1506 'group_description': user_group.user_group_description,
1507 'active': user_group.users_group_active,
1507 'active': user_group.users_group_active,
1508 'owner': user_group.user.username,
1508 'owner': user_group.user.username,
1509 'sync': user_group.sync,
1509 'sync': user_group.sync,
1510 'owner_email': user_group.user.email,
1510 'owner_email': user_group.user.email,
1511 }
1511 }
1512
1512
1513 if with_group_members:
1513 if with_group_members:
1514 users = []
1514 users = []
1515 for user in user_group.members:
1515 for user in user_group.members:
1516 user = user.user
1516 user = user.user
1517 users.append(user.get_api_data(include_secrets=include_secrets))
1517 users.append(user.get_api_data(include_secrets=include_secrets))
1518 data['users'] = users
1518 data['users'] = users
1519
1519
1520 return data
1520 return data
1521
1521
1522
1522
1523 class UserGroupMember(Base, BaseModel):
1523 class UserGroupMember(Base, BaseModel):
1524 __tablename__ = 'users_groups_members'
1524 __tablename__ = 'users_groups_members'
1525 __table_args__ = (
1525 __table_args__ = (
1526 base_table_args,
1526 base_table_args,
1527 )
1527 )
1528
1528
1529 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1529 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1530 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1530 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1531 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1531 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1532
1532
1533 user = relationship('User', lazy='joined')
1533 user = relationship('User', lazy='joined')
1534 users_group = relationship('UserGroup')
1534 users_group = relationship('UserGroup')
1535
1535
1536 def __init__(self, gr_id='', u_id=''):
1536 def __init__(self, gr_id='', u_id=''):
1537 self.users_group_id = gr_id
1537 self.users_group_id = gr_id
1538 self.user_id = u_id
1538 self.user_id = u_id
1539
1539
1540
1540
1541 class RepositoryField(Base, BaseModel):
1541 class RepositoryField(Base, BaseModel):
1542 __tablename__ = 'repositories_fields'
1542 __tablename__ = 'repositories_fields'
1543 __table_args__ = (
1543 __table_args__ = (
1544 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1544 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1545 base_table_args,
1545 base_table_args,
1546 )
1546 )
1547
1547
1548 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1548 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1549
1549
1550 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1550 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1551 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1551 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1552 field_key = Column("field_key", String(250))
1552 field_key = Column("field_key", String(250))
1553 field_label = Column("field_label", String(1024), nullable=False)
1553 field_label = Column("field_label", String(1024), nullable=False)
1554 field_value = Column("field_value", String(10000), nullable=False)
1554 field_value = Column("field_value", String(10000), nullable=False)
1555 field_desc = Column("field_desc", String(1024), nullable=False)
1555 field_desc = Column("field_desc", String(1024), nullable=False)
1556 field_type = Column("field_type", String(255), nullable=False, unique=None)
1556 field_type = Column("field_type", String(255), nullable=False, unique=None)
1557 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1557 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1558
1558
1559 repository = relationship('Repository')
1559 repository = relationship('Repository')
1560
1560
1561 @property
1561 @property
1562 def field_key_prefixed(self):
1562 def field_key_prefixed(self):
1563 return 'ex_%s' % self.field_key
1563 return 'ex_%s' % self.field_key
1564
1564
1565 @classmethod
1565 @classmethod
1566 def un_prefix_key(cls, key):
1566 def un_prefix_key(cls, key):
1567 if key.startswith(cls.PREFIX):
1567 if key.startswith(cls.PREFIX):
1568 return key[len(cls.PREFIX):]
1568 return key[len(cls.PREFIX):]
1569 return key
1569 return key
1570
1570
1571 @classmethod
1571 @classmethod
1572 def get_by_key_name(cls, key, repo):
1572 def get_by_key_name(cls, key, repo):
1573 row = cls.query()\
1573 row = cls.query()\
1574 .filter(cls.repository == repo)\
1574 .filter(cls.repository == repo)\
1575 .filter(cls.field_key == key).scalar()
1575 .filter(cls.field_key == key).scalar()
1576 return row
1576 return row
1577
1577
1578
1578
1579 class Repository(Base, BaseModel):
1579 class Repository(Base, BaseModel):
1580 __tablename__ = 'repositories'
1580 __tablename__ = 'repositories'
1581 __table_args__ = (
1581 __table_args__ = (
1582 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1582 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1583 base_table_args,
1583 base_table_args,
1584 )
1584 )
1585 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1585 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1586 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1586 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1587 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1587 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1588
1588
1589 STATE_CREATED = 'repo_state_created'
1589 STATE_CREATED = 'repo_state_created'
1590 STATE_PENDING = 'repo_state_pending'
1590 STATE_PENDING = 'repo_state_pending'
1591 STATE_ERROR = 'repo_state_error'
1591 STATE_ERROR = 'repo_state_error'
1592
1592
1593 LOCK_AUTOMATIC = 'lock_auto'
1593 LOCK_AUTOMATIC = 'lock_auto'
1594 LOCK_API = 'lock_api'
1594 LOCK_API = 'lock_api'
1595 LOCK_WEB = 'lock_web'
1595 LOCK_WEB = 'lock_web'
1596 LOCK_PULL = 'lock_pull'
1596 LOCK_PULL = 'lock_pull'
1597
1597
1598 NAME_SEP = URL_SEP
1598 NAME_SEP = URL_SEP
1599
1599
1600 repo_id = Column(
1600 repo_id = Column(
1601 "repo_id", Integer(), nullable=False, unique=True, default=None,
1601 "repo_id", Integer(), nullable=False, unique=True, default=None,
1602 primary_key=True)
1602 primary_key=True)
1603 _repo_name = Column(
1603 _repo_name = Column(
1604 "repo_name", Text(), nullable=False, default=None)
1604 "repo_name", Text(), nullable=False, default=None)
1605 _repo_name_hash = Column(
1605 _repo_name_hash = Column(
1606 "repo_name_hash", String(255), nullable=False, unique=True)
1606 "repo_name_hash", String(255), nullable=False, unique=True)
1607 repo_state = Column("repo_state", String(255), nullable=True)
1607 repo_state = Column("repo_state", String(255), nullable=True)
1608
1608
1609 clone_uri = Column(
1609 clone_uri = Column(
1610 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1610 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1611 default=None)
1611 default=None)
1612 push_uri = Column(
1612 push_uri = Column(
1613 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1613 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1614 default=None)
1614 default=None)
1615 repo_type = Column(
1615 repo_type = Column(
1616 "repo_type", String(255), nullable=False, unique=False, default=None)
1616 "repo_type", String(255), nullable=False, unique=False, default=None)
1617 user_id = Column(
1617 user_id = Column(
1618 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1618 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1619 unique=False, default=None)
1619 unique=False, default=None)
1620 private = Column(
1620 private = Column(
1621 "private", Boolean(), nullable=True, unique=None, default=None)
1621 "private", Boolean(), nullable=True, unique=None, default=None)
1622 archived = Column(
1622 archived = Column(
1623 "archived", Boolean(), nullable=True, unique=None, default=None)
1623 "archived", Boolean(), nullable=True, unique=None, default=None)
1624 enable_statistics = Column(
1624 enable_statistics = Column(
1625 "statistics", Boolean(), nullable=True, unique=None, default=True)
1625 "statistics", Boolean(), nullable=True, unique=None, default=True)
1626 enable_downloads = Column(
1626 enable_downloads = Column(
1627 "downloads", Boolean(), nullable=True, unique=None, default=True)
1627 "downloads", Boolean(), nullable=True, unique=None, default=True)
1628 description = Column(
1628 description = Column(
1629 "description", String(10000), nullable=True, unique=None, default=None)
1629 "description", String(10000), nullable=True, unique=None, default=None)
1630 created_on = Column(
1630 created_on = Column(
1631 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1631 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1632 default=datetime.datetime.now)
1632 default=datetime.datetime.now)
1633 updated_on = Column(
1633 updated_on = Column(
1634 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1634 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1635 default=datetime.datetime.now)
1635 default=datetime.datetime.now)
1636 _landing_revision = Column(
1636 _landing_revision = Column(
1637 "landing_revision", String(255), nullable=False, unique=False,
1637 "landing_revision", String(255), nullable=False, unique=False,
1638 default=None)
1638 default=None)
1639 enable_locking = Column(
1639 enable_locking = Column(
1640 "enable_locking", Boolean(), nullable=False, unique=None,
1640 "enable_locking", Boolean(), nullable=False, unique=None,
1641 default=False)
1641 default=False)
1642 _locked = Column(
1642 _locked = Column(
1643 "locked", String(255), nullable=True, unique=False, default=None)
1643 "locked", String(255), nullable=True, unique=False, default=None)
1644 _changeset_cache = Column(
1644 _changeset_cache = Column(
1645 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1645 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1646
1646
1647 fork_id = Column(
1647 fork_id = Column(
1648 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1648 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1649 nullable=True, unique=False, default=None)
1649 nullable=True, unique=False, default=None)
1650 group_id = Column(
1650 group_id = Column(
1651 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1651 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1652 unique=False, default=None)
1652 unique=False, default=None)
1653
1653
1654 user = relationship('User', lazy='joined')
1654 user = relationship('User', lazy='joined')
1655 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1655 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1656 group = relationship('RepoGroup', lazy='joined')
1656 group = relationship('RepoGroup', lazy='joined')
1657 repo_to_perm = relationship(
1657 repo_to_perm = relationship(
1658 'UserRepoToPerm', cascade='all',
1658 'UserRepoToPerm', cascade='all',
1659 order_by='UserRepoToPerm.repo_to_perm_id')
1659 order_by='UserRepoToPerm.repo_to_perm_id')
1660 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1660 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1661 stats = relationship('Statistics', cascade='all', uselist=False)
1661 stats = relationship('Statistics', cascade='all', uselist=False)
1662
1662
1663 followers = relationship(
1663 followers = relationship(
1664 'UserFollowing',
1664 'UserFollowing',
1665 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1665 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1666 cascade='all')
1666 cascade='all')
1667 extra_fields = relationship(
1667 extra_fields = relationship(
1668 'RepositoryField', cascade="all, delete, delete-orphan")
1668 'RepositoryField', cascade="all, delete, delete-orphan")
1669 logs = relationship('UserLog')
1669 logs = relationship('UserLog')
1670 comments = relationship(
1670 comments = relationship(
1671 'ChangesetComment', cascade="all, delete, delete-orphan")
1671 'ChangesetComment', cascade="all, delete, delete-orphan")
1672 pull_requests_source = relationship(
1672 pull_requests_source = relationship(
1673 'PullRequest',
1673 'PullRequest',
1674 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1674 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1675 cascade="all, delete, delete-orphan")
1675 cascade="all, delete, delete-orphan")
1676 pull_requests_target = relationship(
1676 pull_requests_target = relationship(
1677 'PullRequest',
1677 'PullRequest',
1678 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1678 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1679 cascade="all, delete, delete-orphan")
1679 cascade="all, delete, delete-orphan")
1680 ui = relationship('RepoRhodeCodeUi', cascade="all")
1680 ui = relationship('RepoRhodeCodeUi', cascade="all")
1681 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1681 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1682 integrations = relationship('Integration', cascade="all, delete, delete-orphan")
1682 integrations = relationship('Integration', cascade="all, delete, delete-orphan")
1683
1683
1684 scoped_tokens = relationship('UserApiKeys', cascade="all")
1684 scoped_tokens = relationship('UserApiKeys', cascade="all")
1685
1685
1686 artifacts = relationship('FileStore', cascade="all")
1686 artifacts = relationship('FileStore', cascade="all")
1687
1687
1688 def __unicode__(self):
1688 def __unicode__(self):
1689 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1689 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1690 safe_unicode(self.repo_name))
1690 safe_unicode(self.repo_name))
1691
1691
1692 @hybrid_property
1692 @hybrid_property
1693 def description_safe(self):
1693 def description_safe(self):
1694 from rhodecode.lib import helpers as h
1694 from rhodecode.lib import helpers as h
1695 return h.escape(self.description)
1695 return h.escape(self.description)
1696
1696
1697 @hybrid_property
1697 @hybrid_property
1698 def landing_rev(self):
1698 def landing_rev(self):
1699 # always should return [rev_type, rev]
1699 # always should return [rev_type, rev]
1700 if self._landing_revision:
1700 if self._landing_revision:
1701 _rev_info = self._landing_revision.split(':')
1701 _rev_info = self._landing_revision.split(':')
1702 if len(_rev_info) < 2:
1702 if len(_rev_info) < 2:
1703 _rev_info.insert(0, 'rev')
1703 _rev_info.insert(0, 'rev')
1704 return [_rev_info[0], _rev_info[1]]
1704 return [_rev_info[0], _rev_info[1]]
1705 return [None, None]
1705 return [None, None]
1706
1706
1707 @landing_rev.setter
1707 @landing_rev.setter
1708 def landing_rev(self, val):
1708 def landing_rev(self, val):
1709 if ':' not in val:
1709 if ':' not in val:
1710 raise ValueError('value must be delimited with `:` and consist '
1710 raise ValueError('value must be delimited with `:` and consist '
1711 'of <rev_type>:<rev>, got %s instead' % val)
1711 'of <rev_type>:<rev>, got %s instead' % val)
1712 self._landing_revision = val
1712 self._landing_revision = val
1713
1713
1714 @hybrid_property
1714 @hybrid_property
1715 def locked(self):
1715 def locked(self):
1716 if self._locked:
1716 if self._locked:
1717 user_id, timelocked, reason = self._locked.split(':')
1717 user_id, timelocked, reason = self._locked.split(':')
1718 lock_values = int(user_id), timelocked, reason
1718 lock_values = int(user_id), timelocked, reason
1719 else:
1719 else:
1720 lock_values = [None, None, None]
1720 lock_values = [None, None, None]
1721 return lock_values
1721 return lock_values
1722
1722
1723 @locked.setter
1723 @locked.setter
1724 def locked(self, val):
1724 def locked(self, val):
1725 if val and isinstance(val, (list, tuple)):
1725 if val and isinstance(val, (list, tuple)):
1726 self._locked = ':'.join(map(str, val))
1726 self._locked = ':'.join(map(str, val))
1727 else:
1727 else:
1728 self._locked = None
1728 self._locked = None
1729
1729
1730 @hybrid_property
1730 @hybrid_property
1731 def changeset_cache(self):
1731 def changeset_cache(self):
1732 from rhodecode.lib.vcs.backends.base import EmptyCommit
1732 from rhodecode.lib.vcs.backends.base import EmptyCommit
1733 dummy = EmptyCommit().__json__()
1733 dummy = EmptyCommit().__json__()
1734 if not self._changeset_cache:
1734 if not self._changeset_cache:
1735 dummy['source_repo_id'] = self.repo_id
1735 dummy['source_repo_id'] = self.repo_id
1736 return json.loads(json.dumps(dummy))
1736 return json.loads(json.dumps(dummy))
1737
1737
1738 try:
1738 try:
1739 return json.loads(self._changeset_cache)
1739 return json.loads(self._changeset_cache)
1740 except TypeError:
1740 except TypeError:
1741 return dummy
1741 return dummy
1742 except Exception:
1742 except Exception:
1743 log.error(traceback.format_exc())
1743 log.error(traceback.format_exc())
1744 return dummy
1744 return dummy
1745
1745
1746 @changeset_cache.setter
1746 @changeset_cache.setter
1747 def changeset_cache(self, val):
1747 def changeset_cache(self, val):
1748 try:
1748 try:
1749 self._changeset_cache = json.dumps(val)
1749 self._changeset_cache = json.dumps(val)
1750 except Exception:
1750 except Exception:
1751 log.error(traceback.format_exc())
1751 log.error(traceback.format_exc())
1752
1752
1753 @hybrid_property
1753 @hybrid_property
1754 def repo_name(self):
1754 def repo_name(self):
1755 return self._repo_name
1755 return self._repo_name
1756
1756
1757 @repo_name.setter
1757 @repo_name.setter
1758 def repo_name(self, value):
1758 def repo_name(self, value):
1759 self._repo_name = value
1759 self._repo_name = value
1760 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1760 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1761
1761
1762 @classmethod
1762 @classmethod
1763 def normalize_repo_name(cls, repo_name):
1763 def normalize_repo_name(cls, repo_name):
1764 """
1764 """
1765 Normalizes os specific repo_name to the format internally stored inside
1765 Normalizes os specific repo_name to the format internally stored inside
1766 database using URL_SEP
1766 database using URL_SEP
1767
1767
1768 :param cls:
1768 :param cls:
1769 :param repo_name:
1769 :param repo_name:
1770 """
1770 """
1771 return cls.NAME_SEP.join(repo_name.split(os.sep))
1771 return cls.NAME_SEP.join(repo_name.split(os.sep))
1772
1772
1773 @classmethod
1773 @classmethod
1774 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1774 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1775 session = Session()
1775 session = Session()
1776 q = session.query(cls).filter(cls.repo_name == repo_name)
1776 q = session.query(cls).filter(cls.repo_name == repo_name)
1777
1777
1778 if cache:
1778 if cache:
1779 if identity_cache:
1779 if identity_cache:
1780 val = cls.identity_cache(session, 'repo_name', repo_name)
1780 val = cls.identity_cache(session, 'repo_name', repo_name)
1781 if val:
1781 if val:
1782 return val
1782 return val
1783 else:
1783 else:
1784 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1784 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1785 q = q.options(
1785 q = q.options(
1786 FromCache("sql_cache_short", cache_key))
1786 FromCache("sql_cache_short", cache_key))
1787
1787
1788 return q.scalar()
1788 return q.scalar()
1789
1789
1790 @classmethod
1790 @classmethod
1791 def get_by_id_or_repo_name(cls, repoid):
1791 def get_by_id_or_repo_name(cls, repoid):
1792 if isinstance(repoid, (int, long)):
1792 if isinstance(repoid, (int, long)):
1793 try:
1793 try:
1794 repo = cls.get(repoid)
1794 repo = cls.get(repoid)
1795 except ValueError:
1795 except ValueError:
1796 repo = None
1796 repo = None
1797 else:
1797 else:
1798 repo = cls.get_by_repo_name(repoid)
1798 repo = cls.get_by_repo_name(repoid)
1799 return repo
1799 return repo
1800
1800
1801 @classmethod
1801 @classmethod
1802 def get_by_full_path(cls, repo_full_path):
1802 def get_by_full_path(cls, repo_full_path):
1803 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1803 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1804 repo_name = cls.normalize_repo_name(repo_name)
1804 repo_name = cls.normalize_repo_name(repo_name)
1805 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1805 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1806
1806
1807 @classmethod
1807 @classmethod
1808 def get_repo_forks(cls, repo_id):
1808 def get_repo_forks(cls, repo_id):
1809 return cls.query().filter(Repository.fork_id == repo_id)
1809 return cls.query().filter(Repository.fork_id == repo_id)
1810
1810
1811 @classmethod
1811 @classmethod
1812 def base_path(cls):
1812 def base_path(cls):
1813 """
1813 """
1814 Returns base path when all repos are stored
1814 Returns base path when all repos are stored
1815
1815
1816 :param cls:
1816 :param cls:
1817 """
1817 """
1818 q = Session().query(RhodeCodeUi)\
1818 q = Session().query(RhodeCodeUi)\
1819 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1819 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1820 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1820 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1821 return q.one().ui_value
1821 return q.one().ui_value
1822
1822
1823 @classmethod
1823 @classmethod
1824 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1824 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1825 case_insensitive=True, archived=False):
1825 case_insensitive=True, archived=False):
1826 q = Repository.query()
1826 q = Repository.query()
1827
1827
1828 if not archived:
1828 if not archived:
1829 q = q.filter(Repository.archived.isnot(true()))
1829 q = q.filter(Repository.archived.isnot(true()))
1830
1830
1831 if not isinstance(user_id, Optional):
1831 if not isinstance(user_id, Optional):
1832 q = q.filter(Repository.user_id == user_id)
1832 q = q.filter(Repository.user_id == user_id)
1833
1833
1834 if not isinstance(group_id, Optional):
1834 if not isinstance(group_id, Optional):
1835 q = q.filter(Repository.group_id == group_id)
1835 q = q.filter(Repository.group_id == group_id)
1836
1836
1837 if case_insensitive:
1837 if case_insensitive:
1838 q = q.order_by(func.lower(Repository.repo_name))
1838 q = q.order_by(func.lower(Repository.repo_name))
1839 else:
1839 else:
1840 q = q.order_by(Repository.repo_name)
1840 q = q.order_by(Repository.repo_name)
1841
1841
1842 return q.all()
1842 return q.all()
1843
1843
1844 @property
1844 @property
1845 def repo_uid(self):
1845 def repo_uid(self):
1846 return '_{}'.format(self.repo_id)
1846 return '_{}'.format(self.repo_id)
1847
1847
1848 @property
1848 @property
1849 def forks(self):
1849 def forks(self):
1850 """
1850 """
1851 Return forks of this repo
1851 Return forks of this repo
1852 """
1852 """
1853 return Repository.get_repo_forks(self.repo_id)
1853 return Repository.get_repo_forks(self.repo_id)
1854
1854
1855 @property
1855 @property
1856 def parent(self):
1856 def parent(self):
1857 """
1857 """
1858 Returns fork parent
1858 Returns fork parent
1859 """
1859 """
1860 return self.fork
1860 return self.fork
1861
1861
1862 @property
1862 @property
1863 def just_name(self):
1863 def just_name(self):
1864 return self.repo_name.split(self.NAME_SEP)[-1]
1864 return self.repo_name.split(self.NAME_SEP)[-1]
1865
1865
1866 @property
1866 @property
1867 def groups_with_parents(self):
1867 def groups_with_parents(self):
1868 groups = []
1868 groups = []
1869 if self.group is None:
1869 if self.group is None:
1870 return groups
1870 return groups
1871
1871
1872 cur_gr = self.group
1872 cur_gr = self.group
1873 groups.insert(0, cur_gr)
1873 groups.insert(0, cur_gr)
1874 while 1:
1874 while 1:
1875 gr = getattr(cur_gr, 'parent_group', None)
1875 gr = getattr(cur_gr, 'parent_group', None)
1876 cur_gr = cur_gr.parent_group
1876 cur_gr = cur_gr.parent_group
1877 if gr is None:
1877 if gr is None:
1878 break
1878 break
1879 groups.insert(0, gr)
1879 groups.insert(0, gr)
1880
1880
1881 return groups
1881 return groups
1882
1882
1883 @property
1883 @property
1884 def groups_and_repo(self):
1884 def groups_and_repo(self):
1885 return self.groups_with_parents, self
1885 return self.groups_with_parents, self
1886
1886
1887 @LazyProperty
1887 @LazyProperty
1888 def repo_path(self):
1888 def repo_path(self):
1889 """
1889 """
1890 Returns base full path for that repository means where it actually
1890 Returns base full path for that repository means where it actually
1891 exists on a filesystem
1891 exists on a filesystem
1892 """
1892 """
1893 q = Session().query(RhodeCodeUi).filter(
1893 q = Session().query(RhodeCodeUi).filter(
1894 RhodeCodeUi.ui_key == self.NAME_SEP)
1894 RhodeCodeUi.ui_key == self.NAME_SEP)
1895 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1895 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1896 return q.one().ui_value
1896 return q.one().ui_value
1897
1897
1898 @property
1898 @property
1899 def repo_full_path(self):
1899 def repo_full_path(self):
1900 p = [self.repo_path]
1900 p = [self.repo_path]
1901 # we need to split the name by / since this is how we store the
1901 # we need to split the name by / since this is how we store the
1902 # names in the database, but that eventually needs to be converted
1902 # names in the database, but that eventually needs to be converted
1903 # into a valid system path
1903 # into a valid system path
1904 p += self.repo_name.split(self.NAME_SEP)
1904 p += self.repo_name.split(self.NAME_SEP)
1905 return os.path.join(*map(safe_unicode, p))
1905 return os.path.join(*map(safe_unicode, p))
1906
1906
1907 @property
1907 @property
1908 def cache_keys(self):
1908 def cache_keys(self):
1909 """
1909 """
1910 Returns associated cache keys for that repo
1910 Returns associated cache keys for that repo
1911 """
1911 """
1912 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1912 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1913 repo_id=self.repo_id)
1913 repo_id=self.repo_id)
1914 return CacheKey.query()\
1914 return CacheKey.query()\
1915 .filter(CacheKey.cache_args == invalidation_namespace)\
1915 .filter(CacheKey.cache_args == invalidation_namespace)\
1916 .order_by(CacheKey.cache_key)\
1916 .order_by(CacheKey.cache_key)\
1917 .all()
1917 .all()
1918
1918
1919 @property
1919 @property
1920 def cached_diffs_relative_dir(self):
1920 def cached_diffs_relative_dir(self):
1921 """
1921 """
1922 Return a relative to the repository store path of cached diffs
1922 Return a relative to the repository store path of cached diffs
1923 used for safe display for users, who shouldn't know the absolute store
1923 used for safe display for users, who shouldn't know the absolute store
1924 path
1924 path
1925 """
1925 """
1926 return os.path.join(
1926 return os.path.join(
1927 os.path.dirname(self.repo_name),
1927 os.path.dirname(self.repo_name),
1928 self.cached_diffs_dir.split(os.path.sep)[-1])
1928 self.cached_diffs_dir.split(os.path.sep)[-1])
1929
1929
1930 @property
1930 @property
1931 def cached_diffs_dir(self):
1931 def cached_diffs_dir(self):
1932 path = self.repo_full_path
1932 path = self.repo_full_path
1933 return os.path.join(
1933 return os.path.join(
1934 os.path.dirname(path),
1934 os.path.dirname(path),
1935 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1935 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1936
1936
1937 def cached_diffs(self):
1937 def cached_diffs(self):
1938 diff_cache_dir = self.cached_diffs_dir
1938 diff_cache_dir = self.cached_diffs_dir
1939 if os.path.isdir(diff_cache_dir):
1939 if os.path.isdir(diff_cache_dir):
1940 return os.listdir(diff_cache_dir)
1940 return os.listdir(diff_cache_dir)
1941 return []
1941 return []
1942
1942
1943 def shadow_repos(self):
1943 def shadow_repos(self):
1944 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1944 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1945 return [
1945 return [
1946 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1946 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1947 if x.startswith(shadow_repos_pattern)]
1947 if x.startswith(shadow_repos_pattern)]
1948
1948
1949 def get_new_name(self, repo_name):
1949 def get_new_name(self, repo_name):
1950 """
1950 """
1951 returns new full repository name based on assigned group and new new
1951 returns new full repository name based on assigned group and new new
1952
1952
1953 :param group_name:
1953 :param group_name:
1954 """
1954 """
1955 path_prefix = self.group.full_path_splitted if self.group else []
1955 path_prefix = self.group.full_path_splitted if self.group else []
1956 return self.NAME_SEP.join(path_prefix + [repo_name])
1956 return self.NAME_SEP.join(path_prefix + [repo_name])
1957
1957
1958 @property
1958 @property
1959 def _config(self):
1959 def _config(self):
1960 """
1960 """
1961 Returns db based config object.
1961 Returns db based config object.
1962 """
1962 """
1963 from rhodecode.lib.utils import make_db_config
1963 from rhodecode.lib.utils import make_db_config
1964 return make_db_config(clear_session=False, repo=self)
1964 return make_db_config(clear_session=False, repo=self)
1965
1965
1966 def permissions(self, with_admins=True, with_owner=True,
1966 def permissions(self, with_admins=True, with_owner=True,
1967 expand_from_user_groups=False):
1967 expand_from_user_groups=False):
1968 """
1968 """
1969 Permissions for repositories
1969 Permissions for repositories
1970 """
1970 """
1971 _admin_perm = 'repository.admin'
1971 _admin_perm = 'repository.admin'
1972
1972
1973 owner_row = []
1973 owner_row = []
1974 if with_owner:
1974 if with_owner:
1975 usr = AttributeDict(self.user.get_dict())
1975 usr = AttributeDict(self.user.get_dict())
1976 usr.owner_row = True
1976 usr.owner_row = True
1977 usr.permission = _admin_perm
1977 usr.permission = _admin_perm
1978 usr.permission_id = None
1978 usr.permission_id = None
1979 owner_row.append(usr)
1979 owner_row.append(usr)
1980
1980
1981 super_admin_ids = []
1981 super_admin_ids = []
1982 super_admin_rows = []
1982 super_admin_rows = []
1983 if with_admins:
1983 if with_admins:
1984 for usr in User.get_all_super_admins():
1984 for usr in User.get_all_super_admins():
1985 super_admin_ids.append(usr.user_id)
1985 super_admin_ids.append(usr.user_id)
1986 # if this admin is also owner, don't double the record
1986 # if this admin is also owner, don't double the record
1987 if usr.user_id == owner_row[0].user_id:
1987 if usr.user_id == owner_row[0].user_id:
1988 owner_row[0].admin_row = True
1988 owner_row[0].admin_row = True
1989 else:
1989 else:
1990 usr = AttributeDict(usr.get_dict())
1990 usr = AttributeDict(usr.get_dict())
1991 usr.admin_row = True
1991 usr.admin_row = True
1992 usr.permission = _admin_perm
1992 usr.permission = _admin_perm
1993 usr.permission_id = None
1993 usr.permission_id = None
1994 super_admin_rows.append(usr)
1994 super_admin_rows.append(usr)
1995
1995
1996 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1996 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1997 q = q.options(joinedload(UserRepoToPerm.repository),
1997 q = q.options(joinedload(UserRepoToPerm.repository),
1998 joinedload(UserRepoToPerm.user),
1998 joinedload(UserRepoToPerm.user),
1999 joinedload(UserRepoToPerm.permission),)
1999 joinedload(UserRepoToPerm.permission),)
2000
2000
2001 # get owners and admins and permissions. We do a trick of re-writing
2001 # get owners and admins and permissions. We do a trick of re-writing
2002 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2002 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2003 # has a global reference and changing one object propagates to all
2003 # has a global reference and changing one object propagates to all
2004 # others. This means if admin is also an owner admin_row that change
2004 # others. This means if admin is also an owner admin_row that change
2005 # would propagate to both objects
2005 # would propagate to both objects
2006 perm_rows = []
2006 perm_rows = []
2007 for _usr in q.all():
2007 for _usr in q.all():
2008 usr = AttributeDict(_usr.user.get_dict())
2008 usr = AttributeDict(_usr.user.get_dict())
2009 # if this user is also owner/admin, mark as duplicate record
2009 # if this user is also owner/admin, mark as duplicate record
2010 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2010 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2011 usr.duplicate_perm = True
2011 usr.duplicate_perm = True
2012 # also check if this permission is maybe used by branch_permissions
2012 # also check if this permission is maybe used by branch_permissions
2013 if _usr.branch_perm_entry:
2013 if _usr.branch_perm_entry:
2014 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2014 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2015
2015
2016 usr.permission = _usr.permission.permission_name
2016 usr.permission = _usr.permission.permission_name
2017 usr.permission_id = _usr.repo_to_perm_id
2017 usr.permission_id = _usr.repo_to_perm_id
2018 perm_rows.append(usr)
2018 perm_rows.append(usr)
2019
2019
2020 # filter the perm rows by 'default' first and then sort them by
2020 # filter the perm rows by 'default' first and then sort them by
2021 # admin,write,read,none permissions sorted again alphabetically in
2021 # admin,write,read,none permissions sorted again alphabetically in
2022 # each group
2022 # each group
2023 perm_rows = sorted(perm_rows, key=display_user_sort)
2023 perm_rows = sorted(perm_rows, key=display_user_sort)
2024
2024
2025 user_groups_rows = []
2025 user_groups_rows = []
2026 if expand_from_user_groups:
2026 if expand_from_user_groups:
2027 for ug in self.permission_user_groups(with_members=True):
2027 for ug in self.permission_user_groups(with_members=True):
2028 for user_data in ug.members:
2028 for user_data in ug.members:
2029 user_groups_rows.append(user_data)
2029 user_groups_rows.append(user_data)
2030
2030
2031 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2031 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2032
2032
2033 def permission_user_groups(self, with_members=True):
2033 def permission_user_groups(self, with_members=True):
2034 q = UserGroupRepoToPerm.query()\
2034 q = UserGroupRepoToPerm.query()\
2035 .filter(UserGroupRepoToPerm.repository == self)
2035 .filter(UserGroupRepoToPerm.repository == self)
2036 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2036 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2037 joinedload(UserGroupRepoToPerm.users_group),
2037 joinedload(UserGroupRepoToPerm.users_group),
2038 joinedload(UserGroupRepoToPerm.permission),)
2038 joinedload(UserGroupRepoToPerm.permission),)
2039
2039
2040 perm_rows = []
2040 perm_rows = []
2041 for _user_group in q.all():
2041 for _user_group in q.all():
2042 entry = AttributeDict(_user_group.users_group.get_dict())
2042 entry = AttributeDict(_user_group.users_group.get_dict())
2043 entry.permission = _user_group.permission.permission_name
2043 entry.permission = _user_group.permission.permission_name
2044 if with_members:
2044 if with_members:
2045 entry.members = [x.user.get_dict()
2045 entry.members = [x.user.get_dict()
2046 for x in _user_group.users_group.members]
2046 for x in _user_group.users_group.members]
2047 perm_rows.append(entry)
2047 perm_rows.append(entry)
2048
2048
2049 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2049 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2050 return perm_rows
2050 return perm_rows
2051
2051
2052 def get_api_data(self, include_secrets=False):
2052 def get_api_data(self, include_secrets=False):
2053 """
2053 """
2054 Common function for generating repo api data
2054 Common function for generating repo api data
2055
2055
2056 :param include_secrets: See :meth:`User.get_api_data`.
2056 :param include_secrets: See :meth:`User.get_api_data`.
2057
2057
2058 """
2058 """
2059 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2059 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2060 # move this methods on models level.
2060 # move this methods on models level.
2061 from rhodecode.model.settings import SettingsModel
2061 from rhodecode.model.settings import SettingsModel
2062 from rhodecode.model.repo import RepoModel
2062 from rhodecode.model.repo import RepoModel
2063
2063
2064 repo = self
2064 repo = self
2065 _user_id, _time, _reason = self.locked
2065 _user_id, _time, _reason = self.locked
2066
2066
2067 data = {
2067 data = {
2068 'repo_id': repo.repo_id,
2068 'repo_id': repo.repo_id,
2069 'repo_name': repo.repo_name,
2069 'repo_name': repo.repo_name,
2070 'repo_type': repo.repo_type,
2070 'repo_type': repo.repo_type,
2071 'clone_uri': repo.clone_uri or '',
2071 'clone_uri': repo.clone_uri or '',
2072 'push_uri': repo.push_uri or '',
2072 'push_uri': repo.push_uri or '',
2073 'url': RepoModel().get_url(self),
2073 'url': RepoModel().get_url(self),
2074 'private': repo.private,
2074 'private': repo.private,
2075 'created_on': repo.created_on,
2075 'created_on': repo.created_on,
2076 'description': repo.description_safe,
2076 'description': repo.description_safe,
2077 'landing_rev': repo.landing_rev,
2077 'landing_rev': repo.landing_rev,
2078 'owner': repo.user.username,
2078 'owner': repo.user.username,
2079 'fork_of': repo.fork.repo_name if repo.fork else None,
2079 'fork_of': repo.fork.repo_name if repo.fork else None,
2080 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2080 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2081 'enable_statistics': repo.enable_statistics,
2081 'enable_statistics': repo.enable_statistics,
2082 'enable_locking': repo.enable_locking,
2082 'enable_locking': repo.enable_locking,
2083 'enable_downloads': repo.enable_downloads,
2083 'enable_downloads': repo.enable_downloads,
2084 'last_changeset': repo.changeset_cache,
2084 'last_changeset': repo.changeset_cache,
2085 'locked_by': User.get(_user_id).get_api_data(
2085 'locked_by': User.get(_user_id).get_api_data(
2086 include_secrets=include_secrets) if _user_id else None,
2086 include_secrets=include_secrets) if _user_id else None,
2087 'locked_date': time_to_datetime(_time) if _time else None,
2087 'locked_date': time_to_datetime(_time) if _time else None,
2088 'lock_reason': _reason if _reason else None,
2088 'lock_reason': _reason if _reason else None,
2089 }
2089 }
2090
2090
2091 # TODO: mikhail: should be per-repo settings here
2091 # TODO: mikhail: should be per-repo settings here
2092 rc_config = SettingsModel().get_all_settings()
2092 rc_config = SettingsModel().get_all_settings()
2093 repository_fields = str2bool(
2093 repository_fields = str2bool(
2094 rc_config.get('rhodecode_repository_fields'))
2094 rc_config.get('rhodecode_repository_fields'))
2095 if repository_fields:
2095 if repository_fields:
2096 for f in self.extra_fields:
2096 for f in self.extra_fields:
2097 data[f.field_key_prefixed] = f.field_value
2097 data[f.field_key_prefixed] = f.field_value
2098
2098
2099 return data
2099 return data
2100
2100
2101 @classmethod
2101 @classmethod
2102 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2102 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2103 if not lock_time:
2103 if not lock_time:
2104 lock_time = time.time()
2104 lock_time = time.time()
2105 if not lock_reason:
2105 if not lock_reason:
2106 lock_reason = cls.LOCK_AUTOMATIC
2106 lock_reason = cls.LOCK_AUTOMATIC
2107 repo.locked = [user_id, lock_time, lock_reason]
2107 repo.locked = [user_id, lock_time, lock_reason]
2108 Session().add(repo)
2108 Session().add(repo)
2109 Session().commit()
2109 Session().commit()
2110
2110
2111 @classmethod
2111 @classmethod
2112 def unlock(cls, repo):
2112 def unlock(cls, repo):
2113 repo.locked = None
2113 repo.locked = None
2114 Session().add(repo)
2114 Session().add(repo)
2115 Session().commit()
2115 Session().commit()
2116
2116
2117 @classmethod
2117 @classmethod
2118 def getlock(cls, repo):
2118 def getlock(cls, repo):
2119 return repo.locked
2119 return repo.locked
2120
2120
2121 def is_user_lock(self, user_id):
2121 def is_user_lock(self, user_id):
2122 if self.lock[0]:
2122 if self.lock[0]:
2123 lock_user_id = safe_int(self.lock[0])
2123 lock_user_id = safe_int(self.lock[0])
2124 user_id = safe_int(user_id)
2124 user_id = safe_int(user_id)
2125 # both are ints, and they are equal
2125 # both are ints, and they are equal
2126 return all([lock_user_id, user_id]) and lock_user_id == user_id
2126 return all([lock_user_id, user_id]) and lock_user_id == user_id
2127
2127
2128 return False
2128 return False
2129
2129
2130 def get_locking_state(self, action, user_id, only_when_enabled=True):
2130 def get_locking_state(self, action, user_id, only_when_enabled=True):
2131 """
2131 """
2132 Checks locking on this repository, if locking is enabled and lock is
2132 Checks locking on this repository, if locking is enabled and lock is
2133 present returns a tuple of make_lock, locked, locked_by.
2133 present returns a tuple of make_lock, locked, locked_by.
2134 make_lock can have 3 states None (do nothing) True, make lock
2134 make_lock can have 3 states None (do nothing) True, make lock
2135 False release lock, This value is later propagated to hooks, which
2135 False release lock, This value is later propagated to hooks, which
2136 do the locking. Think about this as signals passed to hooks what to do.
2136 do the locking. Think about this as signals passed to hooks what to do.
2137
2137
2138 """
2138 """
2139 # TODO: johbo: This is part of the business logic and should be moved
2139 # TODO: johbo: This is part of the business logic and should be moved
2140 # into the RepositoryModel.
2140 # into the RepositoryModel.
2141
2141
2142 if action not in ('push', 'pull'):
2142 if action not in ('push', 'pull'):
2143 raise ValueError("Invalid action value: %s" % repr(action))
2143 raise ValueError("Invalid action value: %s" % repr(action))
2144
2144
2145 # defines if locked error should be thrown to user
2145 # defines if locked error should be thrown to user
2146 currently_locked = False
2146 currently_locked = False
2147 # defines if new lock should be made, tri-state
2147 # defines if new lock should be made, tri-state
2148 make_lock = None
2148 make_lock = None
2149 repo = self
2149 repo = self
2150 user = User.get(user_id)
2150 user = User.get(user_id)
2151
2151
2152 lock_info = repo.locked
2152 lock_info = repo.locked
2153
2153
2154 if repo and (repo.enable_locking or not only_when_enabled):
2154 if repo and (repo.enable_locking or not only_when_enabled):
2155 if action == 'push':
2155 if action == 'push':
2156 # check if it's already locked !, if it is compare users
2156 # check if it's already locked !, if it is compare users
2157 locked_by_user_id = lock_info[0]
2157 locked_by_user_id = lock_info[0]
2158 if user.user_id == locked_by_user_id:
2158 if user.user_id == locked_by_user_id:
2159 log.debug(
2159 log.debug(
2160 'Got `push` action from user %s, now unlocking', user)
2160 'Got `push` action from user %s, now unlocking', user)
2161 # unlock if we have push from user who locked
2161 # unlock if we have push from user who locked
2162 make_lock = False
2162 make_lock = False
2163 else:
2163 else:
2164 # we're not the same user who locked, ban with
2164 # we're not the same user who locked, ban with
2165 # code defined in settings (default is 423 HTTP Locked) !
2165 # code defined in settings (default is 423 HTTP Locked) !
2166 log.debug('Repo %s is currently locked by %s', repo, user)
2166 log.debug('Repo %s is currently locked by %s', repo, user)
2167 currently_locked = True
2167 currently_locked = True
2168 elif action == 'pull':
2168 elif action == 'pull':
2169 # [0] user [1] date
2169 # [0] user [1] date
2170 if lock_info[0] and lock_info[1]:
2170 if lock_info[0] and lock_info[1]:
2171 log.debug('Repo %s is currently locked by %s', repo, user)
2171 log.debug('Repo %s is currently locked by %s', repo, user)
2172 currently_locked = True
2172 currently_locked = True
2173 else:
2173 else:
2174 log.debug('Setting lock on repo %s by %s', repo, user)
2174 log.debug('Setting lock on repo %s by %s', repo, user)
2175 make_lock = True
2175 make_lock = True
2176
2176
2177 else:
2177 else:
2178 log.debug('Repository %s do not have locking enabled', repo)
2178 log.debug('Repository %s do not have locking enabled', repo)
2179
2179
2180 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2180 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2181 make_lock, currently_locked, lock_info)
2181 make_lock, currently_locked, lock_info)
2182
2182
2183 from rhodecode.lib.auth import HasRepoPermissionAny
2183 from rhodecode.lib.auth import HasRepoPermissionAny
2184 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2184 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2185 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2185 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2186 # if we don't have at least write permission we cannot make a lock
2186 # if we don't have at least write permission we cannot make a lock
2187 log.debug('lock state reset back to FALSE due to lack '
2187 log.debug('lock state reset back to FALSE due to lack '
2188 'of at least read permission')
2188 'of at least read permission')
2189 make_lock = False
2189 make_lock = False
2190
2190
2191 return make_lock, currently_locked, lock_info
2191 return make_lock, currently_locked, lock_info
2192
2192
2193 @property
2193 @property
2194 def last_commit_cache_update_diff(self):
2194 def last_commit_cache_update_diff(self):
2195 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2195 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2196
2196
2197 @property
2197 @property
2198 def last_commit_change(self):
2198 def last_commit_change(self):
2199 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2199 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2200 empty_date = datetime.datetime.fromtimestamp(0)
2200 empty_date = datetime.datetime.fromtimestamp(0)
2201 date_latest = self.changeset_cache.get('date', empty_date)
2201 date_latest = self.changeset_cache.get('date', empty_date)
2202 try:
2202 try:
2203 return parse_datetime(date_latest)
2203 return parse_datetime(date_latest)
2204 except Exception:
2204 except Exception:
2205 return empty_date
2205 return empty_date
2206
2206
2207 @property
2207 @property
2208 def last_db_change(self):
2208 def last_db_change(self):
2209 return self.updated_on
2209 return self.updated_on
2210
2210
2211 @property
2211 @property
2212 def clone_uri_hidden(self):
2212 def clone_uri_hidden(self):
2213 clone_uri = self.clone_uri
2213 clone_uri = self.clone_uri
2214 if clone_uri:
2214 if clone_uri:
2215 import urlobject
2215 import urlobject
2216 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2216 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2217 if url_obj.password:
2217 if url_obj.password:
2218 clone_uri = url_obj.with_password('*****')
2218 clone_uri = url_obj.with_password('*****')
2219 return clone_uri
2219 return clone_uri
2220
2220
2221 @property
2221 @property
2222 def push_uri_hidden(self):
2222 def push_uri_hidden(self):
2223 push_uri = self.push_uri
2223 push_uri = self.push_uri
2224 if push_uri:
2224 if push_uri:
2225 import urlobject
2225 import urlobject
2226 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2226 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2227 if url_obj.password:
2227 if url_obj.password:
2228 push_uri = url_obj.with_password('*****')
2228 push_uri = url_obj.with_password('*****')
2229 return push_uri
2229 return push_uri
2230
2230
2231 def clone_url(self, **override):
2231 def clone_url(self, **override):
2232 from rhodecode.model.settings import SettingsModel
2232 from rhodecode.model.settings import SettingsModel
2233
2233
2234 uri_tmpl = None
2234 uri_tmpl = None
2235 if 'with_id' in override:
2235 if 'with_id' in override:
2236 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2236 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2237 del override['with_id']
2237 del override['with_id']
2238
2238
2239 if 'uri_tmpl' in override:
2239 if 'uri_tmpl' in override:
2240 uri_tmpl = override['uri_tmpl']
2240 uri_tmpl = override['uri_tmpl']
2241 del override['uri_tmpl']
2241 del override['uri_tmpl']
2242
2242
2243 ssh = False
2243 ssh = False
2244 if 'ssh' in override:
2244 if 'ssh' in override:
2245 ssh = True
2245 ssh = True
2246 del override['ssh']
2246 del override['ssh']
2247
2247
2248 # we didn't override our tmpl from **overrides
2248 # we didn't override our tmpl from **overrides
2249 if not uri_tmpl:
2249 if not uri_tmpl:
2250 rc_config = SettingsModel().get_all_settings(cache=True)
2250 rc_config = SettingsModel().get_all_settings(cache=True)
2251 if ssh:
2251 if ssh:
2252 uri_tmpl = rc_config.get(
2252 uri_tmpl = rc_config.get(
2253 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2253 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2254 else:
2254 else:
2255 uri_tmpl = rc_config.get(
2255 uri_tmpl = rc_config.get(
2256 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2256 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2257
2257
2258 request = get_current_request()
2258 request = get_current_request()
2259 return get_clone_url(request=request,
2259 return get_clone_url(request=request,
2260 uri_tmpl=uri_tmpl,
2260 uri_tmpl=uri_tmpl,
2261 repo_name=self.repo_name,
2261 repo_name=self.repo_name,
2262 repo_id=self.repo_id, **override)
2262 repo_id=self.repo_id, **override)
2263
2263
2264 def set_state(self, state):
2264 def set_state(self, state):
2265 self.repo_state = state
2265 self.repo_state = state
2266 Session().add(self)
2266 Session().add(self)
2267 #==========================================================================
2267 #==========================================================================
2268 # SCM PROPERTIES
2268 # SCM PROPERTIES
2269 #==========================================================================
2269 #==========================================================================
2270
2270
2271 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2271 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2272 return get_commit_safe(
2272 return get_commit_safe(
2273 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2273 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2274
2274
2275 def get_changeset(self, rev=None, pre_load=None):
2275 def get_changeset(self, rev=None, pre_load=None):
2276 warnings.warn("Use get_commit", DeprecationWarning)
2276 warnings.warn("Use get_commit", DeprecationWarning)
2277 commit_id = None
2277 commit_id = None
2278 commit_idx = None
2278 commit_idx = None
2279 if isinstance(rev, compat.string_types):
2279 if isinstance(rev, compat.string_types):
2280 commit_id = rev
2280 commit_id = rev
2281 else:
2281 else:
2282 commit_idx = rev
2282 commit_idx = rev
2283 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2283 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2284 pre_load=pre_load)
2284 pre_load=pre_load)
2285
2285
2286 def get_landing_commit(self):
2286 def get_landing_commit(self):
2287 """
2287 """
2288 Returns landing commit, or if that doesn't exist returns the tip
2288 Returns landing commit, or if that doesn't exist returns the tip
2289 """
2289 """
2290 _rev_type, _rev = self.landing_rev
2290 _rev_type, _rev = self.landing_rev
2291 commit = self.get_commit(_rev)
2291 commit = self.get_commit(_rev)
2292 if isinstance(commit, EmptyCommit):
2292 if isinstance(commit, EmptyCommit):
2293 return self.get_commit()
2293 return self.get_commit()
2294 return commit
2294 return commit
2295
2295
2296 def update_commit_cache(self, cs_cache=None, config=None):
2296 def update_commit_cache(self, cs_cache=None, config=None):
2297 """
2297 """
2298 Update cache of last changeset for repository, keys should be::
2298 Update cache of last changeset for repository, keys should be::
2299
2299
2300 source_repo_id
2300 source_repo_id
2301 short_id
2301 short_id
2302 raw_id
2302 raw_id
2303 revision
2303 revision
2304 parents
2304 parents
2305 message
2305 message
2306 date
2306 date
2307 author
2307 author
2308 updated_on
2308 updated_on
2309
2309
2310 """
2310 """
2311 from rhodecode.lib.vcs.backends.base import BaseChangeset
2311 from rhodecode.lib.vcs.backends.base import BaseChangeset
2312 if cs_cache is None:
2312 if cs_cache is None:
2313 # use no-cache version here
2313 # use no-cache version here
2314 scm_repo = self.scm_instance(cache=False, config=config)
2314 scm_repo = self.scm_instance(cache=False, config=config)
2315
2315
2316 empty = scm_repo is None or scm_repo.is_empty()
2316 empty = scm_repo is None or scm_repo.is_empty()
2317 if not empty:
2317 if not empty:
2318 cs_cache = scm_repo.get_commit(
2318 cs_cache = scm_repo.get_commit(
2319 pre_load=["author", "date", "message", "parents"])
2319 pre_load=["author", "date", "message", "parents"])
2320 else:
2320 else:
2321 cs_cache = EmptyCommit()
2321 cs_cache = EmptyCommit()
2322
2322
2323 if isinstance(cs_cache, BaseChangeset):
2323 if isinstance(cs_cache, BaseChangeset):
2324 cs_cache = cs_cache.__json__()
2324 cs_cache = cs_cache.__json__()
2325
2325
2326 def is_outdated(new_cs_cache):
2326 def is_outdated(new_cs_cache):
2327 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2327 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2328 new_cs_cache['revision'] != self.changeset_cache['revision']):
2328 new_cs_cache['revision'] != self.changeset_cache['revision']):
2329 return True
2329 return True
2330 return False
2330 return False
2331
2331
2332 # check if we have maybe already latest cached revision
2332 # check if we have maybe already latest cached revision
2333 if is_outdated(cs_cache) or not self.changeset_cache:
2333 if is_outdated(cs_cache) or not self.changeset_cache:
2334 _default = datetime.datetime.utcnow()
2334 _default = datetime.datetime.utcnow()
2335 last_change = cs_cache.get('date') or _default
2335 last_change = cs_cache.get('date') or _default
2336 # we check if last update is newer than the new value
2336 # we check if last update is newer than the new value
2337 # if yes, we use the current timestamp instead. Imagine you get
2337 # if yes, we use the current timestamp instead. Imagine you get
2338 # old commit pushed 1y ago, we'd set last update 1y to ago.
2338 # old commit pushed 1y ago, we'd set last update 1y to ago.
2339 last_change_timestamp = datetime_to_time(last_change)
2339 last_change_timestamp = datetime_to_time(last_change)
2340 current_timestamp = datetime_to_time(last_change)
2340 current_timestamp = datetime_to_time(last_change)
2341 if last_change_timestamp > current_timestamp:
2341 if last_change_timestamp > current_timestamp:
2342 cs_cache['date'] = _default
2342 cs_cache['date'] = _default
2343
2343
2344 cs_cache['updated_on'] = time.time()
2344 cs_cache['updated_on'] = time.time()
2345 self.changeset_cache = cs_cache
2345 self.changeset_cache = cs_cache
2346 Session().add(self)
2346 Session().add(self)
2347 Session().commit()
2347 Session().commit()
2348
2348
2349 log.debug('updated repo %s with new commit cache %s',
2349 log.debug('updated repo %s with new commit cache %s',
2350 self.repo_name, cs_cache)
2350 self.repo_name, cs_cache)
2351 else:
2351 else:
2352 cs_cache = self.changeset_cache
2352 cs_cache = self.changeset_cache
2353 cs_cache['updated_on'] = time.time()
2353 cs_cache['updated_on'] = time.time()
2354 self.changeset_cache = cs_cache
2354 self.changeset_cache = cs_cache
2355 Session().add(self)
2355 Session().add(self)
2356 Session().commit()
2356 Session().commit()
2357
2357
2358 log.debug('Skipping update_commit_cache for repo:`%s` '
2358 log.debug('Skipping update_commit_cache for repo:`%s` '
2359 'commit already with latest changes', self.repo_name)
2359 'commit already with latest changes', self.repo_name)
2360
2360
2361 @property
2361 @property
2362 def tip(self):
2362 def tip(self):
2363 return self.get_commit('tip')
2363 return self.get_commit('tip')
2364
2364
2365 @property
2365 @property
2366 def author(self):
2366 def author(self):
2367 return self.tip.author
2367 return self.tip.author
2368
2368
2369 @property
2369 @property
2370 def last_change(self):
2370 def last_change(self):
2371 return self.scm_instance().last_change
2371 return self.scm_instance().last_change
2372
2372
2373 def get_comments(self, revisions=None):
2373 def get_comments(self, revisions=None):
2374 """
2374 """
2375 Returns comments for this repository grouped by revisions
2375 Returns comments for this repository grouped by revisions
2376
2376
2377 :param revisions: filter query by revisions only
2377 :param revisions: filter query by revisions only
2378 """
2378 """
2379 cmts = ChangesetComment.query()\
2379 cmts = ChangesetComment.query()\
2380 .filter(ChangesetComment.repo == self)
2380 .filter(ChangesetComment.repo == self)
2381 if revisions:
2381 if revisions:
2382 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2382 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2383 grouped = collections.defaultdict(list)
2383 grouped = collections.defaultdict(list)
2384 for cmt in cmts.all():
2384 for cmt in cmts.all():
2385 grouped[cmt.revision].append(cmt)
2385 grouped[cmt.revision].append(cmt)
2386 return grouped
2386 return grouped
2387
2387
2388 def statuses(self, revisions=None):
2388 def statuses(self, revisions=None):
2389 """
2389 """
2390 Returns statuses for this repository
2390 Returns statuses for this repository
2391
2391
2392 :param revisions: list of revisions to get statuses for
2392 :param revisions: list of revisions to get statuses for
2393 """
2393 """
2394 statuses = ChangesetStatus.query()\
2394 statuses = ChangesetStatus.query()\
2395 .filter(ChangesetStatus.repo == self)\
2395 .filter(ChangesetStatus.repo == self)\
2396 .filter(ChangesetStatus.version == 0)
2396 .filter(ChangesetStatus.version == 0)
2397
2397
2398 if revisions:
2398 if revisions:
2399 # Try doing the filtering in chunks to avoid hitting limits
2399 # Try doing the filtering in chunks to avoid hitting limits
2400 size = 500
2400 size = 500
2401 status_results = []
2401 status_results = []
2402 for chunk in xrange(0, len(revisions), size):
2402 for chunk in xrange(0, len(revisions), size):
2403 status_results += statuses.filter(
2403 status_results += statuses.filter(
2404 ChangesetStatus.revision.in_(
2404 ChangesetStatus.revision.in_(
2405 revisions[chunk: chunk+size])
2405 revisions[chunk: chunk+size])
2406 ).all()
2406 ).all()
2407 else:
2407 else:
2408 status_results = statuses.all()
2408 status_results = statuses.all()
2409
2409
2410 grouped = {}
2410 grouped = {}
2411
2411
2412 # maybe we have open new pullrequest without a status?
2412 # maybe we have open new pullrequest without a status?
2413 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2413 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2414 status_lbl = ChangesetStatus.get_status_lbl(stat)
2414 status_lbl = ChangesetStatus.get_status_lbl(stat)
2415 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2415 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2416 for rev in pr.revisions:
2416 for rev in pr.revisions:
2417 pr_id = pr.pull_request_id
2417 pr_id = pr.pull_request_id
2418 pr_repo = pr.target_repo.repo_name
2418 pr_repo = pr.target_repo.repo_name
2419 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2419 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2420
2420
2421 for stat in status_results:
2421 for stat in status_results:
2422 pr_id = pr_repo = None
2422 pr_id = pr_repo = None
2423 if stat.pull_request:
2423 if stat.pull_request:
2424 pr_id = stat.pull_request.pull_request_id
2424 pr_id = stat.pull_request.pull_request_id
2425 pr_repo = stat.pull_request.target_repo.repo_name
2425 pr_repo = stat.pull_request.target_repo.repo_name
2426 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2426 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2427 pr_id, pr_repo]
2427 pr_id, pr_repo]
2428 return grouped
2428 return grouped
2429
2429
2430 # ==========================================================================
2430 # ==========================================================================
2431 # SCM CACHE INSTANCE
2431 # SCM CACHE INSTANCE
2432 # ==========================================================================
2432 # ==========================================================================
2433
2433
2434 def scm_instance(self, **kwargs):
2434 def scm_instance(self, **kwargs):
2435 import rhodecode
2435 import rhodecode
2436
2436
2437 # Passing a config will not hit the cache currently only used
2437 # Passing a config will not hit the cache currently only used
2438 # for repo2dbmapper
2438 # for repo2dbmapper
2439 config = kwargs.pop('config', None)
2439 config = kwargs.pop('config', None)
2440 cache = kwargs.pop('cache', None)
2440 cache = kwargs.pop('cache', None)
2441 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2441 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2442 if vcs_full_cache is not None:
2442 if vcs_full_cache is not None:
2443 # allows override global config
2443 # allows override global config
2444 full_cache = vcs_full_cache
2444 full_cache = vcs_full_cache
2445 else:
2445 else:
2446 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2446 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2447 # if cache is NOT defined use default global, else we have a full
2447 # if cache is NOT defined use default global, else we have a full
2448 # control over cache behaviour
2448 # control over cache behaviour
2449 if cache is None and full_cache and not config:
2449 if cache is None and full_cache and not config:
2450 log.debug('Initializing pure cached instance for %s', self.repo_path)
2450 log.debug('Initializing pure cached instance for %s', self.repo_path)
2451 return self._get_instance_cached()
2451 return self._get_instance_cached()
2452
2452
2453 # cache here is sent to the "vcs server"
2453 # cache here is sent to the "vcs server"
2454 return self._get_instance(cache=bool(cache), config=config)
2454 return self._get_instance(cache=bool(cache), config=config)
2455
2455
2456 def _get_instance_cached(self):
2456 def _get_instance_cached(self):
2457 from rhodecode.lib import rc_cache
2457 from rhodecode.lib import rc_cache
2458
2458
2459 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2459 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2460 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2460 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2461 repo_id=self.repo_id)
2461 repo_id=self.repo_id)
2462 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2462 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2463
2463
2464 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2464 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2465 def get_instance_cached(repo_id, context_id, _cache_state_uid):
2465 def get_instance_cached(repo_id, context_id, _cache_state_uid):
2466 return self._get_instance(repo_state_uid=_cache_state_uid)
2466 return self._get_instance(repo_state_uid=_cache_state_uid)
2467
2467
2468 # we must use thread scoped cache here,
2468 # we must use thread scoped cache here,
2469 # because each thread of gevent needs it's own not shared connection and cache
2469 # because each thread of gevent needs it's own not shared connection and cache
2470 # we also alter `args` so the cache key is individual for every green thread.
2470 # we also alter `args` so the cache key is individual for every green thread.
2471 inv_context_manager = rc_cache.InvalidationContext(
2471 inv_context_manager = rc_cache.InvalidationContext(
2472 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2472 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2473 thread_scoped=True)
2473 thread_scoped=True)
2474 with inv_context_manager as invalidation_context:
2474 with inv_context_manager as invalidation_context:
2475 cache_state_uid = invalidation_context.cache_data['cache_state_uid']
2475 cache_state_uid = invalidation_context.cache_data['cache_state_uid']
2476 args = (self.repo_id, inv_context_manager.cache_key, cache_state_uid)
2476 args = (self.repo_id, inv_context_manager.cache_key, cache_state_uid)
2477
2477
2478 # re-compute and store cache if we get invalidate signal
2478 # re-compute and store cache if we get invalidate signal
2479 if invalidation_context.should_invalidate():
2479 if invalidation_context.should_invalidate():
2480 instance = get_instance_cached.refresh(*args)
2480 instance = get_instance_cached.refresh(*args)
2481 else:
2481 else:
2482 instance = get_instance_cached(*args)
2482 instance = get_instance_cached(*args)
2483
2483
2484 log.debug('Repo instance fetched in %.3fs', inv_context_manager.compute_time)
2484 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2485 return instance
2485 return instance
2486
2486
2487 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2487 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2488 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2488 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2489 self.repo_type, self.repo_path, cache)
2489 self.repo_type, self.repo_path, cache)
2490 config = config or self._config
2490 config = config or self._config
2491 custom_wire = {
2491 custom_wire = {
2492 'cache': cache, # controls the vcs.remote cache
2492 'cache': cache, # controls the vcs.remote cache
2493 'repo_state_uid': repo_state_uid
2493 'repo_state_uid': repo_state_uid
2494 }
2494 }
2495 repo = get_vcs_instance(
2495 repo = get_vcs_instance(
2496 repo_path=safe_str(self.repo_full_path),
2496 repo_path=safe_str(self.repo_full_path),
2497 config=config,
2497 config=config,
2498 with_wire=custom_wire,
2498 with_wire=custom_wire,
2499 create=False,
2499 create=False,
2500 _vcs_alias=self.repo_type)
2500 _vcs_alias=self.repo_type)
2501 if repo is not None:
2501 if repo is not None:
2502 repo.count() # cache rebuild
2502 repo.count() # cache rebuild
2503 return repo
2503 return repo
2504
2504
2505 def __json__(self):
2505 def __json__(self):
2506 return {'landing_rev': self.landing_rev}
2506 return {'landing_rev': self.landing_rev}
2507
2507
2508 def get_dict(self):
2508 def get_dict(self):
2509
2509
2510 # Since we transformed `repo_name` to a hybrid property, we need to
2510 # Since we transformed `repo_name` to a hybrid property, we need to
2511 # keep compatibility with the code which uses `repo_name` field.
2511 # keep compatibility with the code which uses `repo_name` field.
2512
2512
2513 result = super(Repository, self).get_dict()
2513 result = super(Repository, self).get_dict()
2514 result['repo_name'] = result.pop('_repo_name', None)
2514 result['repo_name'] = result.pop('_repo_name', None)
2515 return result
2515 return result
2516
2516
2517
2517
2518 class RepoGroup(Base, BaseModel):
2518 class RepoGroup(Base, BaseModel):
2519 __tablename__ = 'groups'
2519 __tablename__ = 'groups'
2520 __table_args__ = (
2520 __table_args__ = (
2521 UniqueConstraint('group_name', 'group_parent_id'),
2521 UniqueConstraint('group_name', 'group_parent_id'),
2522 base_table_args,
2522 base_table_args,
2523 )
2523 )
2524 __mapper_args__ = {'order_by': 'group_name'}
2524 __mapper_args__ = {'order_by': 'group_name'}
2525
2525
2526 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2526 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2527
2527
2528 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2528 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2529 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2529 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2530 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2530 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2531 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2531 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2532 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2532 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2533 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2533 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2534 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2534 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2535 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2535 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2536 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2536 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2537 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2537 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2538 _changeset_cache = Column(
2538 _changeset_cache = Column(
2539 "changeset_cache", LargeBinary(), nullable=True) # JSON data
2539 "changeset_cache", LargeBinary(), nullable=True) # JSON data
2540
2540
2541 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2541 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2542 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2542 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2543 parent_group = relationship('RepoGroup', remote_side=group_id)
2543 parent_group = relationship('RepoGroup', remote_side=group_id)
2544 user = relationship('User')
2544 user = relationship('User')
2545 integrations = relationship('Integration', cascade="all, delete, delete-orphan")
2545 integrations = relationship('Integration', cascade="all, delete, delete-orphan")
2546
2546
2547 def __init__(self, group_name='', parent_group=None):
2547 def __init__(self, group_name='', parent_group=None):
2548 self.group_name = group_name
2548 self.group_name = group_name
2549 self.parent_group = parent_group
2549 self.parent_group = parent_group
2550
2550
2551 def __unicode__(self):
2551 def __unicode__(self):
2552 return u"<%s('id:%s:%s')>" % (
2552 return u"<%s('id:%s:%s')>" % (
2553 self.__class__.__name__, self.group_id, self.group_name)
2553 self.__class__.__name__, self.group_id, self.group_name)
2554
2554
2555 @hybrid_property
2555 @hybrid_property
2556 def group_name(self):
2556 def group_name(self):
2557 return self._group_name
2557 return self._group_name
2558
2558
2559 @group_name.setter
2559 @group_name.setter
2560 def group_name(self, value):
2560 def group_name(self, value):
2561 self._group_name = value
2561 self._group_name = value
2562 self.group_name_hash = self.hash_repo_group_name(value)
2562 self.group_name_hash = self.hash_repo_group_name(value)
2563
2563
2564 @hybrid_property
2564 @hybrid_property
2565 def changeset_cache(self):
2565 def changeset_cache(self):
2566 from rhodecode.lib.vcs.backends.base import EmptyCommit
2566 from rhodecode.lib.vcs.backends.base import EmptyCommit
2567 dummy = EmptyCommit().__json__()
2567 dummy = EmptyCommit().__json__()
2568 if not self._changeset_cache:
2568 if not self._changeset_cache:
2569 dummy['source_repo_id'] = ''
2569 dummy['source_repo_id'] = ''
2570 return json.loads(json.dumps(dummy))
2570 return json.loads(json.dumps(dummy))
2571
2571
2572 try:
2572 try:
2573 return json.loads(self._changeset_cache)
2573 return json.loads(self._changeset_cache)
2574 except TypeError:
2574 except TypeError:
2575 return dummy
2575 return dummy
2576 except Exception:
2576 except Exception:
2577 log.error(traceback.format_exc())
2577 log.error(traceback.format_exc())
2578 return dummy
2578 return dummy
2579
2579
2580 @changeset_cache.setter
2580 @changeset_cache.setter
2581 def changeset_cache(self, val):
2581 def changeset_cache(self, val):
2582 try:
2582 try:
2583 self._changeset_cache = json.dumps(val)
2583 self._changeset_cache = json.dumps(val)
2584 except Exception:
2584 except Exception:
2585 log.error(traceback.format_exc())
2585 log.error(traceback.format_exc())
2586
2586
2587 @validates('group_parent_id')
2587 @validates('group_parent_id')
2588 def validate_group_parent_id(self, key, val):
2588 def validate_group_parent_id(self, key, val):
2589 """
2589 """
2590 Check cycle references for a parent group to self
2590 Check cycle references for a parent group to self
2591 """
2591 """
2592 if self.group_id and val:
2592 if self.group_id and val:
2593 assert val != self.group_id
2593 assert val != self.group_id
2594
2594
2595 return val
2595 return val
2596
2596
2597 @hybrid_property
2597 @hybrid_property
2598 def description_safe(self):
2598 def description_safe(self):
2599 from rhodecode.lib import helpers as h
2599 from rhodecode.lib import helpers as h
2600 return h.escape(self.group_description)
2600 return h.escape(self.group_description)
2601
2601
2602 @classmethod
2602 @classmethod
2603 def hash_repo_group_name(cls, repo_group_name):
2603 def hash_repo_group_name(cls, repo_group_name):
2604 val = remove_formatting(repo_group_name)
2604 val = remove_formatting(repo_group_name)
2605 val = safe_str(val).lower()
2605 val = safe_str(val).lower()
2606 chars = []
2606 chars = []
2607 for c in val:
2607 for c in val:
2608 if c not in string.ascii_letters:
2608 if c not in string.ascii_letters:
2609 c = str(ord(c))
2609 c = str(ord(c))
2610 chars.append(c)
2610 chars.append(c)
2611
2611
2612 return ''.join(chars)
2612 return ''.join(chars)
2613
2613
2614 @classmethod
2614 @classmethod
2615 def _generate_choice(cls, repo_group):
2615 def _generate_choice(cls, repo_group):
2616 from webhelpers.html import literal as _literal
2616 from webhelpers.html import literal as _literal
2617 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2617 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2618 return repo_group.group_id, _name(repo_group.full_path_splitted)
2618 return repo_group.group_id, _name(repo_group.full_path_splitted)
2619
2619
2620 @classmethod
2620 @classmethod
2621 def groups_choices(cls, groups=None, show_empty_group=True):
2621 def groups_choices(cls, groups=None, show_empty_group=True):
2622 if not groups:
2622 if not groups:
2623 groups = cls.query().all()
2623 groups = cls.query().all()
2624
2624
2625 repo_groups = []
2625 repo_groups = []
2626 if show_empty_group:
2626 if show_empty_group:
2627 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2627 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2628
2628
2629 repo_groups.extend([cls._generate_choice(x) for x in groups])
2629 repo_groups.extend([cls._generate_choice(x) for x in groups])
2630
2630
2631 repo_groups = sorted(
2631 repo_groups = sorted(
2632 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2632 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2633 return repo_groups
2633 return repo_groups
2634
2634
2635 @classmethod
2635 @classmethod
2636 def url_sep(cls):
2636 def url_sep(cls):
2637 return URL_SEP
2637 return URL_SEP
2638
2638
2639 @classmethod
2639 @classmethod
2640 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2640 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2641 if case_insensitive:
2641 if case_insensitive:
2642 gr = cls.query().filter(func.lower(cls.group_name)
2642 gr = cls.query().filter(func.lower(cls.group_name)
2643 == func.lower(group_name))
2643 == func.lower(group_name))
2644 else:
2644 else:
2645 gr = cls.query().filter(cls.group_name == group_name)
2645 gr = cls.query().filter(cls.group_name == group_name)
2646 if cache:
2646 if cache:
2647 name_key = _hash_key(group_name)
2647 name_key = _hash_key(group_name)
2648 gr = gr.options(
2648 gr = gr.options(
2649 FromCache("sql_cache_short", "get_group_%s" % name_key))
2649 FromCache("sql_cache_short", "get_group_%s" % name_key))
2650 return gr.scalar()
2650 return gr.scalar()
2651
2651
2652 @classmethod
2652 @classmethod
2653 def get_user_personal_repo_group(cls, user_id):
2653 def get_user_personal_repo_group(cls, user_id):
2654 user = User.get(user_id)
2654 user = User.get(user_id)
2655 if user.username == User.DEFAULT_USER:
2655 if user.username == User.DEFAULT_USER:
2656 return None
2656 return None
2657
2657
2658 return cls.query()\
2658 return cls.query()\
2659 .filter(cls.personal == true()) \
2659 .filter(cls.personal == true()) \
2660 .filter(cls.user == user) \
2660 .filter(cls.user == user) \
2661 .order_by(cls.group_id.asc()) \
2661 .order_by(cls.group_id.asc()) \
2662 .first()
2662 .first()
2663
2663
2664 @classmethod
2664 @classmethod
2665 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2665 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2666 case_insensitive=True):
2666 case_insensitive=True):
2667 q = RepoGroup.query()
2667 q = RepoGroup.query()
2668
2668
2669 if not isinstance(user_id, Optional):
2669 if not isinstance(user_id, Optional):
2670 q = q.filter(RepoGroup.user_id == user_id)
2670 q = q.filter(RepoGroup.user_id == user_id)
2671
2671
2672 if not isinstance(group_id, Optional):
2672 if not isinstance(group_id, Optional):
2673 q = q.filter(RepoGroup.group_parent_id == group_id)
2673 q = q.filter(RepoGroup.group_parent_id == group_id)
2674
2674
2675 if case_insensitive:
2675 if case_insensitive:
2676 q = q.order_by(func.lower(RepoGroup.group_name))
2676 q = q.order_by(func.lower(RepoGroup.group_name))
2677 else:
2677 else:
2678 q = q.order_by(RepoGroup.group_name)
2678 q = q.order_by(RepoGroup.group_name)
2679 return q.all()
2679 return q.all()
2680
2680
2681 @property
2681 @property
2682 def parents(self, parents_recursion_limit = 10):
2682 def parents(self, parents_recursion_limit = 10):
2683 groups = []
2683 groups = []
2684 if self.parent_group is None:
2684 if self.parent_group is None:
2685 return groups
2685 return groups
2686 cur_gr = self.parent_group
2686 cur_gr = self.parent_group
2687 groups.insert(0, cur_gr)
2687 groups.insert(0, cur_gr)
2688 cnt = 0
2688 cnt = 0
2689 while 1:
2689 while 1:
2690 cnt += 1
2690 cnt += 1
2691 gr = getattr(cur_gr, 'parent_group', None)
2691 gr = getattr(cur_gr, 'parent_group', None)
2692 cur_gr = cur_gr.parent_group
2692 cur_gr = cur_gr.parent_group
2693 if gr is None:
2693 if gr is None:
2694 break
2694 break
2695 if cnt == parents_recursion_limit:
2695 if cnt == parents_recursion_limit:
2696 # this will prevent accidental infinit loops
2696 # this will prevent accidental infinit loops
2697 log.error('more than %s parents found for group %s, stopping '
2697 log.error('more than %s parents found for group %s, stopping '
2698 'recursive parent fetching', parents_recursion_limit, self)
2698 'recursive parent fetching', parents_recursion_limit, self)
2699 break
2699 break
2700
2700
2701 groups.insert(0, gr)
2701 groups.insert(0, gr)
2702 return groups
2702 return groups
2703
2703
2704 @property
2704 @property
2705 def last_commit_cache_update_diff(self):
2705 def last_commit_cache_update_diff(self):
2706 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2706 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2707
2707
2708 @property
2708 @property
2709 def last_commit_change(self):
2709 def last_commit_change(self):
2710 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2710 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2711 empty_date = datetime.datetime.fromtimestamp(0)
2711 empty_date = datetime.datetime.fromtimestamp(0)
2712 date_latest = self.changeset_cache.get('date', empty_date)
2712 date_latest = self.changeset_cache.get('date', empty_date)
2713 try:
2713 try:
2714 return parse_datetime(date_latest)
2714 return parse_datetime(date_latest)
2715 except Exception:
2715 except Exception:
2716 return empty_date
2716 return empty_date
2717
2717
2718 @property
2718 @property
2719 def last_db_change(self):
2719 def last_db_change(self):
2720 return self.updated_on
2720 return self.updated_on
2721
2721
2722 @property
2722 @property
2723 def children(self):
2723 def children(self):
2724 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2724 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2725
2725
2726 @property
2726 @property
2727 def name(self):
2727 def name(self):
2728 return self.group_name.split(RepoGroup.url_sep())[-1]
2728 return self.group_name.split(RepoGroup.url_sep())[-1]
2729
2729
2730 @property
2730 @property
2731 def full_path(self):
2731 def full_path(self):
2732 return self.group_name
2732 return self.group_name
2733
2733
2734 @property
2734 @property
2735 def full_path_splitted(self):
2735 def full_path_splitted(self):
2736 return self.group_name.split(RepoGroup.url_sep())
2736 return self.group_name.split(RepoGroup.url_sep())
2737
2737
2738 @property
2738 @property
2739 def repositories(self):
2739 def repositories(self):
2740 return Repository.query()\
2740 return Repository.query()\
2741 .filter(Repository.group == self)\
2741 .filter(Repository.group == self)\
2742 .order_by(Repository.repo_name)
2742 .order_by(Repository.repo_name)
2743
2743
2744 @property
2744 @property
2745 def repositories_recursive_count(self):
2745 def repositories_recursive_count(self):
2746 cnt = self.repositories.count()
2746 cnt = self.repositories.count()
2747
2747
2748 def children_count(group):
2748 def children_count(group):
2749 cnt = 0
2749 cnt = 0
2750 for child in group.children:
2750 for child in group.children:
2751 cnt += child.repositories.count()
2751 cnt += child.repositories.count()
2752 cnt += children_count(child)
2752 cnt += children_count(child)
2753 return cnt
2753 return cnt
2754
2754
2755 return cnt + children_count(self)
2755 return cnt + children_count(self)
2756
2756
2757 def _recursive_objects(self, include_repos=True, include_groups=True):
2757 def _recursive_objects(self, include_repos=True, include_groups=True):
2758 all_ = []
2758 all_ = []
2759
2759
2760 def _get_members(root_gr):
2760 def _get_members(root_gr):
2761 if include_repos:
2761 if include_repos:
2762 for r in root_gr.repositories:
2762 for r in root_gr.repositories:
2763 all_.append(r)
2763 all_.append(r)
2764 childs = root_gr.children.all()
2764 childs = root_gr.children.all()
2765 if childs:
2765 if childs:
2766 for gr in childs:
2766 for gr in childs:
2767 if include_groups:
2767 if include_groups:
2768 all_.append(gr)
2768 all_.append(gr)
2769 _get_members(gr)
2769 _get_members(gr)
2770
2770
2771 root_group = []
2771 root_group = []
2772 if include_groups:
2772 if include_groups:
2773 root_group = [self]
2773 root_group = [self]
2774
2774
2775 _get_members(self)
2775 _get_members(self)
2776 return root_group + all_
2776 return root_group + all_
2777
2777
2778 def recursive_groups_and_repos(self):
2778 def recursive_groups_and_repos(self):
2779 """
2779 """
2780 Recursive return all groups, with repositories in those groups
2780 Recursive return all groups, with repositories in those groups
2781 """
2781 """
2782 return self._recursive_objects()
2782 return self._recursive_objects()
2783
2783
2784 def recursive_groups(self):
2784 def recursive_groups(self):
2785 """
2785 """
2786 Returns all children groups for this group including children of children
2786 Returns all children groups for this group including children of children
2787 """
2787 """
2788 return self._recursive_objects(include_repos=False)
2788 return self._recursive_objects(include_repos=False)
2789
2789
2790 def recursive_repos(self):
2790 def recursive_repos(self):
2791 """
2791 """
2792 Returns all children repositories for this group
2792 Returns all children repositories for this group
2793 """
2793 """
2794 return self._recursive_objects(include_groups=False)
2794 return self._recursive_objects(include_groups=False)
2795
2795
2796 def get_new_name(self, group_name):
2796 def get_new_name(self, group_name):
2797 """
2797 """
2798 returns new full group name based on parent and new name
2798 returns new full group name based on parent and new name
2799
2799
2800 :param group_name:
2800 :param group_name:
2801 """
2801 """
2802 path_prefix = (self.parent_group.full_path_splitted if
2802 path_prefix = (self.parent_group.full_path_splitted if
2803 self.parent_group else [])
2803 self.parent_group else [])
2804 return RepoGroup.url_sep().join(path_prefix + [group_name])
2804 return RepoGroup.url_sep().join(path_prefix + [group_name])
2805
2805
2806 def update_commit_cache(self, config=None):
2806 def update_commit_cache(self, config=None):
2807 """
2807 """
2808 Update cache of last changeset for newest repository inside this group, keys should be::
2808 Update cache of last changeset for newest repository inside this group, keys should be::
2809
2809
2810 source_repo_id
2810 source_repo_id
2811 short_id
2811 short_id
2812 raw_id
2812 raw_id
2813 revision
2813 revision
2814 parents
2814 parents
2815 message
2815 message
2816 date
2816 date
2817 author
2817 author
2818
2818
2819 """
2819 """
2820 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2820 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2821
2821
2822 def repo_groups_and_repos():
2822 def repo_groups_and_repos():
2823 all_entries = OrderedDefaultDict(list)
2823 all_entries = OrderedDefaultDict(list)
2824
2824
2825 def _get_members(root_gr, pos=0):
2825 def _get_members(root_gr, pos=0):
2826
2826
2827 for repo in root_gr.repositories:
2827 for repo in root_gr.repositories:
2828 all_entries[root_gr].append(repo)
2828 all_entries[root_gr].append(repo)
2829
2829
2830 # fill in all parent positions
2830 # fill in all parent positions
2831 for parent_group in root_gr.parents:
2831 for parent_group in root_gr.parents:
2832 all_entries[parent_group].extend(all_entries[root_gr])
2832 all_entries[parent_group].extend(all_entries[root_gr])
2833
2833
2834 children_groups = root_gr.children.all()
2834 children_groups = root_gr.children.all()
2835 if children_groups:
2835 if children_groups:
2836 for cnt, gr in enumerate(children_groups, 1):
2836 for cnt, gr in enumerate(children_groups, 1):
2837 _get_members(gr, pos=pos+cnt)
2837 _get_members(gr, pos=pos+cnt)
2838
2838
2839 _get_members(root_gr=self)
2839 _get_members(root_gr=self)
2840 return all_entries
2840 return all_entries
2841
2841
2842 empty_date = datetime.datetime.fromtimestamp(0)
2842 empty_date = datetime.datetime.fromtimestamp(0)
2843 for repo_group, repos in repo_groups_and_repos().items():
2843 for repo_group, repos in repo_groups_and_repos().items():
2844
2844
2845 latest_repo_cs_cache = {}
2845 latest_repo_cs_cache = {}
2846 for repo in repos:
2846 for repo in repos:
2847 repo_cs_cache = repo.changeset_cache
2847 repo_cs_cache = repo.changeset_cache
2848 date_latest = latest_repo_cs_cache.get('date', empty_date)
2848 date_latest = latest_repo_cs_cache.get('date', empty_date)
2849 date_current = repo_cs_cache.get('date', empty_date)
2849 date_current = repo_cs_cache.get('date', empty_date)
2850 current_timestamp = datetime_to_time(parse_datetime(date_latest))
2850 current_timestamp = datetime_to_time(parse_datetime(date_latest))
2851 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
2851 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
2852 latest_repo_cs_cache = repo_cs_cache
2852 latest_repo_cs_cache = repo_cs_cache
2853 latest_repo_cs_cache['source_repo_id'] = repo.repo_id
2853 latest_repo_cs_cache['source_repo_id'] = repo.repo_id
2854
2854
2855 latest_repo_cs_cache['updated_on'] = time.time()
2855 latest_repo_cs_cache['updated_on'] = time.time()
2856 repo_group.changeset_cache = latest_repo_cs_cache
2856 repo_group.changeset_cache = latest_repo_cs_cache
2857 Session().add(repo_group)
2857 Session().add(repo_group)
2858 Session().commit()
2858 Session().commit()
2859
2859
2860 log.debug('updated repo group %s with new commit cache %s',
2860 log.debug('updated repo group %s with new commit cache %s',
2861 repo_group.group_name, latest_repo_cs_cache)
2861 repo_group.group_name, latest_repo_cs_cache)
2862
2862
2863 def permissions(self, with_admins=True, with_owner=True,
2863 def permissions(self, with_admins=True, with_owner=True,
2864 expand_from_user_groups=False):
2864 expand_from_user_groups=False):
2865 """
2865 """
2866 Permissions for repository groups
2866 Permissions for repository groups
2867 """
2867 """
2868 _admin_perm = 'group.admin'
2868 _admin_perm = 'group.admin'
2869
2869
2870 owner_row = []
2870 owner_row = []
2871 if with_owner:
2871 if with_owner:
2872 usr = AttributeDict(self.user.get_dict())
2872 usr = AttributeDict(self.user.get_dict())
2873 usr.owner_row = True
2873 usr.owner_row = True
2874 usr.permission = _admin_perm
2874 usr.permission = _admin_perm
2875 owner_row.append(usr)
2875 owner_row.append(usr)
2876
2876
2877 super_admin_ids = []
2877 super_admin_ids = []
2878 super_admin_rows = []
2878 super_admin_rows = []
2879 if with_admins:
2879 if with_admins:
2880 for usr in User.get_all_super_admins():
2880 for usr in User.get_all_super_admins():
2881 super_admin_ids.append(usr.user_id)
2881 super_admin_ids.append(usr.user_id)
2882 # if this admin is also owner, don't double the record
2882 # if this admin is also owner, don't double the record
2883 if usr.user_id == owner_row[0].user_id:
2883 if usr.user_id == owner_row[0].user_id:
2884 owner_row[0].admin_row = True
2884 owner_row[0].admin_row = True
2885 else:
2885 else:
2886 usr = AttributeDict(usr.get_dict())
2886 usr = AttributeDict(usr.get_dict())
2887 usr.admin_row = True
2887 usr.admin_row = True
2888 usr.permission = _admin_perm
2888 usr.permission = _admin_perm
2889 super_admin_rows.append(usr)
2889 super_admin_rows.append(usr)
2890
2890
2891 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2891 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2892 q = q.options(joinedload(UserRepoGroupToPerm.group),
2892 q = q.options(joinedload(UserRepoGroupToPerm.group),
2893 joinedload(UserRepoGroupToPerm.user),
2893 joinedload(UserRepoGroupToPerm.user),
2894 joinedload(UserRepoGroupToPerm.permission),)
2894 joinedload(UserRepoGroupToPerm.permission),)
2895
2895
2896 # get owners and admins and permissions. We do a trick of re-writing
2896 # get owners and admins and permissions. We do a trick of re-writing
2897 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2897 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2898 # has a global reference and changing one object propagates to all
2898 # has a global reference and changing one object propagates to all
2899 # others. This means if admin is also an owner admin_row that change
2899 # others. This means if admin is also an owner admin_row that change
2900 # would propagate to both objects
2900 # would propagate to both objects
2901 perm_rows = []
2901 perm_rows = []
2902 for _usr in q.all():
2902 for _usr in q.all():
2903 usr = AttributeDict(_usr.user.get_dict())
2903 usr = AttributeDict(_usr.user.get_dict())
2904 # if this user is also owner/admin, mark as duplicate record
2904 # if this user is also owner/admin, mark as duplicate record
2905 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2905 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2906 usr.duplicate_perm = True
2906 usr.duplicate_perm = True
2907 usr.permission = _usr.permission.permission_name
2907 usr.permission = _usr.permission.permission_name
2908 perm_rows.append(usr)
2908 perm_rows.append(usr)
2909
2909
2910 # filter the perm rows by 'default' first and then sort them by
2910 # filter the perm rows by 'default' first and then sort them by
2911 # admin,write,read,none permissions sorted again alphabetically in
2911 # admin,write,read,none permissions sorted again alphabetically in
2912 # each group
2912 # each group
2913 perm_rows = sorted(perm_rows, key=display_user_sort)
2913 perm_rows = sorted(perm_rows, key=display_user_sort)
2914
2914
2915 user_groups_rows = []
2915 user_groups_rows = []
2916 if expand_from_user_groups:
2916 if expand_from_user_groups:
2917 for ug in self.permission_user_groups(with_members=True):
2917 for ug in self.permission_user_groups(with_members=True):
2918 for user_data in ug.members:
2918 for user_data in ug.members:
2919 user_groups_rows.append(user_data)
2919 user_groups_rows.append(user_data)
2920
2920
2921 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2921 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2922
2922
2923 def permission_user_groups(self, with_members=False):
2923 def permission_user_groups(self, with_members=False):
2924 q = UserGroupRepoGroupToPerm.query()\
2924 q = UserGroupRepoGroupToPerm.query()\
2925 .filter(UserGroupRepoGroupToPerm.group == self)
2925 .filter(UserGroupRepoGroupToPerm.group == self)
2926 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2926 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2927 joinedload(UserGroupRepoGroupToPerm.users_group),
2927 joinedload(UserGroupRepoGroupToPerm.users_group),
2928 joinedload(UserGroupRepoGroupToPerm.permission),)
2928 joinedload(UserGroupRepoGroupToPerm.permission),)
2929
2929
2930 perm_rows = []
2930 perm_rows = []
2931 for _user_group in q.all():
2931 for _user_group in q.all():
2932 entry = AttributeDict(_user_group.users_group.get_dict())
2932 entry = AttributeDict(_user_group.users_group.get_dict())
2933 entry.permission = _user_group.permission.permission_name
2933 entry.permission = _user_group.permission.permission_name
2934 if with_members:
2934 if with_members:
2935 entry.members = [x.user.get_dict()
2935 entry.members = [x.user.get_dict()
2936 for x in _user_group.users_group.members]
2936 for x in _user_group.users_group.members]
2937 perm_rows.append(entry)
2937 perm_rows.append(entry)
2938
2938
2939 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2939 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2940 return perm_rows
2940 return perm_rows
2941
2941
2942 def get_api_data(self):
2942 def get_api_data(self):
2943 """
2943 """
2944 Common function for generating api data
2944 Common function for generating api data
2945
2945
2946 """
2946 """
2947 group = self
2947 group = self
2948 data = {
2948 data = {
2949 'group_id': group.group_id,
2949 'group_id': group.group_id,
2950 'group_name': group.group_name,
2950 'group_name': group.group_name,
2951 'group_description': group.description_safe,
2951 'group_description': group.description_safe,
2952 'parent_group': group.parent_group.group_name if group.parent_group else None,
2952 'parent_group': group.parent_group.group_name if group.parent_group else None,
2953 'repositories': [x.repo_name for x in group.repositories],
2953 'repositories': [x.repo_name for x in group.repositories],
2954 'owner': group.user.username,
2954 'owner': group.user.username,
2955 }
2955 }
2956 return data
2956 return data
2957
2957
2958 def get_dict(self):
2958 def get_dict(self):
2959 # Since we transformed `group_name` to a hybrid property, we need to
2959 # Since we transformed `group_name` to a hybrid property, we need to
2960 # keep compatibility with the code which uses `group_name` field.
2960 # keep compatibility with the code which uses `group_name` field.
2961 result = super(RepoGroup, self).get_dict()
2961 result = super(RepoGroup, self).get_dict()
2962 result['group_name'] = result.pop('_group_name', None)
2962 result['group_name'] = result.pop('_group_name', None)
2963 return result
2963 return result
2964
2964
2965
2965
2966 class Permission(Base, BaseModel):
2966 class Permission(Base, BaseModel):
2967 __tablename__ = 'permissions'
2967 __tablename__ = 'permissions'
2968 __table_args__ = (
2968 __table_args__ = (
2969 Index('p_perm_name_idx', 'permission_name'),
2969 Index('p_perm_name_idx', 'permission_name'),
2970 base_table_args,
2970 base_table_args,
2971 )
2971 )
2972
2972
2973 PERMS = [
2973 PERMS = [
2974 ('hg.admin', _('RhodeCode Super Administrator')),
2974 ('hg.admin', _('RhodeCode Super Administrator')),
2975
2975
2976 ('repository.none', _('Repository no access')),
2976 ('repository.none', _('Repository no access')),
2977 ('repository.read', _('Repository read access')),
2977 ('repository.read', _('Repository read access')),
2978 ('repository.write', _('Repository write access')),
2978 ('repository.write', _('Repository write access')),
2979 ('repository.admin', _('Repository admin access')),
2979 ('repository.admin', _('Repository admin access')),
2980
2980
2981 ('group.none', _('Repository group no access')),
2981 ('group.none', _('Repository group no access')),
2982 ('group.read', _('Repository group read access')),
2982 ('group.read', _('Repository group read access')),
2983 ('group.write', _('Repository group write access')),
2983 ('group.write', _('Repository group write access')),
2984 ('group.admin', _('Repository group admin access')),
2984 ('group.admin', _('Repository group admin access')),
2985
2985
2986 ('usergroup.none', _('User group no access')),
2986 ('usergroup.none', _('User group no access')),
2987 ('usergroup.read', _('User group read access')),
2987 ('usergroup.read', _('User group read access')),
2988 ('usergroup.write', _('User group write access')),
2988 ('usergroup.write', _('User group write access')),
2989 ('usergroup.admin', _('User group admin access')),
2989 ('usergroup.admin', _('User group admin access')),
2990
2990
2991 ('branch.none', _('Branch no permissions')),
2991 ('branch.none', _('Branch no permissions')),
2992 ('branch.merge', _('Branch access by web merge')),
2992 ('branch.merge', _('Branch access by web merge')),
2993 ('branch.push', _('Branch access by push')),
2993 ('branch.push', _('Branch access by push')),
2994 ('branch.push_force', _('Branch access by push with force')),
2994 ('branch.push_force', _('Branch access by push with force')),
2995
2995
2996 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2996 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2997 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2997 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2998
2998
2999 ('hg.usergroup.create.false', _('User Group creation disabled')),
2999 ('hg.usergroup.create.false', _('User Group creation disabled')),
3000 ('hg.usergroup.create.true', _('User Group creation enabled')),
3000 ('hg.usergroup.create.true', _('User Group creation enabled')),
3001
3001
3002 ('hg.create.none', _('Repository creation disabled')),
3002 ('hg.create.none', _('Repository creation disabled')),
3003 ('hg.create.repository', _('Repository creation enabled')),
3003 ('hg.create.repository', _('Repository creation enabled')),
3004 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3004 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3005 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3005 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3006
3006
3007 ('hg.fork.none', _('Repository forking disabled')),
3007 ('hg.fork.none', _('Repository forking disabled')),
3008 ('hg.fork.repository', _('Repository forking enabled')),
3008 ('hg.fork.repository', _('Repository forking enabled')),
3009
3009
3010 ('hg.register.none', _('Registration disabled')),
3010 ('hg.register.none', _('Registration disabled')),
3011 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3011 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3012 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3012 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3013
3013
3014 ('hg.password_reset.enabled', _('Password reset enabled')),
3014 ('hg.password_reset.enabled', _('Password reset enabled')),
3015 ('hg.password_reset.hidden', _('Password reset hidden')),
3015 ('hg.password_reset.hidden', _('Password reset hidden')),
3016 ('hg.password_reset.disabled', _('Password reset disabled')),
3016 ('hg.password_reset.disabled', _('Password reset disabled')),
3017
3017
3018 ('hg.extern_activate.manual', _('Manual activation of external account')),
3018 ('hg.extern_activate.manual', _('Manual activation of external account')),
3019 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3019 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3020
3020
3021 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3021 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3022 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3022 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3023 ]
3023 ]
3024
3024
3025 # definition of system default permissions for DEFAULT user, created on
3025 # definition of system default permissions for DEFAULT user, created on
3026 # system setup
3026 # system setup
3027 DEFAULT_USER_PERMISSIONS = [
3027 DEFAULT_USER_PERMISSIONS = [
3028 # object perms
3028 # object perms
3029 'repository.read',
3029 'repository.read',
3030 'group.read',
3030 'group.read',
3031 'usergroup.read',
3031 'usergroup.read',
3032 # branch, for backward compat we need same value as before so forced pushed
3032 # branch, for backward compat we need same value as before so forced pushed
3033 'branch.push_force',
3033 'branch.push_force',
3034 # global
3034 # global
3035 'hg.create.repository',
3035 'hg.create.repository',
3036 'hg.repogroup.create.false',
3036 'hg.repogroup.create.false',
3037 'hg.usergroup.create.false',
3037 'hg.usergroup.create.false',
3038 'hg.create.write_on_repogroup.true',
3038 'hg.create.write_on_repogroup.true',
3039 'hg.fork.repository',
3039 'hg.fork.repository',
3040 'hg.register.manual_activate',
3040 'hg.register.manual_activate',
3041 'hg.password_reset.enabled',
3041 'hg.password_reset.enabled',
3042 'hg.extern_activate.auto',
3042 'hg.extern_activate.auto',
3043 'hg.inherit_default_perms.true',
3043 'hg.inherit_default_perms.true',
3044 ]
3044 ]
3045
3045
3046 # defines which permissions are more important higher the more important
3046 # defines which permissions are more important higher the more important
3047 # Weight defines which permissions are more important.
3047 # Weight defines which permissions are more important.
3048 # The higher number the more important.
3048 # The higher number the more important.
3049 PERM_WEIGHTS = {
3049 PERM_WEIGHTS = {
3050 'repository.none': 0,
3050 'repository.none': 0,
3051 'repository.read': 1,
3051 'repository.read': 1,
3052 'repository.write': 3,
3052 'repository.write': 3,
3053 'repository.admin': 4,
3053 'repository.admin': 4,
3054
3054
3055 'group.none': 0,
3055 'group.none': 0,
3056 'group.read': 1,
3056 'group.read': 1,
3057 'group.write': 3,
3057 'group.write': 3,
3058 'group.admin': 4,
3058 'group.admin': 4,
3059
3059
3060 'usergroup.none': 0,
3060 'usergroup.none': 0,
3061 'usergroup.read': 1,
3061 'usergroup.read': 1,
3062 'usergroup.write': 3,
3062 'usergroup.write': 3,
3063 'usergroup.admin': 4,
3063 'usergroup.admin': 4,
3064
3064
3065 'branch.none': 0,
3065 'branch.none': 0,
3066 'branch.merge': 1,
3066 'branch.merge': 1,
3067 'branch.push': 3,
3067 'branch.push': 3,
3068 'branch.push_force': 4,
3068 'branch.push_force': 4,
3069
3069
3070 'hg.repogroup.create.false': 0,
3070 'hg.repogroup.create.false': 0,
3071 'hg.repogroup.create.true': 1,
3071 'hg.repogroup.create.true': 1,
3072
3072
3073 'hg.usergroup.create.false': 0,
3073 'hg.usergroup.create.false': 0,
3074 'hg.usergroup.create.true': 1,
3074 'hg.usergroup.create.true': 1,
3075
3075
3076 'hg.fork.none': 0,
3076 'hg.fork.none': 0,
3077 'hg.fork.repository': 1,
3077 'hg.fork.repository': 1,
3078 'hg.create.none': 0,
3078 'hg.create.none': 0,
3079 'hg.create.repository': 1
3079 'hg.create.repository': 1
3080 }
3080 }
3081
3081
3082 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3082 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3083 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3083 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3084 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3084 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3085
3085
3086 def __unicode__(self):
3086 def __unicode__(self):
3087 return u"<%s('%s:%s')>" % (
3087 return u"<%s('%s:%s')>" % (
3088 self.__class__.__name__, self.permission_id, self.permission_name
3088 self.__class__.__name__, self.permission_id, self.permission_name
3089 )
3089 )
3090
3090
3091 @classmethod
3091 @classmethod
3092 def get_by_key(cls, key):
3092 def get_by_key(cls, key):
3093 return cls.query().filter(cls.permission_name == key).scalar()
3093 return cls.query().filter(cls.permission_name == key).scalar()
3094
3094
3095 @classmethod
3095 @classmethod
3096 def get_default_repo_perms(cls, user_id, repo_id=None):
3096 def get_default_repo_perms(cls, user_id, repo_id=None):
3097 q = Session().query(UserRepoToPerm, Repository, Permission)\
3097 q = Session().query(UserRepoToPerm, Repository, Permission)\
3098 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3098 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3099 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3099 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3100 .filter(UserRepoToPerm.user_id == user_id)
3100 .filter(UserRepoToPerm.user_id == user_id)
3101 if repo_id:
3101 if repo_id:
3102 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3102 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3103 return q.all()
3103 return q.all()
3104
3104
3105 @classmethod
3105 @classmethod
3106 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3106 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3107 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3107 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3108 .join(
3108 .join(
3109 Permission,
3109 Permission,
3110 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3110 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3111 .join(
3111 .join(
3112 UserRepoToPerm,
3112 UserRepoToPerm,
3113 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3113 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3114 .filter(UserRepoToPerm.user_id == user_id)
3114 .filter(UserRepoToPerm.user_id == user_id)
3115
3115
3116 if repo_id:
3116 if repo_id:
3117 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3117 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3118 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3118 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3119
3119
3120 @classmethod
3120 @classmethod
3121 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3121 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3122 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3122 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3123 .join(
3123 .join(
3124 Permission,
3124 Permission,
3125 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3125 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3126 .join(
3126 .join(
3127 Repository,
3127 Repository,
3128 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3128 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3129 .join(
3129 .join(
3130 UserGroup,
3130 UserGroup,
3131 UserGroupRepoToPerm.users_group_id ==
3131 UserGroupRepoToPerm.users_group_id ==
3132 UserGroup.users_group_id)\
3132 UserGroup.users_group_id)\
3133 .join(
3133 .join(
3134 UserGroupMember,
3134 UserGroupMember,
3135 UserGroupRepoToPerm.users_group_id ==
3135 UserGroupRepoToPerm.users_group_id ==
3136 UserGroupMember.users_group_id)\
3136 UserGroupMember.users_group_id)\
3137 .filter(
3137 .filter(
3138 UserGroupMember.user_id == user_id,
3138 UserGroupMember.user_id == user_id,
3139 UserGroup.users_group_active == true())
3139 UserGroup.users_group_active == true())
3140 if repo_id:
3140 if repo_id:
3141 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3141 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3142 return q.all()
3142 return q.all()
3143
3143
3144 @classmethod
3144 @classmethod
3145 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3145 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3146 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3146 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3147 .join(
3147 .join(
3148 Permission,
3148 Permission,
3149 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3149 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3150 .join(
3150 .join(
3151 UserGroupRepoToPerm,
3151 UserGroupRepoToPerm,
3152 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3152 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3153 .join(
3153 .join(
3154 UserGroup,
3154 UserGroup,
3155 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3155 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3156 .join(
3156 .join(
3157 UserGroupMember,
3157 UserGroupMember,
3158 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3158 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3159 .filter(
3159 .filter(
3160 UserGroupMember.user_id == user_id,
3160 UserGroupMember.user_id == user_id,
3161 UserGroup.users_group_active == true())
3161 UserGroup.users_group_active == true())
3162
3162
3163 if repo_id:
3163 if repo_id:
3164 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3164 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3165 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3165 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3166
3166
3167 @classmethod
3167 @classmethod
3168 def get_default_group_perms(cls, user_id, repo_group_id=None):
3168 def get_default_group_perms(cls, user_id, repo_group_id=None):
3169 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3169 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3170 .join(
3170 .join(
3171 Permission,
3171 Permission,
3172 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3172 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3173 .join(
3173 .join(
3174 RepoGroup,
3174 RepoGroup,
3175 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3175 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3176 .filter(UserRepoGroupToPerm.user_id == user_id)
3176 .filter(UserRepoGroupToPerm.user_id == user_id)
3177 if repo_group_id:
3177 if repo_group_id:
3178 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3178 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3179 return q.all()
3179 return q.all()
3180
3180
3181 @classmethod
3181 @classmethod
3182 def get_default_group_perms_from_user_group(
3182 def get_default_group_perms_from_user_group(
3183 cls, user_id, repo_group_id=None):
3183 cls, user_id, repo_group_id=None):
3184 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3184 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3185 .join(
3185 .join(
3186 Permission,
3186 Permission,
3187 UserGroupRepoGroupToPerm.permission_id ==
3187 UserGroupRepoGroupToPerm.permission_id ==
3188 Permission.permission_id)\
3188 Permission.permission_id)\
3189 .join(
3189 .join(
3190 RepoGroup,
3190 RepoGroup,
3191 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3191 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3192 .join(
3192 .join(
3193 UserGroup,
3193 UserGroup,
3194 UserGroupRepoGroupToPerm.users_group_id ==
3194 UserGroupRepoGroupToPerm.users_group_id ==
3195 UserGroup.users_group_id)\
3195 UserGroup.users_group_id)\
3196 .join(
3196 .join(
3197 UserGroupMember,
3197 UserGroupMember,
3198 UserGroupRepoGroupToPerm.users_group_id ==
3198 UserGroupRepoGroupToPerm.users_group_id ==
3199 UserGroupMember.users_group_id)\
3199 UserGroupMember.users_group_id)\
3200 .filter(
3200 .filter(
3201 UserGroupMember.user_id == user_id,
3201 UserGroupMember.user_id == user_id,
3202 UserGroup.users_group_active == true())
3202 UserGroup.users_group_active == true())
3203 if repo_group_id:
3203 if repo_group_id:
3204 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3204 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3205 return q.all()
3205 return q.all()
3206
3206
3207 @classmethod
3207 @classmethod
3208 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3208 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3209 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3209 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3210 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3210 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3211 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3211 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3212 .filter(UserUserGroupToPerm.user_id == user_id)
3212 .filter(UserUserGroupToPerm.user_id == user_id)
3213 if user_group_id:
3213 if user_group_id:
3214 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3214 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3215 return q.all()
3215 return q.all()
3216
3216
3217 @classmethod
3217 @classmethod
3218 def get_default_user_group_perms_from_user_group(
3218 def get_default_user_group_perms_from_user_group(
3219 cls, user_id, user_group_id=None):
3219 cls, user_id, user_group_id=None):
3220 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3220 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3221 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3221 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3222 .join(
3222 .join(
3223 Permission,
3223 Permission,
3224 UserGroupUserGroupToPerm.permission_id ==
3224 UserGroupUserGroupToPerm.permission_id ==
3225 Permission.permission_id)\
3225 Permission.permission_id)\
3226 .join(
3226 .join(
3227 TargetUserGroup,
3227 TargetUserGroup,
3228 UserGroupUserGroupToPerm.target_user_group_id ==
3228 UserGroupUserGroupToPerm.target_user_group_id ==
3229 TargetUserGroup.users_group_id)\
3229 TargetUserGroup.users_group_id)\
3230 .join(
3230 .join(
3231 UserGroup,
3231 UserGroup,
3232 UserGroupUserGroupToPerm.user_group_id ==
3232 UserGroupUserGroupToPerm.user_group_id ==
3233 UserGroup.users_group_id)\
3233 UserGroup.users_group_id)\
3234 .join(
3234 .join(
3235 UserGroupMember,
3235 UserGroupMember,
3236 UserGroupUserGroupToPerm.user_group_id ==
3236 UserGroupUserGroupToPerm.user_group_id ==
3237 UserGroupMember.users_group_id)\
3237 UserGroupMember.users_group_id)\
3238 .filter(
3238 .filter(
3239 UserGroupMember.user_id == user_id,
3239 UserGroupMember.user_id == user_id,
3240 UserGroup.users_group_active == true())
3240 UserGroup.users_group_active == true())
3241 if user_group_id:
3241 if user_group_id:
3242 q = q.filter(
3242 q = q.filter(
3243 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3243 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3244
3244
3245 return q.all()
3245 return q.all()
3246
3246
3247
3247
3248 class UserRepoToPerm(Base, BaseModel):
3248 class UserRepoToPerm(Base, BaseModel):
3249 __tablename__ = 'repo_to_perm'
3249 __tablename__ = 'repo_to_perm'
3250 __table_args__ = (
3250 __table_args__ = (
3251 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3251 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3252 base_table_args
3252 base_table_args
3253 )
3253 )
3254
3254
3255 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3255 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3256 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3256 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3257 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3257 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3258 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3258 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3259
3259
3260 user = relationship('User')
3260 user = relationship('User')
3261 repository = relationship('Repository')
3261 repository = relationship('Repository')
3262 permission = relationship('Permission')
3262 permission = relationship('Permission')
3263
3263
3264 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3264 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete, delete-orphan", lazy='joined')
3265
3265
3266 @classmethod
3266 @classmethod
3267 def create(cls, user, repository, permission):
3267 def create(cls, user, repository, permission):
3268 n = cls()
3268 n = cls()
3269 n.user = user
3269 n.user = user
3270 n.repository = repository
3270 n.repository = repository
3271 n.permission = permission
3271 n.permission = permission
3272 Session().add(n)
3272 Session().add(n)
3273 return n
3273 return n
3274
3274
3275 def __unicode__(self):
3275 def __unicode__(self):
3276 return u'<%s => %s >' % (self.user, self.repository)
3276 return u'<%s => %s >' % (self.user, self.repository)
3277
3277
3278
3278
3279 class UserUserGroupToPerm(Base, BaseModel):
3279 class UserUserGroupToPerm(Base, BaseModel):
3280 __tablename__ = 'user_user_group_to_perm'
3280 __tablename__ = 'user_user_group_to_perm'
3281 __table_args__ = (
3281 __table_args__ = (
3282 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3282 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3283 base_table_args
3283 base_table_args
3284 )
3284 )
3285
3285
3286 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3286 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3287 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3287 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3288 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3288 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3289 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3289 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3290
3290
3291 user = relationship('User')
3291 user = relationship('User')
3292 user_group = relationship('UserGroup')
3292 user_group = relationship('UserGroup')
3293 permission = relationship('Permission')
3293 permission = relationship('Permission')
3294
3294
3295 @classmethod
3295 @classmethod
3296 def create(cls, user, user_group, permission):
3296 def create(cls, user, user_group, permission):
3297 n = cls()
3297 n = cls()
3298 n.user = user
3298 n.user = user
3299 n.user_group = user_group
3299 n.user_group = user_group
3300 n.permission = permission
3300 n.permission = permission
3301 Session().add(n)
3301 Session().add(n)
3302 return n
3302 return n
3303
3303
3304 def __unicode__(self):
3304 def __unicode__(self):
3305 return u'<%s => %s >' % (self.user, self.user_group)
3305 return u'<%s => %s >' % (self.user, self.user_group)
3306
3306
3307
3307
3308 class UserToPerm(Base, BaseModel):
3308 class UserToPerm(Base, BaseModel):
3309 __tablename__ = 'user_to_perm'
3309 __tablename__ = 'user_to_perm'
3310 __table_args__ = (
3310 __table_args__ = (
3311 UniqueConstraint('user_id', 'permission_id'),
3311 UniqueConstraint('user_id', 'permission_id'),
3312 base_table_args
3312 base_table_args
3313 )
3313 )
3314
3314
3315 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3315 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3316 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3316 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3317 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3317 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3318
3318
3319 user = relationship('User')
3319 user = relationship('User')
3320 permission = relationship('Permission', lazy='joined')
3320 permission = relationship('Permission', lazy='joined')
3321
3321
3322 def __unicode__(self):
3322 def __unicode__(self):
3323 return u'<%s => %s >' % (self.user, self.permission)
3323 return u'<%s => %s >' % (self.user, self.permission)
3324
3324
3325
3325
3326 class UserGroupRepoToPerm(Base, BaseModel):
3326 class UserGroupRepoToPerm(Base, BaseModel):
3327 __tablename__ = 'users_group_repo_to_perm'
3327 __tablename__ = 'users_group_repo_to_perm'
3328 __table_args__ = (
3328 __table_args__ = (
3329 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3329 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3330 base_table_args
3330 base_table_args
3331 )
3331 )
3332
3332
3333 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3333 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3334 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3334 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3335 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3335 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3336 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3336 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3337
3337
3338 users_group = relationship('UserGroup')
3338 users_group = relationship('UserGroup')
3339 permission = relationship('Permission')
3339 permission = relationship('Permission')
3340 repository = relationship('Repository')
3340 repository = relationship('Repository')
3341 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3341 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3342
3342
3343 @classmethod
3343 @classmethod
3344 def create(cls, users_group, repository, permission):
3344 def create(cls, users_group, repository, permission):
3345 n = cls()
3345 n = cls()
3346 n.users_group = users_group
3346 n.users_group = users_group
3347 n.repository = repository
3347 n.repository = repository
3348 n.permission = permission
3348 n.permission = permission
3349 Session().add(n)
3349 Session().add(n)
3350 return n
3350 return n
3351
3351
3352 def __unicode__(self):
3352 def __unicode__(self):
3353 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3353 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3354
3354
3355
3355
3356 class UserGroupUserGroupToPerm(Base, BaseModel):
3356 class UserGroupUserGroupToPerm(Base, BaseModel):
3357 __tablename__ = 'user_group_user_group_to_perm'
3357 __tablename__ = 'user_group_user_group_to_perm'
3358 __table_args__ = (
3358 __table_args__ = (
3359 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3359 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3360 CheckConstraint('target_user_group_id != user_group_id'),
3360 CheckConstraint('target_user_group_id != user_group_id'),
3361 base_table_args
3361 base_table_args
3362 )
3362 )
3363
3363
3364 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)
3364 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)
3365 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3365 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3366 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3366 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3367 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3367 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3368
3368
3369 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3369 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3370 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3370 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3371 permission = relationship('Permission')
3371 permission = relationship('Permission')
3372
3372
3373 @classmethod
3373 @classmethod
3374 def create(cls, target_user_group, user_group, permission):
3374 def create(cls, target_user_group, user_group, permission):
3375 n = cls()
3375 n = cls()
3376 n.target_user_group = target_user_group
3376 n.target_user_group = target_user_group
3377 n.user_group = user_group
3377 n.user_group = user_group
3378 n.permission = permission
3378 n.permission = permission
3379 Session().add(n)
3379 Session().add(n)
3380 return n
3380 return n
3381
3381
3382 def __unicode__(self):
3382 def __unicode__(self):
3383 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3383 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3384
3384
3385
3385
3386 class UserGroupToPerm(Base, BaseModel):
3386 class UserGroupToPerm(Base, BaseModel):
3387 __tablename__ = 'users_group_to_perm'
3387 __tablename__ = 'users_group_to_perm'
3388 __table_args__ = (
3388 __table_args__ = (
3389 UniqueConstraint('users_group_id', 'permission_id',),
3389 UniqueConstraint('users_group_id', 'permission_id',),
3390 base_table_args
3390 base_table_args
3391 )
3391 )
3392
3392
3393 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3393 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3394 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3394 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3395 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3395 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3396
3396
3397 users_group = relationship('UserGroup')
3397 users_group = relationship('UserGroup')
3398 permission = relationship('Permission')
3398 permission = relationship('Permission')
3399
3399
3400
3400
3401 class UserRepoGroupToPerm(Base, BaseModel):
3401 class UserRepoGroupToPerm(Base, BaseModel):
3402 __tablename__ = 'user_repo_group_to_perm'
3402 __tablename__ = 'user_repo_group_to_perm'
3403 __table_args__ = (
3403 __table_args__ = (
3404 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3404 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3405 base_table_args
3405 base_table_args
3406 )
3406 )
3407
3407
3408 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3408 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3409 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3409 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3410 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3410 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3411 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3411 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3412
3412
3413 user = relationship('User')
3413 user = relationship('User')
3414 group = relationship('RepoGroup')
3414 group = relationship('RepoGroup')
3415 permission = relationship('Permission')
3415 permission = relationship('Permission')
3416
3416
3417 @classmethod
3417 @classmethod
3418 def create(cls, user, repository_group, permission):
3418 def create(cls, user, repository_group, permission):
3419 n = cls()
3419 n = cls()
3420 n.user = user
3420 n.user = user
3421 n.group = repository_group
3421 n.group = repository_group
3422 n.permission = permission
3422 n.permission = permission
3423 Session().add(n)
3423 Session().add(n)
3424 return n
3424 return n
3425
3425
3426
3426
3427 class UserGroupRepoGroupToPerm(Base, BaseModel):
3427 class UserGroupRepoGroupToPerm(Base, BaseModel):
3428 __tablename__ = 'users_group_repo_group_to_perm'
3428 __tablename__ = 'users_group_repo_group_to_perm'
3429 __table_args__ = (
3429 __table_args__ = (
3430 UniqueConstraint('users_group_id', 'group_id'),
3430 UniqueConstraint('users_group_id', 'group_id'),
3431 base_table_args
3431 base_table_args
3432 )
3432 )
3433
3433
3434 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)
3434 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)
3435 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3435 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3436 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3436 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3437 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3437 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3438
3438
3439 users_group = relationship('UserGroup')
3439 users_group = relationship('UserGroup')
3440 permission = relationship('Permission')
3440 permission = relationship('Permission')
3441 group = relationship('RepoGroup')
3441 group = relationship('RepoGroup')
3442
3442
3443 @classmethod
3443 @classmethod
3444 def create(cls, user_group, repository_group, permission):
3444 def create(cls, user_group, repository_group, permission):
3445 n = cls()
3445 n = cls()
3446 n.users_group = user_group
3446 n.users_group = user_group
3447 n.group = repository_group
3447 n.group = repository_group
3448 n.permission = permission
3448 n.permission = permission
3449 Session().add(n)
3449 Session().add(n)
3450 return n
3450 return n
3451
3451
3452 def __unicode__(self):
3452 def __unicode__(self):
3453 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3453 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3454
3454
3455
3455
3456 class Statistics(Base, BaseModel):
3456 class Statistics(Base, BaseModel):
3457 __tablename__ = 'statistics'
3457 __tablename__ = 'statistics'
3458 __table_args__ = (
3458 __table_args__ = (
3459 base_table_args
3459 base_table_args
3460 )
3460 )
3461
3461
3462 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3462 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3463 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3463 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3464 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3464 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3465 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3465 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3466 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3466 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3467 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3467 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3468
3468
3469 repository = relationship('Repository', single_parent=True)
3469 repository = relationship('Repository', single_parent=True)
3470
3470
3471
3471
3472 class UserFollowing(Base, BaseModel):
3472 class UserFollowing(Base, BaseModel):
3473 __tablename__ = 'user_followings'
3473 __tablename__ = 'user_followings'
3474 __table_args__ = (
3474 __table_args__ = (
3475 UniqueConstraint('user_id', 'follows_repository_id'),
3475 UniqueConstraint('user_id', 'follows_repository_id'),
3476 UniqueConstraint('user_id', 'follows_user_id'),
3476 UniqueConstraint('user_id', 'follows_user_id'),
3477 base_table_args
3477 base_table_args
3478 )
3478 )
3479
3479
3480 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3480 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3481 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3481 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3482 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3482 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3483 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3483 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3484 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3484 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3485
3485
3486 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3486 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3487
3487
3488 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3488 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3489 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3489 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3490
3490
3491 @classmethod
3491 @classmethod
3492 def get_repo_followers(cls, repo_id):
3492 def get_repo_followers(cls, repo_id):
3493 return cls.query().filter(cls.follows_repo_id == repo_id)
3493 return cls.query().filter(cls.follows_repo_id == repo_id)
3494
3494
3495
3495
3496 class CacheKey(Base, BaseModel):
3496 class CacheKey(Base, BaseModel):
3497 __tablename__ = 'cache_invalidation'
3497 __tablename__ = 'cache_invalidation'
3498 __table_args__ = (
3498 __table_args__ = (
3499 UniqueConstraint('cache_key'),
3499 UniqueConstraint('cache_key'),
3500 Index('key_idx', 'cache_key'),
3500 Index('key_idx', 'cache_key'),
3501 base_table_args,
3501 base_table_args,
3502 )
3502 )
3503
3503
3504 CACHE_TYPE_FEED = 'FEED'
3504 CACHE_TYPE_FEED = 'FEED'
3505 CACHE_TYPE_README = 'README'
3505 CACHE_TYPE_README = 'README'
3506 # namespaces used to register process/thread aware caches
3506 # namespaces used to register process/thread aware caches
3507 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3507 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3508 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3508 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3509
3509
3510 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3510 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3511 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3511 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3512 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3512 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3513 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3513 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3514 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3514 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3515
3515
3516 def __init__(self, cache_key, cache_args='', cache_state_uid=None):
3516 def __init__(self, cache_key, cache_args='', cache_state_uid=None):
3517 self.cache_key = cache_key
3517 self.cache_key = cache_key
3518 self.cache_args = cache_args
3518 self.cache_args = cache_args
3519 self.cache_active = False
3519 self.cache_active = False
3520 # first key should be same for all entries, since all workers should share it
3520 # first key should be same for all entries, since all workers should share it
3521 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid(based_on=cache_args)
3521 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid(based_on=cache_args)
3522
3522
3523 def __unicode__(self):
3523 def __unicode__(self):
3524 return u"<%s('%s:%s[%s]')>" % (
3524 return u"<%s('%s:%s[%s]')>" % (
3525 self.__class__.__name__,
3525 self.__class__.__name__,
3526 self.cache_id, self.cache_key, self.cache_active)
3526 self.cache_id, self.cache_key, self.cache_active)
3527
3527
3528 def _cache_key_partition(self):
3528 def _cache_key_partition(self):
3529 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3529 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3530 return prefix, repo_name, suffix
3530 return prefix, repo_name, suffix
3531
3531
3532 def get_prefix(self):
3532 def get_prefix(self):
3533 """
3533 """
3534 Try to extract prefix from existing cache key. The key could consist
3534 Try to extract prefix from existing cache key. The key could consist
3535 of prefix, repo_name, suffix
3535 of prefix, repo_name, suffix
3536 """
3536 """
3537 # this returns prefix, repo_name, suffix
3537 # this returns prefix, repo_name, suffix
3538 return self._cache_key_partition()[0]
3538 return self._cache_key_partition()[0]
3539
3539
3540 def get_suffix(self):
3540 def get_suffix(self):
3541 """
3541 """
3542 get suffix that might have been used in _get_cache_key to
3542 get suffix that might have been used in _get_cache_key to
3543 generate self.cache_key. Only used for informational purposes
3543 generate self.cache_key. Only used for informational purposes
3544 in repo_edit.mako.
3544 in repo_edit.mako.
3545 """
3545 """
3546 # prefix, repo_name, suffix
3546 # prefix, repo_name, suffix
3547 return self._cache_key_partition()[2]
3547 return self._cache_key_partition()[2]
3548
3548
3549 @classmethod
3549 @classmethod
3550 def generate_new_state_uid(cls, based_on=None):
3550 def generate_new_state_uid(cls, based_on=None):
3551 if based_on:
3551 if based_on:
3552 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3552 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3553 else:
3553 else:
3554 return str(uuid.uuid4())
3554 return str(uuid.uuid4())
3555
3555
3556 @classmethod
3556 @classmethod
3557 def delete_all_cache(cls):
3557 def delete_all_cache(cls):
3558 """
3558 """
3559 Delete all cache keys from database.
3559 Delete all cache keys from database.
3560 Should only be run when all instances are down and all entries
3560 Should only be run when all instances are down and all entries
3561 thus stale.
3561 thus stale.
3562 """
3562 """
3563 cls.query().delete()
3563 cls.query().delete()
3564 Session().commit()
3564 Session().commit()
3565
3565
3566 @classmethod
3566 @classmethod
3567 def set_invalidate(cls, cache_uid, delete=False):
3567 def set_invalidate(cls, cache_uid, delete=False):
3568 """
3568 """
3569 Mark all caches of a repo as invalid in the database.
3569 Mark all caches of a repo as invalid in the database.
3570 """
3570 """
3571
3571
3572 try:
3572 try:
3573 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3573 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3574 if delete:
3574 if delete:
3575 qry.delete()
3575 qry.delete()
3576 log.debug('cache objects deleted for cache args %s',
3576 log.debug('cache objects deleted for cache args %s',
3577 safe_str(cache_uid))
3577 safe_str(cache_uid))
3578 else:
3578 else:
3579 qry.update({"cache_active": False,
3579 qry.update({"cache_active": False,
3580 "cache_state_uid": cls.generate_new_state_uid()})
3580 "cache_state_uid": cls.generate_new_state_uid()})
3581 log.debug('cache objects marked as invalid for cache args %s',
3581 log.debug('cache objects marked as invalid for cache args %s',
3582 safe_str(cache_uid))
3582 safe_str(cache_uid))
3583
3583
3584 Session().commit()
3584 Session().commit()
3585 except Exception:
3585 except Exception:
3586 log.exception(
3586 log.exception(
3587 'Cache key invalidation failed for cache args %s',
3587 'Cache key invalidation failed for cache args %s',
3588 safe_str(cache_uid))
3588 safe_str(cache_uid))
3589 Session().rollback()
3589 Session().rollback()
3590
3590
3591 @classmethod
3591 @classmethod
3592 def get_active_cache(cls, cache_key):
3592 def get_active_cache(cls, cache_key):
3593 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3593 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3594 if inv_obj:
3594 if inv_obj:
3595 return inv_obj
3595 return inv_obj
3596 return None
3596 return None
3597
3597
3598
3598
3599 class ChangesetComment(Base, BaseModel):
3599 class ChangesetComment(Base, BaseModel):
3600 __tablename__ = 'changeset_comments'
3600 __tablename__ = 'changeset_comments'
3601 __table_args__ = (
3601 __table_args__ = (
3602 Index('cc_revision_idx', 'revision'),
3602 Index('cc_revision_idx', 'revision'),
3603 base_table_args,
3603 base_table_args,
3604 )
3604 )
3605
3605
3606 COMMENT_OUTDATED = u'comment_outdated'
3606 COMMENT_OUTDATED = u'comment_outdated'
3607 COMMENT_TYPE_NOTE = u'note'
3607 COMMENT_TYPE_NOTE = u'note'
3608 COMMENT_TYPE_TODO = u'todo'
3608 COMMENT_TYPE_TODO = u'todo'
3609 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3609 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3610
3610
3611 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3611 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3612 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3612 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3613 revision = Column('revision', String(40), nullable=True)
3613 revision = Column('revision', String(40), nullable=True)
3614 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3614 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3615 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3615 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3616 line_no = Column('line_no', Unicode(10), nullable=True)
3616 line_no = Column('line_no', Unicode(10), nullable=True)
3617 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3617 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3618 f_path = Column('f_path', Unicode(1000), nullable=True)
3618 f_path = Column('f_path', Unicode(1000), nullable=True)
3619 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3619 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3620 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3620 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3621 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3621 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3622 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3622 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3623 renderer = Column('renderer', Unicode(64), nullable=True)
3623 renderer = Column('renderer', Unicode(64), nullable=True)
3624 display_state = Column('display_state', Unicode(128), nullable=True)
3624 display_state = Column('display_state', Unicode(128), nullable=True)
3625
3625
3626 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3626 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3627 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3627 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3628
3628
3629 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3629 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3630 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3630 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3631
3631
3632 author = relationship('User', lazy='joined')
3632 author = relationship('User', lazy='joined')
3633 repo = relationship('Repository')
3633 repo = relationship('Repository')
3634 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3634 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3635 pull_request = relationship('PullRequest', lazy='joined')
3635 pull_request = relationship('PullRequest', lazy='joined')
3636 pull_request_version = relationship('PullRequestVersion')
3636 pull_request_version = relationship('PullRequestVersion')
3637
3637
3638 @classmethod
3638 @classmethod
3639 def get_users(cls, revision=None, pull_request_id=None):
3639 def get_users(cls, revision=None, pull_request_id=None):
3640 """
3640 """
3641 Returns user associated with this ChangesetComment. ie those
3641 Returns user associated with this ChangesetComment. ie those
3642 who actually commented
3642 who actually commented
3643
3643
3644 :param cls:
3644 :param cls:
3645 :param revision:
3645 :param revision:
3646 """
3646 """
3647 q = Session().query(User)\
3647 q = Session().query(User)\
3648 .join(ChangesetComment.author)
3648 .join(ChangesetComment.author)
3649 if revision:
3649 if revision:
3650 q = q.filter(cls.revision == revision)
3650 q = q.filter(cls.revision == revision)
3651 elif pull_request_id:
3651 elif pull_request_id:
3652 q = q.filter(cls.pull_request_id == pull_request_id)
3652 q = q.filter(cls.pull_request_id == pull_request_id)
3653 return q.all()
3653 return q.all()
3654
3654
3655 @classmethod
3655 @classmethod
3656 def get_index_from_version(cls, pr_version, versions):
3656 def get_index_from_version(cls, pr_version, versions):
3657 num_versions = [x.pull_request_version_id for x in versions]
3657 num_versions = [x.pull_request_version_id for x in versions]
3658 try:
3658 try:
3659 return num_versions.index(pr_version) +1
3659 return num_versions.index(pr_version) +1
3660 except (IndexError, ValueError):
3660 except (IndexError, ValueError):
3661 return
3661 return
3662
3662
3663 @property
3663 @property
3664 def outdated(self):
3664 def outdated(self):
3665 return self.display_state == self.COMMENT_OUTDATED
3665 return self.display_state == self.COMMENT_OUTDATED
3666
3666
3667 def outdated_at_version(self, version):
3667 def outdated_at_version(self, version):
3668 """
3668 """
3669 Checks if comment is outdated for given pull request version
3669 Checks if comment is outdated for given pull request version
3670 """
3670 """
3671 return self.outdated and self.pull_request_version_id != version
3671 return self.outdated and self.pull_request_version_id != version
3672
3672
3673 def older_than_version(self, version):
3673 def older_than_version(self, version):
3674 """
3674 """
3675 Checks if comment is made from previous version than given
3675 Checks if comment is made from previous version than given
3676 """
3676 """
3677 if version is None:
3677 if version is None:
3678 return self.pull_request_version_id is not None
3678 return self.pull_request_version_id is not None
3679
3679
3680 return self.pull_request_version_id < version
3680 return self.pull_request_version_id < version
3681
3681
3682 @property
3682 @property
3683 def resolved(self):
3683 def resolved(self):
3684 return self.resolved_by[0] if self.resolved_by else None
3684 return self.resolved_by[0] if self.resolved_by else None
3685
3685
3686 @property
3686 @property
3687 def is_todo(self):
3687 def is_todo(self):
3688 return self.comment_type == self.COMMENT_TYPE_TODO
3688 return self.comment_type == self.COMMENT_TYPE_TODO
3689
3689
3690 @property
3690 @property
3691 def is_inline(self):
3691 def is_inline(self):
3692 return self.line_no and self.f_path
3692 return self.line_no and self.f_path
3693
3693
3694 def get_index_version(self, versions):
3694 def get_index_version(self, versions):
3695 return self.get_index_from_version(
3695 return self.get_index_from_version(
3696 self.pull_request_version_id, versions)
3696 self.pull_request_version_id, versions)
3697
3697
3698 def __repr__(self):
3698 def __repr__(self):
3699 if self.comment_id:
3699 if self.comment_id:
3700 return '<DB:Comment #%s>' % self.comment_id
3700 return '<DB:Comment #%s>' % self.comment_id
3701 else:
3701 else:
3702 return '<DB:Comment at %#x>' % id(self)
3702 return '<DB:Comment at %#x>' % id(self)
3703
3703
3704 def get_api_data(self):
3704 def get_api_data(self):
3705 comment = self
3705 comment = self
3706 data = {
3706 data = {
3707 'comment_id': comment.comment_id,
3707 'comment_id': comment.comment_id,
3708 'comment_type': comment.comment_type,
3708 'comment_type': comment.comment_type,
3709 'comment_text': comment.text,
3709 'comment_text': comment.text,
3710 'comment_status': comment.status_change,
3710 'comment_status': comment.status_change,
3711 'comment_f_path': comment.f_path,
3711 'comment_f_path': comment.f_path,
3712 'comment_lineno': comment.line_no,
3712 'comment_lineno': comment.line_no,
3713 'comment_author': comment.author,
3713 'comment_author': comment.author,
3714 'comment_created_on': comment.created_on,
3714 'comment_created_on': comment.created_on,
3715 'comment_resolved_by': self.resolved
3715 'comment_resolved_by': self.resolved
3716 }
3716 }
3717 return data
3717 return data
3718
3718
3719 def __json__(self):
3719 def __json__(self):
3720 data = dict()
3720 data = dict()
3721 data.update(self.get_api_data())
3721 data.update(self.get_api_data())
3722 return data
3722 return data
3723
3723
3724
3724
3725 class ChangesetStatus(Base, BaseModel):
3725 class ChangesetStatus(Base, BaseModel):
3726 __tablename__ = 'changeset_statuses'
3726 __tablename__ = 'changeset_statuses'
3727 __table_args__ = (
3727 __table_args__ = (
3728 Index('cs_revision_idx', 'revision'),
3728 Index('cs_revision_idx', 'revision'),
3729 Index('cs_version_idx', 'version'),
3729 Index('cs_version_idx', 'version'),
3730 UniqueConstraint('repo_id', 'revision', 'version'),
3730 UniqueConstraint('repo_id', 'revision', 'version'),
3731 base_table_args
3731 base_table_args
3732 )
3732 )
3733
3733
3734 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3734 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3735 STATUS_APPROVED = 'approved'
3735 STATUS_APPROVED = 'approved'
3736 STATUS_REJECTED = 'rejected'
3736 STATUS_REJECTED = 'rejected'
3737 STATUS_UNDER_REVIEW = 'under_review'
3737 STATUS_UNDER_REVIEW = 'under_review'
3738
3738
3739 STATUSES = [
3739 STATUSES = [
3740 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3740 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3741 (STATUS_APPROVED, _("Approved")),
3741 (STATUS_APPROVED, _("Approved")),
3742 (STATUS_REJECTED, _("Rejected")),
3742 (STATUS_REJECTED, _("Rejected")),
3743 (STATUS_UNDER_REVIEW, _("Under Review")),
3743 (STATUS_UNDER_REVIEW, _("Under Review")),
3744 ]
3744 ]
3745
3745
3746 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3746 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3747 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3747 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3748 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3748 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3749 revision = Column('revision', String(40), nullable=False)
3749 revision = Column('revision', String(40), nullable=False)
3750 status = Column('status', String(128), nullable=False, default=DEFAULT)
3750 status = Column('status', String(128), nullable=False, default=DEFAULT)
3751 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3751 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3752 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3752 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3753 version = Column('version', Integer(), nullable=False, default=0)
3753 version = Column('version', Integer(), nullable=False, default=0)
3754 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3754 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3755
3755
3756 author = relationship('User', lazy='joined')
3756 author = relationship('User', lazy='joined')
3757 repo = relationship('Repository')
3757 repo = relationship('Repository')
3758 comment = relationship('ChangesetComment', lazy='joined')
3758 comment = relationship('ChangesetComment', lazy='joined')
3759 pull_request = relationship('PullRequest', lazy='joined')
3759 pull_request = relationship('PullRequest', lazy='joined')
3760
3760
3761 def __unicode__(self):
3761 def __unicode__(self):
3762 return u"<%s('%s[v%s]:%s')>" % (
3762 return u"<%s('%s[v%s]:%s')>" % (
3763 self.__class__.__name__,
3763 self.__class__.__name__,
3764 self.status, self.version, self.author
3764 self.status, self.version, self.author
3765 )
3765 )
3766
3766
3767 @classmethod
3767 @classmethod
3768 def get_status_lbl(cls, value):
3768 def get_status_lbl(cls, value):
3769 return dict(cls.STATUSES).get(value)
3769 return dict(cls.STATUSES).get(value)
3770
3770
3771 @property
3771 @property
3772 def status_lbl(self):
3772 def status_lbl(self):
3773 return ChangesetStatus.get_status_lbl(self.status)
3773 return ChangesetStatus.get_status_lbl(self.status)
3774
3774
3775 def get_api_data(self):
3775 def get_api_data(self):
3776 status = self
3776 status = self
3777 data = {
3777 data = {
3778 'status_id': status.changeset_status_id,
3778 'status_id': status.changeset_status_id,
3779 'status': status.status,
3779 'status': status.status,
3780 }
3780 }
3781 return data
3781 return data
3782
3782
3783 def __json__(self):
3783 def __json__(self):
3784 data = dict()
3784 data = dict()
3785 data.update(self.get_api_data())
3785 data.update(self.get_api_data())
3786 return data
3786 return data
3787
3787
3788
3788
3789 class _SetState(object):
3789 class _SetState(object):
3790 """
3790 """
3791 Context processor allowing changing state for sensitive operation such as
3791 Context processor allowing changing state for sensitive operation such as
3792 pull request update or merge
3792 pull request update or merge
3793 """
3793 """
3794
3794
3795 def __init__(self, pull_request, pr_state, back_state=None):
3795 def __init__(self, pull_request, pr_state, back_state=None):
3796 self._pr = pull_request
3796 self._pr = pull_request
3797 self._org_state = back_state or pull_request.pull_request_state
3797 self._org_state = back_state or pull_request.pull_request_state
3798 self._pr_state = pr_state
3798 self._pr_state = pr_state
3799
3799
3800 def __enter__(self):
3800 def __enter__(self):
3801 log.debug('StateLock: entering set state context, setting state to: `%s`',
3801 log.debug('StateLock: entering set state context, setting state to: `%s`',
3802 self._pr_state)
3802 self._pr_state)
3803 self._pr.pull_request_state = self._pr_state
3803 self._pr.pull_request_state = self._pr_state
3804 Session().add(self._pr)
3804 Session().add(self._pr)
3805 Session().commit()
3805 Session().commit()
3806
3806
3807 def __exit__(self, exc_type, exc_val, exc_tb):
3807 def __exit__(self, exc_type, exc_val, exc_tb):
3808 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3808 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3809 self._org_state)
3809 self._org_state)
3810 self._pr.pull_request_state = self._org_state
3810 self._pr.pull_request_state = self._org_state
3811 Session().add(self._pr)
3811 Session().add(self._pr)
3812 Session().commit()
3812 Session().commit()
3813
3813
3814
3814
3815 class _PullRequestBase(BaseModel):
3815 class _PullRequestBase(BaseModel):
3816 """
3816 """
3817 Common attributes of pull request and version entries.
3817 Common attributes of pull request and version entries.
3818 """
3818 """
3819
3819
3820 # .status values
3820 # .status values
3821 STATUS_NEW = u'new'
3821 STATUS_NEW = u'new'
3822 STATUS_OPEN = u'open'
3822 STATUS_OPEN = u'open'
3823 STATUS_CLOSED = u'closed'
3823 STATUS_CLOSED = u'closed'
3824
3824
3825 # available states
3825 # available states
3826 STATE_CREATING = u'creating'
3826 STATE_CREATING = u'creating'
3827 STATE_UPDATING = u'updating'
3827 STATE_UPDATING = u'updating'
3828 STATE_MERGING = u'merging'
3828 STATE_MERGING = u'merging'
3829 STATE_CREATED = u'created'
3829 STATE_CREATED = u'created'
3830
3830
3831 title = Column('title', Unicode(255), nullable=True)
3831 title = Column('title', Unicode(255), nullable=True)
3832 description = Column(
3832 description = Column(
3833 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3833 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3834 nullable=True)
3834 nullable=True)
3835 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3835 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3836
3836
3837 # new/open/closed status of pull request (not approve/reject/etc)
3837 # new/open/closed status of pull request (not approve/reject/etc)
3838 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3838 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3839 created_on = Column(
3839 created_on = Column(
3840 'created_on', DateTime(timezone=False), nullable=False,
3840 'created_on', DateTime(timezone=False), nullable=False,
3841 default=datetime.datetime.now)
3841 default=datetime.datetime.now)
3842 updated_on = Column(
3842 updated_on = Column(
3843 'updated_on', DateTime(timezone=False), nullable=False,
3843 'updated_on', DateTime(timezone=False), nullable=False,
3844 default=datetime.datetime.now)
3844 default=datetime.datetime.now)
3845
3845
3846 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3846 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3847
3847
3848 @declared_attr
3848 @declared_attr
3849 def user_id(cls):
3849 def user_id(cls):
3850 return Column(
3850 return Column(
3851 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3851 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3852 unique=None)
3852 unique=None)
3853
3853
3854 # 500 revisions max
3854 # 500 revisions max
3855 _revisions = Column(
3855 _revisions = Column(
3856 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3856 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3857
3857
3858 @declared_attr
3858 @declared_attr
3859 def source_repo_id(cls):
3859 def source_repo_id(cls):
3860 # TODO: dan: rename column to source_repo_id
3860 # TODO: dan: rename column to source_repo_id
3861 return Column(
3861 return Column(
3862 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3862 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3863 nullable=False)
3863 nullable=False)
3864
3864
3865 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3865 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3866
3866
3867 @hybrid_property
3867 @hybrid_property
3868 def source_ref(self):
3868 def source_ref(self):
3869 return self._source_ref
3869 return self._source_ref
3870
3870
3871 @source_ref.setter
3871 @source_ref.setter
3872 def source_ref(self, val):
3872 def source_ref(self, val):
3873 parts = (val or '').split(':')
3873 parts = (val or '').split(':')
3874 if len(parts) != 3:
3874 if len(parts) != 3:
3875 raise ValueError(
3875 raise ValueError(
3876 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3876 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3877 self._source_ref = safe_unicode(val)
3877 self._source_ref = safe_unicode(val)
3878
3878
3879 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3879 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3880
3880
3881 @hybrid_property
3881 @hybrid_property
3882 def target_ref(self):
3882 def target_ref(self):
3883 return self._target_ref
3883 return self._target_ref
3884
3884
3885 @target_ref.setter
3885 @target_ref.setter
3886 def target_ref(self, val):
3886 def target_ref(self, val):
3887 parts = (val or '').split(':')
3887 parts = (val or '').split(':')
3888 if len(parts) != 3:
3888 if len(parts) != 3:
3889 raise ValueError(
3889 raise ValueError(
3890 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3890 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3891 self._target_ref = safe_unicode(val)
3891 self._target_ref = safe_unicode(val)
3892
3892
3893 @declared_attr
3893 @declared_attr
3894 def target_repo_id(cls):
3894 def target_repo_id(cls):
3895 # TODO: dan: rename column to target_repo_id
3895 # TODO: dan: rename column to target_repo_id
3896 return Column(
3896 return Column(
3897 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3897 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3898 nullable=False)
3898 nullable=False)
3899
3899
3900 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3900 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3901
3901
3902 # TODO: dan: rename column to last_merge_source_rev
3902 # TODO: dan: rename column to last_merge_source_rev
3903 _last_merge_source_rev = Column(
3903 _last_merge_source_rev = Column(
3904 'last_merge_org_rev', String(40), nullable=True)
3904 'last_merge_org_rev', String(40), nullable=True)
3905 # TODO: dan: rename column to last_merge_target_rev
3905 # TODO: dan: rename column to last_merge_target_rev
3906 _last_merge_target_rev = Column(
3906 _last_merge_target_rev = Column(
3907 'last_merge_other_rev', String(40), nullable=True)
3907 'last_merge_other_rev', String(40), nullable=True)
3908 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3908 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3909 merge_rev = Column('merge_rev', String(40), nullable=True)
3909 merge_rev = Column('merge_rev', String(40), nullable=True)
3910
3910
3911 reviewer_data = Column(
3911 reviewer_data = Column(
3912 'reviewer_data_json', MutationObj.as_mutable(
3912 'reviewer_data_json', MutationObj.as_mutable(
3913 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3913 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3914
3914
3915 @property
3915 @property
3916 def reviewer_data_json(self):
3916 def reviewer_data_json(self):
3917 return json.dumps(self.reviewer_data)
3917 return json.dumps(self.reviewer_data)
3918
3918
3919 @hybrid_property
3919 @hybrid_property
3920 def description_safe(self):
3920 def description_safe(self):
3921 from rhodecode.lib import helpers as h
3921 from rhodecode.lib import helpers as h
3922 return h.escape(self.description)
3922 return h.escape(self.description)
3923
3923
3924 @hybrid_property
3924 @hybrid_property
3925 def revisions(self):
3925 def revisions(self):
3926 return self._revisions.split(':') if self._revisions else []
3926 return self._revisions.split(':') if self._revisions else []
3927
3927
3928 @revisions.setter
3928 @revisions.setter
3929 def revisions(self, val):
3929 def revisions(self, val):
3930 self._revisions = ':'.join(val)
3930 self._revisions = ':'.join(val)
3931
3931
3932 @hybrid_property
3932 @hybrid_property
3933 def last_merge_status(self):
3933 def last_merge_status(self):
3934 return safe_int(self._last_merge_status)
3934 return safe_int(self._last_merge_status)
3935
3935
3936 @last_merge_status.setter
3936 @last_merge_status.setter
3937 def last_merge_status(self, val):
3937 def last_merge_status(self, val):
3938 self._last_merge_status = val
3938 self._last_merge_status = val
3939
3939
3940 @declared_attr
3940 @declared_attr
3941 def author(cls):
3941 def author(cls):
3942 return relationship('User', lazy='joined')
3942 return relationship('User', lazy='joined')
3943
3943
3944 @declared_attr
3944 @declared_attr
3945 def source_repo(cls):
3945 def source_repo(cls):
3946 return relationship(
3946 return relationship(
3947 'Repository',
3947 'Repository',
3948 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3948 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3949
3949
3950 @property
3950 @property
3951 def source_ref_parts(self):
3951 def source_ref_parts(self):
3952 return self.unicode_to_reference(self.source_ref)
3952 return self.unicode_to_reference(self.source_ref)
3953
3953
3954 @declared_attr
3954 @declared_attr
3955 def target_repo(cls):
3955 def target_repo(cls):
3956 return relationship(
3956 return relationship(
3957 'Repository',
3957 'Repository',
3958 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3958 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3959
3959
3960 @property
3960 @property
3961 def target_ref_parts(self):
3961 def target_ref_parts(self):
3962 return self.unicode_to_reference(self.target_ref)
3962 return self.unicode_to_reference(self.target_ref)
3963
3963
3964 @property
3964 @property
3965 def shadow_merge_ref(self):
3965 def shadow_merge_ref(self):
3966 return self.unicode_to_reference(self._shadow_merge_ref)
3966 return self.unicode_to_reference(self._shadow_merge_ref)
3967
3967
3968 @shadow_merge_ref.setter
3968 @shadow_merge_ref.setter
3969 def shadow_merge_ref(self, ref):
3969 def shadow_merge_ref(self, ref):
3970 self._shadow_merge_ref = self.reference_to_unicode(ref)
3970 self._shadow_merge_ref = self.reference_to_unicode(ref)
3971
3971
3972 @staticmethod
3972 @staticmethod
3973 def unicode_to_reference(raw):
3973 def unicode_to_reference(raw):
3974 """
3974 """
3975 Convert a unicode (or string) to a reference object.
3975 Convert a unicode (or string) to a reference object.
3976 If unicode evaluates to False it returns None.
3976 If unicode evaluates to False it returns None.
3977 """
3977 """
3978 if raw:
3978 if raw:
3979 refs = raw.split(':')
3979 refs = raw.split(':')
3980 return Reference(*refs)
3980 return Reference(*refs)
3981 else:
3981 else:
3982 return None
3982 return None
3983
3983
3984 @staticmethod
3984 @staticmethod
3985 def reference_to_unicode(ref):
3985 def reference_to_unicode(ref):
3986 """
3986 """
3987 Convert a reference object to unicode.
3987 Convert a reference object to unicode.
3988 If reference is None it returns None.
3988 If reference is None it returns None.
3989 """
3989 """
3990 if ref:
3990 if ref:
3991 return u':'.join(ref)
3991 return u':'.join(ref)
3992 else:
3992 else:
3993 return None
3993 return None
3994
3994
3995 def get_api_data(self, with_merge_state=True):
3995 def get_api_data(self, with_merge_state=True):
3996 from rhodecode.model.pull_request import PullRequestModel
3996 from rhodecode.model.pull_request import PullRequestModel
3997
3997
3998 pull_request = self
3998 pull_request = self
3999 if with_merge_state:
3999 if with_merge_state:
4000 merge_status = PullRequestModel().merge_status(pull_request)
4000 merge_status = PullRequestModel().merge_status(pull_request)
4001 merge_state = {
4001 merge_state = {
4002 'status': merge_status[0],
4002 'status': merge_status[0],
4003 'message': safe_unicode(merge_status[1]),
4003 'message': safe_unicode(merge_status[1]),
4004 }
4004 }
4005 else:
4005 else:
4006 merge_state = {'status': 'not_available',
4006 merge_state = {'status': 'not_available',
4007 'message': 'not_available'}
4007 'message': 'not_available'}
4008
4008
4009 merge_data = {
4009 merge_data = {
4010 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4010 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4011 'reference': (
4011 'reference': (
4012 pull_request.shadow_merge_ref._asdict()
4012 pull_request.shadow_merge_ref._asdict()
4013 if pull_request.shadow_merge_ref else None),
4013 if pull_request.shadow_merge_ref else None),
4014 }
4014 }
4015
4015
4016 data = {
4016 data = {
4017 'pull_request_id': pull_request.pull_request_id,
4017 'pull_request_id': pull_request.pull_request_id,
4018 'url': PullRequestModel().get_url(pull_request),
4018 'url': PullRequestModel().get_url(pull_request),
4019 'title': pull_request.title,
4019 'title': pull_request.title,
4020 'description': pull_request.description,
4020 'description': pull_request.description,
4021 'status': pull_request.status,
4021 'status': pull_request.status,
4022 'state': pull_request.pull_request_state,
4022 'state': pull_request.pull_request_state,
4023 'created_on': pull_request.created_on,
4023 'created_on': pull_request.created_on,
4024 'updated_on': pull_request.updated_on,
4024 'updated_on': pull_request.updated_on,
4025 'commit_ids': pull_request.revisions,
4025 'commit_ids': pull_request.revisions,
4026 'review_status': pull_request.calculated_review_status(),
4026 'review_status': pull_request.calculated_review_status(),
4027 'mergeable': merge_state,
4027 'mergeable': merge_state,
4028 'source': {
4028 'source': {
4029 'clone_url': pull_request.source_repo.clone_url(),
4029 'clone_url': pull_request.source_repo.clone_url(),
4030 'repository': pull_request.source_repo.repo_name,
4030 'repository': pull_request.source_repo.repo_name,
4031 'reference': {
4031 'reference': {
4032 'name': pull_request.source_ref_parts.name,
4032 'name': pull_request.source_ref_parts.name,
4033 'type': pull_request.source_ref_parts.type,
4033 'type': pull_request.source_ref_parts.type,
4034 'commit_id': pull_request.source_ref_parts.commit_id,
4034 'commit_id': pull_request.source_ref_parts.commit_id,
4035 },
4035 },
4036 },
4036 },
4037 'target': {
4037 'target': {
4038 'clone_url': pull_request.target_repo.clone_url(),
4038 'clone_url': pull_request.target_repo.clone_url(),
4039 'repository': pull_request.target_repo.repo_name,
4039 'repository': pull_request.target_repo.repo_name,
4040 'reference': {
4040 'reference': {
4041 'name': pull_request.target_ref_parts.name,
4041 'name': pull_request.target_ref_parts.name,
4042 'type': pull_request.target_ref_parts.type,
4042 'type': pull_request.target_ref_parts.type,
4043 'commit_id': pull_request.target_ref_parts.commit_id,
4043 'commit_id': pull_request.target_ref_parts.commit_id,
4044 },
4044 },
4045 },
4045 },
4046 'merge': merge_data,
4046 'merge': merge_data,
4047 'author': pull_request.author.get_api_data(include_secrets=False,
4047 'author': pull_request.author.get_api_data(include_secrets=False,
4048 details='basic'),
4048 details='basic'),
4049 'reviewers': [
4049 'reviewers': [
4050 {
4050 {
4051 'user': reviewer.get_api_data(include_secrets=False,
4051 'user': reviewer.get_api_data(include_secrets=False,
4052 details='basic'),
4052 details='basic'),
4053 'reasons': reasons,
4053 'reasons': reasons,
4054 'review_status': st[0][1].status if st else 'not_reviewed',
4054 'review_status': st[0][1].status if st else 'not_reviewed',
4055 }
4055 }
4056 for obj, reviewer, reasons, mandatory, st in
4056 for obj, reviewer, reasons, mandatory, st in
4057 pull_request.reviewers_statuses()
4057 pull_request.reviewers_statuses()
4058 ]
4058 ]
4059 }
4059 }
4060
4060
4061 return data
4061 return data
4062
4062
4063 def set_state(self, pull_request_state, final_state=None):
4063 def set_state(self, pull_request_state, final_state=None):
4064 """
4064 """
4065 # goes from initial state to updating to initial state.
4065 # goes from initial state to updating to initial state.
4066 # initial state can be changed by specifying back_state=
4066 # initial state can be changed by specifying back_state=
4067 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4067 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4068 pull_request.merge()
4068 pull_request.merge()
4069
4069
4070 :param pull_request_state:
4070 :param pull_request_state:
4071 :param final_state:
4071 :param final_state:
4072
4072
4073 """
4073 """
4074
4074
4075 return _SetState(self, pull_request_state, back_state=final_state)
4075 return _SetState(self, pull_request_state, back_state=final_state)
4076
4076
4077
4077
4078 class PullRequest(Base, _PullRequestBase):
4078 class PullRequest(Base, _PullRequestBase):
4079 __tablename__ = 'pull_requests'
4079 __tablename__ = 'pull_requests'
4080 __table_args__ = (
4080 __table_args__ = (
4081 base_table_args,
4081 base_table_args,
4082 )
4082 )
4083
4083
4084 pull_request_id = Column(
4084 pull_request_id = Column(
4085 'pull_request_id', Integer(), nullable=False, primary_key=True)
4085 'pull_request_id', Integer(), nullable=False, primary_key=True)
4086
4086
4087 def __repr__(self):
4087 def __repr__(self):
4088 if self.pull_request_id:
4088 if self.pull_request_id:
4089 return '<DB:PullRequest #%s>' % self.pull_request_id
4089 return '<DB:PullRequest #%s>' % self.pull_request_id
4090 else:
4090 else:
4091 return '<DB:PullRequest at %#x>' % id(self)
4091 return '<DB:PullRequest at %#x>' % id(self)
4092
4092
4093 reviewers = relationship('PullRequestReviewers',
4093 reviewers = relationship('PullRequestReviewers',
4094 cascade="all, delete, delete-orphan")
4094 cascade="all, delete, delete-orphan")
4095 statuses = relationship('ChangesetStatus',
4095 statuses = relationship('ChangesetStatus',
4096 cascade="all, delete, delete-orphan")
4096 cascade="all, delete, delete-orphan")
4097 comments = relationship('ChangesetComment',
4097 comments = relationship('ChangesetComment',
4098 cascade="all, delete, delete-orphan")
4098 cascade="all, delete, delete-orphan")
4099 versions = relationship('PullRequestVersion',
4099 versions = relationship('PullRequestVersion',
4100 cascade="all, delete, delete-orphan",
4100 cascade="all, delete, delete-orphan",
4101 lazy='dynamic')
4101 lazy='dynamic')
4102
4102
4103 @classmethod
4103 @classmethod
4104 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4104 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4105 internal_methods=None):
4105 internal_methods=None):
4106
4106
4107 class PullRequestDisplay(object):
4107 class PullRequestDisplay(object):
4108 """
4108 """
4109 Special object wrapper for showing PullRequest data via Versions
4109 Special object wrapper for showing PullRequest data via Versions
4110 It mimics PR object as close as possible. This is read only object
4110 It mimics PR object as close as possible. This is read only object
4111 just for display
4111 just for display
4112 """
4112 """
4113
4113
4114 def __init__(self, attrs, internal=None):
4114 def __init__(self, attrs, internal=None):
4115 self.attrs = attrs
4115 self.attrs = attrs
4116 # internal have priority over the given ones via attrs
4116 # internal have priority over the given ones via attrs
4117 self.internal = internal or ['versions']
4117 self.internal = internal or ['versions']
4118
4118
4119 def __getattr__(self, item):
4119 def __getattr__(self, item):
4120 if item in self.internal:
4120 if item in self.internal:
4121 return getattr(self, item)
4121 return getattr(self, item)
4122 try:
4122 try:
4123 return self.attrs[item]
4123 return self.attrs[item]
4124 except KeyError:
4124 except KeyError:
4125 raise AttributeError(
4125 raise AttributeError(
4126 '%s object has no attribute %s' % (self, item))
4126 '%s object has no attribute %s' % (self, item))
4127
4127
4128 def __repr__(self):
4128 def __repr__(self):
4129 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
4129 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
4130
4130
4131 def versions(self):
4131 def versions(self):
4132 return pull_request_obj.versions.order_by(
4132 return pull_request_obj.versions.order_by(
4133 PullRequestVersion.pull_request_version_id).all()
4133 PullRequestVersion.pull_request_version_id).all()
4134
4134
4135 def is_closed(self):
4135 def is_closed(self):
4136 return pull_request_obj.is_closed()
4136 return pull_request_obj.is_closed()
4137
4137
4138 @property
4138 @property
4139 def pull_request_version_id(self):
4139 def pull_request_version_id(self):
4140 return getattr(pull_request_obj, 'pull_request_version_id', None)
4140 return getattr(pull_request_obj, 'pull_request_version_id', None)
4141
4141
4142 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4142 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4143
4143
4144 attrs.author = StrictAttributeDict(
4144 attrs.author = StrictAttributeDict(
4145 pull_request_obj.author.get_api_data())
4145 pull_request_obj.author.get_api_data())
4146 if pull_request_obj.target_repo:
4146 if pull_request_obj.target_repo:
4147 attrs.target_repo = StrictAttributeDict(
4147 attrs.target_repo = StrictAttributeDict(
4148 pull_request_obj.target_repo.get_api_data())
4148 pull_request_obj.target_repo.get_api_data())
4149 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4149 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4150
4150
4151 if pull_request_obj.source_repo:
4151 if pull_request_obj.source_repo:
4152 attrs.source_repo = StrictAttributeDict(
4152 attrs.source_repo = StrictAttributeDict(
4153 pull_request_obj.source_repo.get_api_data())
4153 pull_request_obj.source_repo.get_api_data())
4154 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4154 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4155
4155
4156 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4156 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4157 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4157 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4158 attrs.revisions = pull_request_obj.revisions
4158 attrs.revisions = pull_request_obj.revisions
4159
4159
4160 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4160 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4161 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4161 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4162 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4162 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4163
4163
4164 return PullRequestDisplay(attrs, internal=internal_methods)
4164 return PullRequestDisplay(attrs, internal=internal_methods)
4165
4165
4166 def is_closed(self):
4166 def is_closed(self):
4167 return self.status == self.STATUS_CLOSED
4167 return self.status == self.STATUS_CLOSED
4168
4168
4169 def __json__(self):
4169 def __json__(self):
4170 return {
4170 return {
4171 'revisions': self.revisions,
4171 'revisions': self.revisions,
4172 }
4172 }
4173
4173
4174 def calculated_review_status(self):
4174 def calculated_review_status(self):
4175 from rhodecode.model.changeset_status import ChangesetStatusModel
4175 from rhodecode.model.changeset_status import ChangesetStatusModel
4176 return ChangesetStatusModel().calculated_review_status(self)
4176 return ChangesetStatusModel().calculated_review_status(self)
4177
4177
4178 def reviewers_statuses(self):
4178 def reviewers_statuses(self):
4179 from rhodecode.model.changeset_status import ChangesetStatusModel
4179 from rhodecode.model.changeset_status import ChangesetStatusModel
4180 return ChangesetStatusModel().reviewers_statuses(self)
4180 return ChangesetStatusModel().reviewers_statuses(self)
4181
4181
4182 @property
4182 @property
4183 def workspace_id(self):
4183 def workspace_id(self):
4184 from rhodecode.model.pull_request import PullRequestModel
4184 from rhodecode.model.pull_request import PullRequestModel
4185 return PullRequestModel()._workspace_id(self)
4185 return PullRequestModel()._workspace_id(self)
4186
4186
4187 def get_shadow_repo(self):
4187 def get_shadow_repo(self):
4188 workspace_id = self.workspace_id
4188 workspace_id = self.workspace_id
4189 vcs_obj = self.target_repo.scm_instance()
4189 vcs_obj = self.target_repo.scm_instance()
4190 shadow_repository_path = vcs_obj._get_shadow_repository_path(
4190 shadow_repository_path = vcs_obj._get_shadow_repository_path(
4191 self.target_repo.repo_id, workspace_id)
4191 self.target_repo.repo_id, workspace_id)
4192 if os.path.isdir(shadow_repository_path):
4192 if os.path.isdir(shadow_repository_path):
4193 return vcs_obj.get_shadow_instance(shadow_repository_path)
4193 return vcs_obj.get_shadow_instance(shadow_repository_path)
4194
4194
4195
4195
4196 class PullRequestVersion(Base, _PullRequestBase):
4196 class PullRequestVersion(Base, _PullRequestBase):
4197 __tablename__ = 'pull_request_versions'
4197 __tablename__ = 'pull_request_versions'
4198 __table_args__ = (
4198 __table_args__ = (
4199 base_table_args,
4199 base_table_args,
4200 )
4200 )
4201
4201
4202 pull_request_version_id = Column(
4202 pull_request_version_id = Column(
4203 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
4203 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
4204 pull_request_id = Column(
4204 pull_request_id = Column(
4205 'pull_request_id', Integer(),
4205 'pull_request_id', Integer(),
4206 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4206 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4207 pull_request = relationship('PullRequest')
4207 pull_request = relationship('PullRequest')
4208
4208
4209 def __repr__(self):
4209 def __repr__(self):
4210 if self.pull_request_version_id:
4210 if self.pull_request_version_id:
4211 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4211 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4212 else:
4212 else:
4213 return '<DB:PullRequestVersion at %#x>' % id(self)
4213 return '<DB:PullRequestVersion at %#x>' % id(self)
4214
4214
4215 @property
4215 @property
4216 def reviewers(self):
4216 def reviewers(self):
4217 return self.pull_request.reviewers
4217 return self.pull_request.reviewers
4218
4218
4219 @property
4219 @property
4220 def versions(self):
4220 def versions(self):
4221 return self.pull_request.versions
4221 return self.pull_request.versions
4222
4222
4223 def is_closed(self):
4223 def is_closed(self):
4224 # calculate from original
4224 # calculate from original
4225 return self.pull_request.status == self.STATUS_CLOSED
4225 return self.pull_request.status == self.STATUS_CLOSED
4226
4226
4227 def calculated_review_status(self):
4227 def calculated_review_status(self):
4228 return self.pull_request.calculated_review_status()
4228 return self.pull_request.calculated_review_status()
4229
4229
4230 def reviewers_statuses(self):
4230 def reviewers_statuses(self):
4231 return self.pull_request.reviewers_statuses()
4231 return self.pull_request.reviewers_statuses()
4232
4232
4233
4233
4234 class PullRequestReviewers(Base, BaseModel):
4234 class PullRequestReviewers(Base, BaseModel):
4235 __tablename__ = 'pull_request_reviewers'
4235 __tablename__ = 'pull_request_reviewers'
4236 __table_args__ = (
4236 __table_args__ = (
4237 base_table_args,
4237 base_table_args,
4238 )
4238 )
4239
4239
4240 @hybrid_property
4240 @hybrid_property
4241 def reasons(self):
4241 def reasons(self):
4242 if not self._reasons:
4242 if not self._reasons:
4243 return []
4243 return []
4244 return self._reasons
4244 return self._reasons
4245
4245
4246 @reasons.setter
4246 @reasons.setter
4247 def reasons(self, val):
4247 def reasons(self, val):
4248 val = val or []
4248 val = val or []
4249 if any(not isinstance(x, compat.string_types) for x in val):
4249 if any(not isinstance(x, compat.string_types) for x in val):
4250 raise Exception('invalid reasons type, must be list of strings')
4250 raise Exception('invalid reasons type, must be list of strings')
4251 self._reasons = val
4251 self._reasons = val
4252
4252
4253 pull_requests_reviewers_id = Column(
4253 pull_requests_reviewers_id = Column(
4254 'pull_requests_reviewers_id', Integer(), nullable=False,
4254 'pull_requests_reviewers_id', Integer(), nullable=False,
4255 primary_key=True)
4255 primary_key=True)
4256 pull_request_id = Column(
4256 pull_request_id = Column(
4257 "pull_request_id", Integer(),
4257 "pull_request_id", Integer(),
4258 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4258 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4259 user_id = Column(
4259 user_id = Column(
4260 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4260 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4261 _reasons = Column(
4261 _reasons = Column(
4262 'reason', MutationList.as_mutable(
4262 'reason', MutationList.as_mutable(
4263 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4263 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4264
4264
4265 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4265 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4266 user = relationship('User')
4266 user = relationship('User')
4267 pull_request = relationship('PullRequest')
4267 pull_request = relationship('PullRequest')
4268
4268
4269 rule_data = Column(
4269 rule_data = Column(
4270 'rule_data_json',
4270 'rule_data_json',
4271 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4271 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4272
4272
4273 def rule_user_group_data(self):
4273 def rule_user_group_data(self):
4274 """
4274 """
4275 Returns the voting user group rule data for this reviewer
4275 Returns the voting user group rule data for this reviewer
4276 """
4276 """
4277
4277
4278 if self.rule_data and 'vote_rule' in self.rule_data:
4278 if self.rule_data and 'vote_rule' in self.rule_data:
4279 user_group_data = {}
4279 user_group_data = {}
4280 if 'rule_user_group_entry_id' in self.rule_data:
4280 if 'rule_user_group_entry_id' in self.rule_data:
4281 # means a group with voting rules !
4281 # means a group with voting rules !
4282 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4282 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4283 user_group_data['name'] = self.rule_data['rule_name']
4283 user_group_data['name'] = self.rule_data['rule_name']
4284 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4284 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4285
4285
4286 return user_group_data
4286 return user_group_data
4287
4287
4288 def __unicode__(self):
4288 def __unicode__(self):
4289 return u"<%s('id:%s')>" % (self.__class__.__name__,
4289 return u"<%s('id:%s')>" % (self.__class__.__name__,
4290 self.pull_requests_reviewers_id)
4290 self.pull_requests_reviewers_id)
4291
4291
4292
4292
4293 class Notification(Base, BaseModel):
4293 class Notification(Base, BaseModel):
4294 __tablename__ = 'notifications'
4294 __tablename__ = 'notifications'
4295 __table_args__ = (
4295 __table_args__ = (
4296 Index('notification_type_idx', 'type'),
4296 Index('notification_type_idx', 'type'),
4297 base_table_args,
4297 base_table_args,
4298 )
4298 )
4299
4299
4300 TYPE_CHANGESET_COMMENT = u'cs_comment'
4300 TYPE_CHANGESET_COMMENT = u'cs_comment'
4301 TYPE_MESSAGE = u'message'
4301 TYPE_MESSAGE = u'message'
4302 TYPE_MENTION = u'mention'
4302 TYPE_MENTION = u'mention'
4303 TYPE_REGISTRATION = u'registration'
4303 TYPE_REGISTRATION = u'registration'
4304 TYPE_PULL_REQUEST = u'pull_request'
4304 TYPE_PULL_REQUEST = u'pull_request'
4305 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4305 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4306
4306
4307 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4307 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4308 subject = Column('subject', Unicode(512), nullable=True)
4308 subject = Column('subject', Unicode(512), nullable=True)
4309 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4309 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4310 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4310 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4311 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4311 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4312 type_ = Column('type', Unicode(255))
4312 type_ = Column('type', Unicode(255))
4313
4313
4314 created_by_user = relationship('User')
4314 created_by_user = relationship('User')
4315 notifications_to_users = relationship('UserNotification', lazy='joined',
4315 notifications_to_users = relationship('UserNotification', lazy='joined',
4316 cascade="all, delete, delete-orphan")
4316 cascade="all, delete, delete-orphan")
4317
4317
4318 @property
4318 @property
4319 def recipients(self):
4319 def recipients(self):
4320 return [x.user for x in UserNotification.query()\
4320 return [x.user for x in UserNotification.query()\
4321 .filter(UserNotification.notification == self)\
4321 .filter(UserNotification.notification == self)\
4322 .order_by(UserNotification.user_id.asc()).all()]
4322 .order_by(UserNotification.user_id.asc()).all()]
4323
4323
4324 @classmethod
4324 @classmethod
4325 def create(cls, created_by, subject, body, recipients, type_=None):
4325 def create(cls, created_by, subject, body, recipients, type_=None):
4326 if type_ is None:
4326 if type_ is None:
4327 type_ = Notification.TYPE_MESSAGE
4327 type_ = Notification.TYPE_MESSAGE
4328
4328
4329 notification = cls()
4329 notification = cls()
4330 notification.created_by_user = created_by
4330 notification.created_by_user = created_by
4331 notification.subject = subject
4331 notification.subject = subject
4332 notification.body = body
4332 notification.body = body
4333 notification.type_ = type_
4333 notification.type_ = type_
4334 notification.created_on = datetime.datetime.now()
4334 notification.created_on = datetime.datetime.now()
4335
4335
4336 # For each recipient link the created notification to his account
4336 # For each recipient link the created notification to his account
4337 for u in recipients:
4337 for u in recipients:
4338 assoc = UserNotification()
4338 assoc = UserNotification()
4339 assoc.user_id = u.user_id
4339 assoc.user_id = u.user_id
4340 assoc.notification = notification
4340 assoc.notification = notification
4341
4341
4342 # if created_by is inside recipients mark his notification
4342 # if created_by is inside recipients mark his notification
4343 # as read
4343 # as read
4344 if u.user_id == created_by.user_id:
4344 if u.user_id == created_by.user_id:
4345 assoc.read = True
4345 assoc.read = True
4346 Session().add(assoc)
4346 Session().add(assoc)
4347
4347
4348 Session().add(notification)
4348 Session().add(notification)
4349
4349
4350 return notification
4350 return notification
4351
4351
4352
4352
4353 class UserNotification(Base, BaseModel):
4353 class UserNotification(Base, BaseModel):
4354 __tablename__ = 'user_to_notification'
4354 __tablename__ = 'user_to_notification'
4355 __table_args__ = (
4355 __table_args__ = (
4356 UniqueConstraint('user_id', 'notification_id'),
4356 UniqueConstraint('user_id', 'notification_id'),
4357 base_table_args
4357 base_table_args
4358 )
4358 )
4359
4359
4360 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4360 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4361 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4361 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4362 read = Column('read', Boolean, default=False)
4362 read = Column('read', Boolean, default=False)
4363 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4363 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4364
4364
4365 user = relationship('User', lazy="joined")
4365 user = relationship('User', lazy="joined")
4366 notification = relationship('Notification', lazy="joined",
4366 notification = relationship('Notification', lazy="joined",
4367 order_by=lambda: Notification.created_on.desc(),)
4367 order_by=lambda: Notification.created_on.desc(),)
4368
4368
4369 def mark_as_read(self):
4369 def mark_as_read(self):
4370 self.read = True
4370 self.read = True
4371 Session().add(self)
4371 Session().add(self)
4372
4372
4373
4373
4374 class Gist(Base, BaseModel):
4374 class Gist(Base, BaseModel):
4375 __tablename__ = 'gists'
4375 __tablename__ = 'gists'
4376 __table_args__ = (
4376 __table_args__ = (
4377 Index('g_gist_access_id_idx', 'gist_access_id'),
4377 Index('g_gist_access_id_idx', 'gist_access_id'),
4378 Index('g_created_on_idx', 'created_on'),
4378 Index('g_created_on_idx', 'created_on'),
4379 base_table_args
4379 base_table_args
4380 )
4380 )
4381
4381
4382 GIST_PUBLIC = u'public'
4382 GIST_PUBLIC = u'public'
4383 GIST_PRIVATE = u'private'
4383 GIST_PRIVATE = u'private'
4384 DEFAULT_FILENAME = u'gistfile1.txt'
4384 DEFAULT_FILENAME = u'gistfile1.txt'
4385
4385
4386 ACL_LEVEL_PUBLIC = u'acl_public'
4386 ACL_LEVEL_PUBLIC = u'acl_public'
4387 ACL_LEVEL_PRIVATE = u'acl_private'
4387 ACL_LEVEL_PRIVATE = u'acl_private'
4388
4388
4389 gist_id = Column('gist_id', Integer(), primary_key=True)
4389 gist_id = Column('gist_id', Integer(), primary_key=True)
4390 gist_access_id = Column('gist_access_id', Unicode(250))
4390 gist_access_id = Column('gist_access_id', Unicode(250))
4391 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4391 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4392 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4392 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4393 gist_expires = Column('gist_expires', Float(53), nullable=False)
4393 gist_expires = Column('gist_expires', Float(53), nullable=False)
4394 gist_type = Column('gist_type', Unicode(128), nullable=False)
4394 gist_type = Column('gist_type', Unicode(128), nullable=False)
4395 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4395 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4396 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4396 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4397 acl_level = Column('acl_level', Unicode(128), nullable=True)
4397 acl_level = Column('acl_level', Unicode(128), nullable=True)
4398
4398
4399 owner = relationship('User')
4399 owner = relationship('User')
4400
4400
4401 def __repr__(self):
4401 def __repr__(self):
4402 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4402 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4403
4403
4404 @hybrid_property
4404 @hybrid_property
4405 def description_safe(self):
4405 def description_safe(self):
4406 from rhodecode.lib import helpers as h
4406 from rhodecode.lib import helpers as h
4407 return h.escape(self.gist_description)
4407 return h.escape(self.gist_description)
4408
4408
4409 @classmethod
4409 @classmethod
4410 def get_or_404(cls, id_):
4410 def get_or_404(cls, id_):
4411 from pyramid.httpexceptions import HTTPNotFound
4411 from pyramid.httpexceptions import HTTPNotFound
4412
4412
4413 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4413 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4414 if not res:
4414 if not res:
4415 raise HTTPNotFound()
4415 raise HTTPNotFound()
4416 return res
4416 return res
4417
4417
4418 @classmethod
4418 @classmethod
4419 def get_by_access_id(cls, gist_access_id):
4419 def get_by_access_id(cls, gist_access_id):
4420 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4420 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4421
4421
4422 def gist_url(self):
4422 def gist_url(self):
4423 from rhodecode.model.gist import GistModel
4423 from rhodecode.model.gist import GistModel
4424 return GistModel().get_url(self)
4424 return GistModel().get_url(self)
4425
4425
4426 @classmethod
4426 @classmethod
4427 def base_path(cls):
4427 def base_path(cls):
4428 """
4428 """
4429 Returns base path when all gists are stored
4429 Returns base path when all gists are stored
4430
4430
4431 :param cls:
4431 :param cls:
4432 """
4432 """
4433 from rhodecode.model.gist import GIST_STORE_LOC
4433 from rhodecode.model.gist import GIST_STORE_LOC
4434 q = Session().query(RhodeCodeUi)\
4434 q = Session().query(RhodeCodeUi)\
4435 .filter(RhodeCodeUi.ui_key == URL_SEP)
4435 .filter(RhodeCodeUi.ui_key == URL_SEP)
4436 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4436 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4437 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4437 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4438
4438
4439 def get_api_data(self):
4439 def get_api_data(self):
4440 """
4440 """
4441 Common function for generating gist related data for API
4441 Common function for generating gist related data for API
4442 """
4442 """
4443 gist = self
4443 gist = self
4444 data = {
4444 data = {
4445 'gist_id': gist.gist_id,
4445 'gist_id': gist.gist_id,
4446 'type': gist.gist_type,
4446 'type': gist.gist_type,
4447 'access_id': gist.gist_access_id,
4447 'access_id': gist.gist_access_id,
4448 'description': gist.gist_description,
4448 'description': gist.gist_description,
4449 'url': gist.gist_url(),
4449 'url': gist.gist_url(),
4450 'expires': gist.gist_expires,
4450 'expires': gist.gist_expires,
4451 'created_on': gist.created_on,
4451 'created_on': gist.created_on,
4452 'modified_at': gist.modified_at,
4452 'modified_at': gist.modified_at,
4453 'content': None,
4453 'content': None,
4454 'acl_level': gist.acl_level,
4454 'acl_level': gist.acl_level,
4455 }
4455 }
4456 return data
4456 return data
4457
4457
4458 def __json__(self):
4458 def __json__(self):
4459 data = dict(
4459 data = dict(
4460 )
4460 )
4461 data.update(self.get_api_data())
4461 data.update(self.get_api_data())
4462 return data
4462 return data
4463 # SCM functions
4463 # SCM functions
4464
4464
4465 def scm_instance(self, **kwargs):
4465 def scm_instance(self, **kwargs):
4466 """
4466 """
4467 Get an instance of VCS Repository
4467 Get an instance of VCS Repository
4468
4468
4469 :param kwargs:
4469 :param kwargs:
4470 """
4470 """
4471 from rhodecode.model.gist import GistModel
4471 from rhodecode.model.gist import GistModel
4472 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4472 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4473 return get_vcs_instance(
4473 return get_vcs_instance(
4474 repo_path=safe_str(full_repo_path), create=False,
4474 repo_path=safe_str(full_repo_path), create=False,
4475 _vcs_alias=GistModel.vcs_backend)
4475 _vcs_alias=GistModel.vcs_backend)
4476
4476
4477
4477
4478 class ExternalIdentity(Base, BaseModel):
4478 class ExternalIdentity(Base, BaseModel):
4479 __tablename__ = 'external_identities'
4479 __tablename__ = 'external_identities'
4480 __table_args__ = (
4480 __table_args__ = (
4481 Index('local_user_id_idx', 'local_user_id'),
4481 Index('local_user_id_idx', 'local_user_id'),
4482 Index('external_id_idx', 'external_id'),
4482 Index('external_id_idx', 'external_id'),
4483 base_table_args
4483 base_table_args
4484 )
4484 )
4485
4485
4486 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4486 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4487 external_username = Column('external_username', Unicode(1024), default=u'')
4487 external_username = Column('external_username', Unicode(1024), default=u'')
4488 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4488 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4489 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4489 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4490 access_token = Column('access_token', String(1024), default=u'')
4490 access_token = Column('access_token', String(1024), default=u'')
4491 alt_token = Column('alt_token', String(1024), default=u'')
4491 alt_token = Column('alt_token', String(1024), default=u'')
4492 token_secret = Column('token_secret', String(1024), default=u'')
4492 token_secret = Column('token_secret', String(1024), default=u'')
4493
4493
4494 @classmethod
4494 @classmethod
4495 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4495 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4496 """
4496 """
4497 Returns ExternalIdentity instance based on search params
4497 Returns ExternalIdentity instance based on search params
4498
4498
4499 :param external_id:
4499 :param external_id:
4500 :param provider_name:
4500 :param provider_name:
4501 :return: ExternalIdentity
4501 :return: ExternalIdentity
4502 """
4502 """
4503 query = cls.query()
4503 query = cls.query()
4504 query = query.filter(cls.external_id == external_id)
4504 query = query.filter(cls.external_id == external_id)
4505 query = query.filter(cls.provider_name == provider_name)
4505 query = query.filter(cls.provider_name == provider_name)
4506 if local_user_id:
4506 if local_user_id:
4507 query = query.filter(cls.local_user_id == local_user_id)
4507 query = query.filter(cls.local_user_id == local_user_id)
4508 return query.first()
4508 return query.first()
4509
4509
4510 @classmethod
4510 @classmethod
4511 def user_by_external_id_and_provider(cls, external_id, provider_name):
4511 def user_by_external_id_and_provider(cls, external_id, provider_name):
4512 """
4512 """
4513 Returns User instance based on search params
4513 Returns User instance based on search params
4514
4514
4515 :param external_id:
4515 :param external_id:
4516 :param provider_name:
4516 :param provider_name:
4517 :return: User
4517 :return: User
4518 """
4518 """
4519 query = User.query()
4519 query = User.query()
4520 query = query.filter(cls.external_id == external_id)
4520 query = query.filter(cls.external_id == external_id)
4521 query = query.filter(cls.provider_name == provider_name)
4521 query = query.filter(cls.provider_name == provider_name)
4522 query = query.filter(User.user_id == cls.local_user_id)
4522 query = query.filter(User.user_id == cls.local_user_id)
4523 return query.first()
4523 return query.first()
4524
4524
4525 @classmethod
4525 @classmethod
4526 def by_local_user_id(cls, local_user_id):
4526 def by_local_user_id(cls, local_user_id):
4527 """
4527 """
4528 Returns all tokens for user
4528 Returns all tokens for user
4529
4529
4530 :param local_user_id:
4530 :param local_user_id:
4531 :return: ExternalIdentity
4531 :return: ExternalIdentity
4532 """
4532 """
4533 query = cls.query()
4533 query = cls.query()
4534 query = query.filter(cls.local_user_id == local_user_id)
4534 query = query.filter(cls.local_user_id == local_user_id)
4535 return query
4535 return query
4536
4536
4537 @classmethod
4537 @classmethod
4538 def load_provider_plugin(cls, plugin_id):
4538 def load_provider_plugin(cls, plugin_id):
4539 from rhodecode.authentication.base import loadplugin
4539 from rhodecode.authentication.base import loadplugin
4540 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4540 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4541 auth_plugin = loadplugin(_plugin_id)
4541 auth_plugin = loadplugin(_plugin_id)
4542 return auth_plugin
4542 return auth_plugin
4543
4543
4544
4544
4545 class Integration(Base, BaseModel):
4545 class Integration(Base, BaseModel):
4546 __tablename__ = 'integrations'
4546 __tablename__ = 'integrations'
4547 __table_args__ = (
4547 __table_args__ = (
4548 base_table_args
4548 base_table_args
4549 )
4549 )
4550
4550
4551 integration_id = Column('integration_id', Integer(), primary_key=True)
4551 integration_id = Column('integration_id', Integer(), primary_key=True)
4552 integration_type = Column('integration_type', String(255))
4552 integration_type = Column('integration_type', String(255))
4553 enabled = Column('enabled', Boolean(), nullable=False)
4553 enabled = Column('enabled', Boolean(), nullable=False)
4554 name = Column('name', String(255), nullable=False)
4554 name = Column('name', String(255), nullable=False)
4555 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4555 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4556 default=False)
4556 default=False)
4557
4557
4558 settings = Column(
4558 settings = Column(
4559 'settings_json', MutationObj.as_mutable(
4559 'settings_json', MutationObj.as_mutable(
4560 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4560 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4561 repo_id = Column(
4561 repo_id = Column(
4562 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4562 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4563 nullable=True, unique=None, default=None)
4563 nullable=True, unique=None, default=None)
4564 repo = relationship('Repository', lazy='joined')
4564 repo = relationship('Repository', lazy='joined')
4565
4565
4566 repo_group_id = Column(
4566 repo_group_id = Column(
4567 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4567 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4568 nullable=True, unique=None, default=None)
4568 nullable=True, unique=None, default=None)
4569 repo_group = relationship('RepoGroup', lazy='joined')
4569 repo_group = relationship('RepoGroup', lazy='joined')
4570
4570
4571 @property
4571 @property
4572 def scope(self):
4572 def scope(self):
4573 if self.repo:
4573 if self.repo:
4574 return repr(self.repo)
4574 return repr(self.repo)
4575 if self.repo_group:
4575 if self.repo_group:
4576 if self.child_repos_only:
4576 if self.child_repos_only:
4577 return repr(self.repo_group) + ' (child repos only)'
4577 return repr(self.repo_group) + ' (child repos only)'
4578 else:
4578 else:
4579 return repr(self.repo_group) + ' (recursive)'
4579 return repr(self.repo_group) + ' (recursive)'
4580 if self.child_repos_only:
4580 if self.child_repos_only:
4581 return 'root_repos'
4581 return 'root_repos'
4582 return 'global'
4582 return 'global'
4583
4583
4584 def __repr__(self):
4584 def __repr__(self):
4585 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4585 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4586
4586
4587
4587
4588 class RepoReviewRuleUser(Base, BaseModel):
4588 class RepoReviewRuleUser(Base, BaseModel):
4589 __tablename__ = 'repo_review_rules_users'
4589 __tablename__ = 'repo_review_rules_users'
4590 __table_args__ = (
4590 __table_args__ = (
4591 base_table_args
4591 base_table_args
4592 )
4592 )
4593
4593
4594 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4594 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4595 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4595 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4596 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4596 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4597 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4597 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4598 user = relationship('User')
4598 user = relationship('User')
4599
4599
4600 def rule_data(self):
4600 def rule_data(self):
4601 return {
4601 return {
4602 'mandatory': self.mandatory
4602 'mandatory': self.mandatory
4603 }
4603 }
4604
4604
4605
4605
4606 class RepoReviewRuleUserGroup(Base, BaseModel):
4606 class RepoReviewRuleUserGroup(Base, BaseModel):
4607 __tablename__ = 'repo_review_rules_users_groups'
4607 __tablename__ = 'repo_review_rules_users_groups'
4608 __table_args__ = (
4608 __table_args__ = (
4609 base_table_args
4609 base_table_args
4610 )
4610 )
4611
4611
4612 VOTE_RULE_ALL = -1
4612 VOTE_RULE_ALL = -1
4613
4613
4614 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4614 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4615 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4615 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4616 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4616 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4617 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4617 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4618 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4618 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4619 users_group = relationship('UserGroup')
4619 users_group = relationship('UserGroup')
4620
4620
4621 def rule_data(self):
4621 def rule_data(self):
4622 return {
4622 return {
4623 'mandatory': self.mandatory,
4623 'mandatory': self.mandatory,
4624 'vote_rule': self.vote_rule
4624 'vote_rule': self.vote_rule
4625 }
4625 }
4626
4626
4627 @property
4627 @property
4628 def vote_rule_label(self):
4628 def vote_rule_label(self):
4629 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4629 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4630 return 'all must vote'
4630 return 'all must vote'
4631 else:
4631 else:
4632 return 'min. vote {}'.format(self.vote_rule)
4632 return 'min. vote {}'.format(self.vote_rule)
4633
4633
4634
4634
4635 class RepoReviewRule(Base, BaseModel):
4635 class RepoReviewRule(Base, BaseModel):
4636 __tablename__ = 'repo_review_rules'
4636 __tablename__ = 'repo_review_rules'
4637 __table_args__ = (
4637 __table_args__ = (
4638 base_table_args
4638 base_table_args
4639 )
4639 )
4640
4640
4641 repo_review_rule_id = Column(
4641 repo_review_rule_id = Column(
4642 'repo_review_rule_id', Integer(), primary_key=True)
4642 'repo_review_rule_id', Integer(), primary_key=True)
4643 repo_id = Column(
4643 repo_id = Column(
4644 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4644 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4645 repo = relationship('Repository', backref='review_rules')
4645 repo = relationship('Repository', backref='review_rules')
4646
4646
4647 review_rule_name = Column('review_rule_name', String(255))
4647 review_rule_name = Column('review_rule_name', String(255))
4648 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4648 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4649 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4649 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4650 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4650 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4651
4651
4652 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4652 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4653 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4653 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4654 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4654 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4655 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4655 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4656
4656
4657 rule_users = relationship('RepoReviewRuleUser')
4657 rule_users = relationship('RepoReviewRuleUser')
4658 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4658 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4659
4659
4660 def _validate_pattern(self, value):
4660 def _validate_pattern(self, value):
4661 re.compile('^' + glob2re(value) + '$')
4661 re.compile('^' + glob2re(value) + '$')
4662
4662
4663 @hybrid_property
4663 @hybrid_property
4664 def source_branch_pattern(self):
4664 def source_branch_pattern(self):
4665 return self._branch_pattern or '*'
4665 return self._branch_pattern or '*'
4666
4666
4667 @source_branch_pattern.setter
4667 @source_branch_pattern.setter
4668 def source_branch_pattern(self, value):
4668 def source_branch_pattern(self, value):
4669 self._validate_pattern(value)
4669 self._validate_pattern(value)
4670 self._branch_pattern = value or '*'
4670 self._branch_pattern = value or '*'
4671
4671
4672 @hybrid_property
4672 @hybrid_property
4673 def target_branch_pattern(self):
4673 def target_branch_pattern(self):
4674 return self._target_branch_pattern or '*'
4674 return self._target_branch_pattern or '*'
4675
4675
4676 @target_branch_pattern.setter
4676 @target_branch_pattern.setter
4677 def target_branch_pattern(self, value):
4677 def target_branch_pattern(self, value):
4678 self._validate_pattern(value)
4678 self._validate_pattern(value)
4679 self._target_branch_pattern = value or '*'
4679 self._target_branch_pattern = value or '*'
4680
4680
4681 @hybrid_property
4681 @hybrid_property
4682 def file_pattern(self):
4682 def file_pattern(self):
4683 return self._file_pattern or '*'
4683 return self._file_pattern or '*'
4684
4684
4685 @file_pattern.setter
4685 @file_pattern.setter
4686 def file_pattern(self, value):
4686 def file_pattern(self, value):
4687 self._validate_pattern(value)
4687 self._validate_pattern(value)
4688 self._file_pattern = value or '*'
4688 self._file_pattern = value or '*'
4689
4689
4690 def matches(self, source_branch, target_branch, files_changed):
4690 def matches(self, source_branch, target_branch, files_changed):
4691 """
4691 """
4692 Check if this review rule matches a branch/files in a pull request
4692 Check if this review rule matches a branch/files in a pull request
4693
4693
4694 :param source_branch: source branch name for the commit
4694 :param source_branch: source branch name for the commit
4695 :param target_branch: target branch name for the commit
4695 :param target_branch: target branch name for the commit
4696 :param files_changed: list of file paths changed in the pull request
4696 :param files_changed: list of file paths changed in the pull request
4697 """
4697 """
4698
4698
4699 source_branch = source_branch or ''
4699 source_branch = source_branch or ''
4700 target_branch = target_branch or ''
4700 target_branch = target_branch or ''
4701 files_changed = files_changed or []
4701 files_changed = files_changed or []
4702
4702
4703 branch_matches = True
4703 branch_matches = True
4704 if source_branch or target_branch:
4704 if source_branch or target_branch:
4705 if self.source_branch_pattern == '*':
4705 if self.source_branch_pattern == '*':
4706 source_branch_match = True
4706 source_branch_match = True
4707 else:
4707 else:
4708 if self.source_branch_pattern.startswith('re:'):
4708 if self.source_branch_pattern.startswith('re:'):
4709 source_pattern = self.source_branch_pattern[3:]
4709 source_pattern = self.source_branch_pattern[3:]
4710 else:
4710 else:
4711 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4711 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4712 source_branch_regex = re.compile(source_pattern)
4712 source_branch_regex = re.compile(source_pattern)
4713 source_branch_match = bool(source_branch_regex.search(source_branch))
4713 source_branch_match = bool(source_branch_regex.search(source_branch))
4714 if self.target_branch_pattern == '*':
4714 if self.target_branch_pattern == '*':
4715 target_branch_match = True
4715 target_branch_match = True
4716 else:
4716 else:
4717 if self.target_branch_pattern.startswith('re:'):
4717 if self.target_branch_pattern.startswith('re:'):
4718 target_pattern = self.target_branch_pattern[3:]
4718 target_pattern = self.target_branch_pattern[3:]
4719 else:
4719 else:
4720 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4720 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4721 target_branch_regex = re.compile(target_pattern)
4721 target_branch_regex = re.compile(target_pattern)
4722 target_branch_match = bool(target_branch_regex.search(target_branch))
4722 target_branch_match = bool(target_branch_regex.search(target_branch))
4723
4723
4724 branch_matches = source_branch_match and target_branch_match
4724 branch_matches = source_branch_match and target_branch_match
4725
4725
4726 files_matches = True
4726 files_matches = True
4727 if self.file_pattern != '*':
4727 if self.file_pattern != '*':
4728 files_matches = False
4728 files_matches = False
4729 if self.file_pattern.startswith('re:'):
4729 if self.file_pattern.startswith('re:'):
4730 file_pattern = self.file_pattern[3:]
4730 file_pattern = self.file_pattern[3:]
4731 else:
4731 else:
4732 file_pattern = glob2re(self.file_pattern)
4732 file_pattern = glob2re(self.file_pattern)
4733 file_regex = re.compile(file_pattern)
4733 file_regex = re.compile(file_pattern)
4734 for filename in files_changed:
4734 for filename in files_changed:
4735 if file_regex.search(filename):
4735 if file_regex.search(filename):
4736 files_matches = True
4736 files_matches = True
4737 break
4737 break
4738
4738
4739 return branch_matches and files_matches
4739 return branch_matches and files_matches
4740
4740
4741 @property
4741 @property
4742 def review_users(self):
4742 def review_users(self):
4743 """ Returns the users which this rule applies to """
4743 """ Returns the users which this rule applies to """
4744
4744
4745 users = collections.OrderedDict()
4745 users = collections.OrderedDict()
4746
4746
4747 for rule_user in self.rule_users:
4747 for rule_user in self.rule_users:
4748 if rule_user.user.active:
4748 if rule_user.user.active:
4749 if rule_user.user not in users:
4749 if rule_user.user not in users:
4750 users[rule_user.user.username] = {
4750 users[rule_user.user.username] = {
4751 'user': rule_user.user,
4751 'user': rule_user.user,
4752 'source': 'user',
4752 'source': 'user',
4753 'source_data': {},
4753 'source_data': {},
4754 'data': rule_user.rule_data()
4754 'data': rule_user.rule_data()
4755 }
4755 }
4756
4756
4757 for rule_user_group in self.rule_user_groups:
4757 for rule_user_group in self.rule_user_groups:
4758 source_data = {
4758 source_data = {
4759 'user_group_id': rule_user_group.users_group.users_group_id,
4759 'user_group_id': rule_user_group.users_group.users_group_id,
4760 'name': rule_user_group.users_group.users_group_name,
4760 'name': rule_user_group.users_group.users_group_name,
4761 'members': len(rule_user_group.users_group.members)
4761 'members': len(rule_user_group.users_group.members)
4762 }
4762 }
4763 for member in rule_user_group.users_group.members:
4763 for member in rule_user_group.users_group.members:
4764 if member.user.active:
4764 if member.user.active:
4765 key = member.user.username
4765 key = member.user.username
4766 if key in users:
4766 if key in users:
4767 # skip this member as we have him already
4767 # skip this member as we have him already
4768 # this prevents from override the "first" matched
4768 # this prevents from override the "first" matched
4769 # users with duplicates in multiple groups
4769 # users with duplicates in multiple groups
4770 continue
4770 continue
4771
4771
4772 users[key] = {
4772 users[key] = {
4773 'user': member.user,
4773 'user': member.user,
4774 'source': 'user_group',
4774 'source': 'user_group',
4775 'source_data': source_data,
4775 'source_data': source_data,
4776 'data': rule_user_group.rule_data()
4776 'data': rule_user_group.rule_data()
4777 }
4777 }
4778
4778
4779 return users
4779 return users
4780
4780
4781 def user_group_vote_rule(self, user_id):
4781 def user_group_vote_rule(self, user_id):
4782
4782
4783 rules = []
4783 rules = []
4784 if not self.rule_user_groups:
4784 if not self.rule_user_groups:
4785 return rules
4785 return rules
4786
4786
4787 for user_group in self.rule_user_groups:
4787 for user_group in self.rule_user_groups:
4788 user_group_members = [x.user_id for x in user_group.users_group.members]
4788 user_group_members = [x.user_id for x in user_group.users_group.members]
4789 if user_id in user_group_members:
4789 if user_id in user_group_members:
4790 rules.append(user_group)
4790 rules.append(user_group)
4791 return rules
4791 return rules
4792
4792
4793 def __repr__(self):
4793 def __repr__(self):
4794 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4794 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4795 self.repo_review_rule_id, self.repo)
4795 self.repo_review_rule_id, self.repo)
4796
4796
4797
4797
4798 class ScheduleEntry(Base, BaseModel):
4798 class ScheduleEntry(Base, BaseModel):
4799 __tablename__ = 'schedule_entries'
4799 __tablename__ = 'schedule_entries'
4800 __table_args__ = (
4800 __table_args__ = (
4801 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4801 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4802 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4802 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4803 base_table_args,
4803 base_table_args,
4804 )
4804 )
4805
4805
4806 schedule_types = ['crontab', 'timedelta', 'integer']
4806 schedule_types = ['crontab', 'timedelta', 'integer']
4807 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4807 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4808
4808
4809 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4809 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4810 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4810 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4811 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4811 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4812
4812
4813 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4813 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4814 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4814 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4815
4815
4816 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4816 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4817 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4817 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4818
4818
4819 # task
4819 # task
4820 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4820 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4821 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4821 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4822 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4822 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4823 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4823 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4824
4824
4825 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4825 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4826 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4826 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4827
4827
4828 @hybrid_property
4828 @hybrid_property
4829 def schedule_type(self):
4829 def schedule_type(self):
4830 return self._schedule_type
4830 return self._schedule_type
4831
4831
4832 @schedule_type.setter
4832 @schedule_type.setter
4833 def schedule_type(self, val):
4833 def schedule_type(self, val):
4834 if val not in self.schedule_types:
4834 if val not in self.schedule_types:
4835 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4835 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4836 val, self.schedule_type))
4836 val, self.schedule_type))
4837
4837
4838 self._schedule_type = val
4838 self._schedule_type = val
4839
4839
4840 @classmethod
4840 @classmethod
4841 def get_uid(cls, obj):
4841 def get_uid(cls, obj):
4842 args = obj.task_args
4842 args = obj.task_args
4843 kwargs = obj.task_kwargs
4843 kwargs = obj.task_kwargs
4844 if isinstance(args, JsonRaw):
4844 if isinstance(args, JsonRaw):
4845 try:
4845 try:
4846 args = json.loads(args)
4846 args = json.loads(args)
4847 except ValueError:
4847 except ValueError:
4848 args = tuple()
4848 args = tuple()
4849
4849
4850 if isinstance(kwargs, JsonRaw):
4850 if isinstance(kwargs, JsonRaw):
4851 try:
4851 try:
4852 kwargs = json.loads(kwargs)
4852 kwargs = json.loads(kwargs)
4853 except ValueError:
4853 except ValueError:
4854 kwargs = dict()
4854 kwargs = dict()
4855
4855
4856 dot_notation = obj.task_dot_notation
4856 dot_notation = obj.task_dot_notation
4857 val = '.'.join(map(safe_str, [
4857 val = '.'.join(map(safe_str, [
4858 sorted(dot_notation), args, sorted(kwargs.items())]))
4858 sorted(dot_notation), args, sorted(kwargs.items())]))
4859 return hashlib.sha1(val).hexdigest()
4859 return hashlib.sha1(val).hexdigest()
4860
4860
4861 @classmethod
4861 @classmethod
4862 def get_by_schedule_name(cls, schedule_name):
4862 def get_by_schedule_name(cls, schedule_name):
4863 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4863 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4864
4864
4865 @classmethod
4865 @classmethod
4866 def get_by_schedule_id(cls, schedule_id):
4866 def get_by_schedule_id(cls, schedule_id):
4867 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4867 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4868
4868
4869 @property
4869 @property
4870 def task(self):
4870 def task(self):
4871 return self.task_dot_notation
4871 return self.task_dot_notation
4872
4872
4873 @property
4873 @property
4874 def schedule(self):
4874 def schedule(self):
4875 from rhodecode.lib.celerylib.utils import raw_2_schedule
4875 from rhodecode.lib.celerylib.utils import raw_2_schedule
4876 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4876 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4877 return schedule
4877 return schedule
4878
4878
4879 @property
4879 @property
4880 def args(self):
4880 def args(self):
4881 try:
4881 try:
4882 return list(self.task_args or [])
4882 return list(self.task_args or [])
4883 except ValueError:
4883 except ValueError:
4884 return list()
4884 return list()
4885
4885
4886 @property
4886 @property
4887 def kwargs(self):
4887 def kwargs(self):
4888 try:
4888 try:
4889 return dict(self.task_kwargs or {})
4889 return dict(self.task_kwargs or {})
4890 except ValueError:
4890 except ValueError:
4891 return dict()
4891 return dict()
4892
4892
4893 def _as_raw(self, val):
4893 def _as_raw(self, val):
4894 if hasattr(val, 'de_coerce'):
4894 if hasattr(val, 'de_coerce'):
4895 val = val.de_coerce()
4895 val = val.de_coerce()
4896 if val:
4896 if val:
4897 val = json.dumps(val)
4897 val = json.dumps(val)
4898
4898
4899 return val
4899 return val
4900
4900
4901 @property
4901 @property
4902 def schedule_definition_raw(self):
4902 def schedule_definition_raw(self):
4903 return self._as_raw(self.schedule_definition)
4903 return self._as_raw(self.schedule_definition)
4904
4904
4905 @property
4905 @property
4906 def args_raw(self):
4906 def args_raw(self):
4907 return self._as_raw(self.task_args)
4907 return self._as_raw(self.task_args)
4908
4908
4909 @property
4909 @property
4910 def kwargs_raw(self):
4910 def kwargs_raw(self):
4911 return self._as_raw(self.task_kwargs)
4911 return self._as_raw(self.task_kwargs)
4912
4912
4913 def __repr__(self):
4913 def __repr__(self):
4914 return '<DB:ScheduleEntry({}:{})>'.format(
4914 return '<DB:ScheduleEntry({}:{})>'.format(
4915 self.schedule_entry_id, self.schedule_name)
4915 self.schedule_entry_id, self.schedule_name)
4916
4916
4917
4917
4918 @event.listens_for(ScheduleEntry, 'before_update')
4918 @event.listens_for(ScheduleEntry, 'before_update')
4919 def update_task_uid(mapper, connection, target):
4919 def update_task_uid(mapper, connection, target):
4920 target.task_uid = ScheduleEntry.get_uid(target)
4920 target.task_uid = ScheduleEntry.get_uid(target)
4921
4921
4922
4922
4923 @event.listens_for(ScheduleEntry, 'before_insert')
4923 @event.listens_for(ScheduleEntry, 'before_insert')
4924 def set_task_uid(mapper, connection, target):
4924 def set_task_uid(mapper, connection, target):
4925 target.task_uid = ScheduleEntry.get_uid(target)
4925 target.task_uid = ScheduleEntry.get_uid(target)
4926
4926
4927
4927
4928 class _BaseBranchPerms(BaseModel):
4928 class _BaseBranchPerms(BaseModel):
4929 @classmethod
4929 @classmethod
4930 def compute_hash(cls, value):
4930 def compute_hash(cls, value):
4931 return sha1_safe(value)
4931 return sha1_safe(value)
4932
4932
4933 @hybrid_property
4933 @hybrid_property
4934 def branch_pattern(self):
4934 def branch_pattern(self):
4935 return self._branch_pattern or '*'
4935 return self._branch_pattern or '*'
4936
4936
4937 @hybrid_property
4937 @hybrid_property
4938 def branch_hash(self):
4938 def branch_hash(self):
4939 return self._branch_hash
4939 return self._branch_hash
4940
4940
4941 def _validate_glob(self, value):
4941 def _validate_glob(self, value):
4942 re.compile('^' + glob2re(value) + '$')
4942 re.compile('^' + glob2re(value) + '$')
4943
4943
4944 @branch_pattern.setter
4944 @branch_pattern.setter
4945 def branch_pattern(self, value):
4945 def branch_pattern(self, value):
4946 self._validate_glob(value)
4946 self._validate_glob(value)
4947 self._branch_pattern = value or '*'
4947 self._branch_pattern = value or '*'
4948 # set the Hash when setting the branch pattern
4948 # set the Hash when setting the branch pattern
4949 self._branch_hash = self.compute_hash(self._branch_pattern)
4949 self._branch_hash = self.compute_hash(self._branch_pattern)
4950
4950
4951 def matches(self, branch):
4951 def matches(self, branch):
4952 """
4952 """
4953 Check if this the branch matches entry
4953 Check if this the branch matches entry
4954
4954
4955 :param branch: branch name for the commit
4955 :param branch: branch name for the commit
4956 """
4956 """
4957
4957
4958 branch = branch or ''
4958 branch = branch or ''
4959
4959
4960 branch_matches = True
4960 branch_matches = True
4961 if branch:
4961 if branch:
4962 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4962 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4963 branch_matches = bool(branch_regex.search(branch))
4963 branch_matches = bool(branch_regex.search(branch))
4964
4964
4965 return branch_matches
4965 return branch_matches
4966
4966
4967
4967
4968 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4968 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
4969 __tablename__ = 'user_to_repo_branch_permissions'
4969 __tablename__ = 'user_to_repo_branch_permissions'
4970 __table_args__ = (
4970 __table_args__ = (
4971 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4971 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4972 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4972 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4973 )
4973 )
4974
4974
4975 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4975 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
4976
4976
4977 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4977 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
4978 repo = relationship('Repository', backref='user_branch_perms')
4978 repo = relationship('Repository', backref='user_branch_perms')
4979
4979
4980 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4980 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
4981 permission = relationship('Permission')
4981 permission = relationship('Permission')
4982
4982
4983 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4983 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
4984 user_repo_to_perm = relationship('UserRepoToPerm')
4984 user_repo_to_perm = relationship('UserRepoToPerm')
4985
4985
4986 rule_order = Column('rule_order', Integer(), nullable=False)
4986 rule_order = Column('rule_order', Integer(), nullable=False)
4987 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4987 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
4988 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4988 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
4989
4989
4990 def __unicode__(self):
4990 def __unicode__(self):
4991 return u'<UserBranchPermission(%s => %r)>' % (
4991 return u'<UserBranchPermission(%s => %r)>' % (
4992 self.user_repo_to_perm, self.branch_pattern)
4992 self.user_repo_to_perm, self.branch_pattern)
4993
4993
4994
4994
4995 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4995 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
4996 __tablename__ = 'user_group_to_repo_branch_permissions'
4996 __tablename__ = 'user_group_to_repo_branch_permissions'
4997 __table_args__ = (
4997 __table_args__ = (
4998 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4998 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4999 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4999 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
5000 )
5000 )
5001
5001
5002 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5002 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5003
5003
5004 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5004 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5005 repo = relationship('Repository', backref='user_group_branch_perms')
5005 repo = relationship('Repository', backref='user_group_branch_perms')
5006
5006
5007 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5007 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5008 permission = relationship('Permission')
5008 permission = relationship('Permission')
5009
5009
5010 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)
5010 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)
5011 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
5011 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
5012
5012
5013 rule_order = Column('rule_order', Integer(), nullable=False)
5013 rule_order = Column('rule_order', Integer(), nullable=False)
5014 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5014 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5015 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5015 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5016
5016
5017 def __unicode__(self):
5017 def __unicode__(self):
5018 return u'<UserBranchPermission(%s => %r)>' % (
5018 return u'<UserBranchPermission(%s => %r)>' % (
5019 self.user_group_repo_to_perm, self.branch_pattern)
5019 self.user_group_repo_to_perm, self.branch_pattern)
5020
5020
5021
5021
5022 class UserBookmark(Base, BaseModel):
5022 class UserBookmark(Base, BaseModel):
5023 __tablename__ = 'user_bookmarks'
5023 __tablename__ = 'user_bookmarks'
5024 __table_args__ = (
5024 __table_args__ = (
5025 UniqueConstraint('user_id', 'bookmark_repo_id'),
5025 UniqueConstraint('user_id', 'bookmark_repo_id'),
5026 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5026 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5027 UniqueConstraint('user_id', 'bookmark_position'),
5027 UniqueConstraint('user_id', 'bookmark_position'),
5028 base_table_args
5028 base_table_args
5029 )
5029 )
5030
5030
5031 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5031 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5032 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5032 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5033 position = Column("bookmark_position", Integer(), nullable=False)
5033 position = Column("bookmark_position", Integer(), nullable=False)
5034 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5034 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5035 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5035 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5036 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5036 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5037
5037
5038 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5038 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5039 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5039 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5040
5040
5041 user = relationship("User")
5041 user = relationship("User")
5042
5042
5043 repository = relationship("Repository")
5043 repository = relationship("Repository")
5044 repository_group = relationship("RepoGroup")
5044 repository_group = relationship("RepoGroup")
5045
5045
5046 @classmethod
5046 @classmethod
5047 def get_by_position_for_user(cls, position, user_id):
5047 def get_by_position_for_user(cls, position, user_id):
5048 return cls.query() \
5048 return cls.query() \
5049 .filter(UserBookmark.user_id == user_id) \
5049 .filter(UserBookmark.user_id == user_id) \
5050 .filter(UserBookmark.position == position).scalar()
5050 .filter(UserBookmark.position == position).scalar()
5051
5051
5052 @classmethod
5052 @classmethod
5053 def get_bookmarks_for_user(cls, user_id):
5053 def get_bookmarks_for_user(cls, user_id):
5054 return cls.query() \
5054 return cls.query() \
5055 .filter(UserBookmark.user_id == user_id) \
5055 .filter(UserBookmark.user_id == user_id) \
5056 .options(joinedload(UserBookmark.repository)) \
5056 .options(joinedload(UserBookmark.repository)) \
5057 .options(joinedload(UserBookmark.repository_group)) \
5057 .options(joinedload(UserBookmark.repository_group)) \
5058 .order_by(UserBookmark.position.asc()) \
5058 .order_by(UserBookmark.position.asc()) \
5059 .all()
5059 .all()
5060
5060
5061 def __unicode__(self):
5061 def __unicode__(self):
5062 return u'<UserBookmark(%d @ %r)>' % (self.position, self.redirect_url)
5062 return u'<UserBookmark(%d @ %r)>' % (self.position, self.redirect_url)
5063
5063
5064
5064
5065 class FileStore(Base, BaseModel):
5065 class FileStore(Base, BaseModel):
5066 __tablename__ = 'file_store'
5066 __tablename__ = 'file_store'
5067 __table_args__ = (
5067 __table_args__ = (
5068 base_table_args
5068 base_table_args
5069 )
5069 )
5070
5070
5071 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5071 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5072 file_uid = Column('file_uid', String(1024), nullable=False)
5072 file_uid = Column('file_uid', String(1024), nullable=False)
5073 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5073 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5074 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5074 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5075 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5075 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5076
5076
5077 # sha256 hash
5077 # sha256 hash
5078 file_hash = Column('file_hash', String(512), nullable=False)
5078 file_hash = Column('file_hash', String(512), nullable=False)
5079 file_size = Column('file_size', Integer(), nullable=False)
5079 file_size = Column('file_size', Integer(), nullable=False)
5080
5080
5081 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5081 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5082 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5082 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5083 accessed_count = Column('accessed_count', Integer(), default=0)
5083 accessed_count = Column('accessed_count', Integer(), default=0)
5084
5084
5085 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5085 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5086
5086
5087 # if repo/repo_group reference is set, check for permissions
5087 # if repo/repo_group reference is set, check for permissions
5088 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5088 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5089
5089
5090 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5090 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5091 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
5091 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
5092
5092
5093 # scope limited to user, which requester have access to
5093 # scope limited to user, which requester have access to
5094 scope_user_id = Column(
5094 scope_user_id = Column(
5095 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5095 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5096 nullable=True, unique=None, default=None)
5096 nullable=True, unique=None, default=None)
5097 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
5097 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
5098
5098
5099 # scope limited to user group, which requester have access to
5099 # scope limited to user group, which requester have access to
5100 scope_user_group_id = Column(
5100 scope_user_group_id = Column(
5101 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5101 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5102 nullable=True, unique=None, default=None)
5102 nullable=True, unique=None, default=None)
5103 user_group = relationship('UserGroup', lazy='joined')
5103 user_group = relationship('UserGroup', lazy='joined')
5104
5104
5105 # scope limited to repo, which requester have access to
5105 # scope limited to repo, which requester have access to
5106 scope_repo_id = Column(
5106 scope_repo_id = Column(
5107 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5107 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5108 nullable=True, unique=None, default=None)
5108 nullable=True, unique=None, default=None)
5109 repo = relationship('Repository', lazy='joined')
5109 repo = relationship('Repository', lazy='joined')
5110
5110
5111 # scope limited to repo group, which requester have access to
5111 # scope limited to repo group, which requester have access to
5112 scope_repo_group_id = Column(
5112 scope_repo_group_id = Column(
5113 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5113 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5114 nullable=True, unique=None, default=None)
5114 nullable=True, unique=None, default=None)
5115 repo_group = relationship('RepoGroup', lazy='joined')
5115 repo_group = relationship('RepoGroup', lazy='joined')
5116
5116
5117 @classmethod
5117 @classmethod
5118 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5118 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5119 file_description='', enabled=True, check_acl=True, user_id=None,
5119 file_description='', enabled=True, check_acl=True, user_id=None,
5120 scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5120 scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5121
5121
5122 store_entry = FileStore()
5122 store_entry = FileStore()
5123 store_entry.file_uid = file_uid
5123 store_entry.file_uid = file_uid
5124 store_entry.file_display_name = file_display_name
5124 store_entry.file_display_name = file_display_name
5125 store_entry.file_org_name = filename
5125 store_entry.file_org_name = filename
5126 store_entry.file_size = file_size
5126 store_entry.file_size = file_size
5127 store_entry.file_hash = file_hash
5127 store_entry.file_hash = file_hash
5128 store_entry.file_description = file_description
5128 store_entry.file_description = file_description
5129
5129
5130 store_entry.check_acl = check_acl
5130 store_entry.check_acl = check_acl
5131 store_entry.enabled = enabled
5131 store_entry.enabled = enabled
5132
5132
5133 store_entry.user_id = user_id
5133 store_entry.user_id = user_id
5134 store_entry.scope_user_id = scope_user_id
5134 store_entry.scope_user_id = scope_user_id
5135 store_entry.scope_repo_id = scope_repo_id
5135 store_entry.scope_repo_id = scope_repo_id
5136 store_entry.scope_repo_group_id = scope_repo_group_id
5136 store_entry.scope_repo_group_id = scope_repo_group_id
5137 return store_entry
5137 return store_entry
5138
5138
5139 @classmethod
5139 @classmethod
5140 def bump_access_counter(cls, file_uid, commit=True):
5140 def bump_access_counter(cls, file_uid, commit=True):
5141 FileStore().query()\
5141 FileStore().query()\
5142 .filter(FileStore.file_uid == file_uid)\
5142 .filter(FileStore.file_uid == file_uid)\
5143 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5143 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5144 FileStore.accessed_on: datetime.datetime.now()})
5144 FileStore.accessed_on: datetime.datetime.now()})
5145 if commit:
5145 if commit:
5146 Session().commit()
5146 Session().commit()
5147
5147
5148 def __repr__(self):
5148 def __repr__(self):
5149 return '<FileStore({})>'.format(self.file_store_id)
5149 return '<FileStore({})>'.format(self.file_store_id)
5150
5150
5151
5151
5152 class DbMigrateVersion(Base, BaseModel):
5152 class DbMigrateVersion(Base, BaseModel):
5153 __tablename__ = 'db_migrate_version'
5153 __tablename__ = 'db_migrate_version'
5154 __table_args__ = (
5154 __table_args__ = (
5155 base_table_args,
5155 base_table_args,
5156 )
5156 )
5157
5157
5158 repository_id = Column('repository_id', String(250), primary_key=True)
5158 repository_id = Column('repository_id', String(250), primary_key=True)
5159 repository_path = Column('repository_path', Text)
5159 repository_path = Column('repository_path', Text)
5160 version = Column('version', Integer)
5160 version = Column('version', Integer)
5161
5161
5162 @classmethod
5162 @classmethod
5163 def set_version(cls, version):
5163 def set_version(cls, version):
5164 """
5164 """
5165 Helper for forcing a different version, usually for debugging purposes via ishell.
5165 Helper for forcing a different version, usually for debugging purposes via ishell.
5166 """
5166 """
5167 ver = DbMigrateVersion.query().first()
5167 ver = DbMigrateVersion.query().first()
5168 ver.version = version
5168 ver.version = version
5169 Session().commit()
5169 Session().commit()
5170
5170
5171
5171
5172 class DbSession(Base, BaseModel):
5172 class DbSession(Base, BaseModel):
5173 __tablename__ = 'db_session'
5173 __tablename__ = 'db_session'
5174 __table_args__ = (
5174 __table_args__ = (
5175 base_table_args,
5175 base_table_args,
5176 )
5176 )
5177
5177
5178 def __repr__(self):
5178 def __repr__(self):
5179 return '<DB:DbSession({})>'.format(self.id)
5179 return '<DB:DbSession({})>'.format(self.id)
5180
5180
5181 id = Column('id', Integer())
5181 id = Column('id', Integer())
5182 namespace = Column('namespace', String(255), primary_key=True)
5182 namespace = Column('namespace', String(255), primary_key=True)
5183 accessed = Column('accessed', DateTime, nullable=False)
5183 accessed = Column('accessed', DateTime, nullable=False)
5184 created = Column('created', DateTime, nullable=False)
5184 created = Column('created', DateTime, nullable=False)
5185 data = Column('data', PickleType, nullable=False)
5185 data = Column('data', PickleType, nullable=False)
@@ -1,888 +1,888 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import os
21 import os
22 import hashlib
22 import hashlib
23 import logging
23 import logging
24 from collections import namedtuple
24 from collections import namedtuple
25 from functools import wraps
25 from functools import wraps
26 import bleach
26 import bleach
27
27
28 from rhodecode.lib import rc_cache
28 from rhodecode.lib import rc_cache
29 from rhodecode.lib.utils2 import (
29 from rhodecode.lib.utils2 import (
30 Optional, AttributeDict, safe_str, remove_prefix, str2bool)
30 Optional, AttributeDict, safe_str, remove_prefix, str2bool)
31 from rhodecode.lib.vcs.backends import base
31 from rhodecode.lib.vcs.backends import base
32 from rhodecode.model import BaseModel
32 from rhodecode.model import BaseModel
33 from rhodecode.model.db import (
33 from rhodecode.model.db import (
34 RepoRhodeCodeUi, RepoRhodeCodeSetting, RhodeCodeUi, RhodeCodeSetting, CacheKey)
34 RepoRhodeCodeUi, RepoRhodeCodeSetting, RhodeCodeUi, RhodeCodeSetting, CacheKey)
35 from rhodecode.model.meta import Session
35 from rhodecode.model.meta import Session
36
36
37
37
38 log = logging.getLogger(__name__)
38 log = logging.getLogger(__name__)
39
39
40
40
41 UiSetting = namedtuple(
41 UiSetting = namedtuple(
42 'UiSetting', ['section', 'key', 'value', 'active'])
42 'UiSetting', ['section', 'key', 'value', 'active'])
43
43
44 SOCIAL_PLUGINS_LIST = ['github', 'bitbucket', 'twitter', 'google']
44 SOCIAL_PLUGINS_LIST = ['github', 'bitbucket', 'twitter', 'google']
45
45
46
46
47 class SettingNotFound(Exception):
47 class SettingNotFound(Exception):
48 def __init__(self, setting_id):
48 def __init__(self, setting_id):
49 msg = 'Setting `{}` is not found'.format(setting_id)
49 msg = 'Setting `{}` is not found'.format(setting_id)
50 super(SettingNotFound, self).__init__(msg)
50 super(SettingNotFound, self).__init__(msg)
51
51
52
52
53 class SettingsModel(BaseModel):
53 class SettingsModel(BaseModel):
54 BUILTIN_HOOKS = (
54 BUILTIN_HOOKS = (
55 RhodeCodeUi.HOOK_REPO_SIZE, RhodeCodeUi.HOOK_PUSH,
55 RhodeCodeUi.HOOK_REPO_SIZE, RhodeCodeUi.HOOK_PUSH,
56 RhodeCodeUi.HOOK_PRE_PUSH, RhodeCodeUi.HOOK_PRETX_PUSH,
56 RhodeCodeUi.HOOK_PRE_PUSH, RhodeCodeUi.HOOK_PRETX_PUSH,
57 RhodeCodeUi.HOOK_PULL, RhodeCodeUi.HOOK_PRE_PULL,
57 RhodeCodeUi.HOOK_PULL, RhodeCodeUi.HOOK_PRE_PULL,
58 RhodeCodeUi.HOOK_PUSH_KEY,)
58 RhodeCodeUi.HOOK_PUSH_KEY,)
59 HOOKS_SECTION = 'hooks'
59 HOOKS_SECTION = 'hooks'
60
60
61 def __init__(self, sa=None, repo=None):
61 def __init__(self, sa=None, repo=None):
62 self.repo = repo
62 self.repo = repo
63 self.UiDbModel = RepoRhodeCodeUi if repo else RhodeCodeUi
63 self.UiDbModel = RepoRhodeCodeUi if repo else RhodeCodeUi
64 self.SettingsDbModel = (
64 self.SettingsDbModel = (
65 RepoRhodeCodeSetting if repo else RhodeCodeSetting)
65 RepoRhodeCodeSetting if repo else RhodeCodeSetting)
66 super(SettingsModel, self).__init__(sa)
66 super(SettingsModel, self).__init__(sa)
67
67
68 def get_ui_by_key(self, key):
68 def get_ui_by_key(self, key):
69 q = self.UiDbModel.query()
69 q = self.UiDbModel.query()
70 q = q.filter(self.UiDbModel.ui_key == key)
70 q = q.filter(self.UiDbModel.ui_key == key)
71 q = self._filter_by_repo(RepoRhodeCodeUi, q)
71 q = self._filter_by_repo(RepoRhodeCodeUi, q)
72 return q.scalar()
72 return q.scalar()
73
73
74 def get_ui_by_section(self, section):
74 def get_ui_by_section(self, section):
75 q = self.UiDbModel.query()
75 q = self.UiDbModel.query()
76 q = q.filter(self.UiDbModel.ui_section == section)
76 q = q.filter(self.UiDbModel.ui_section == section)
77 q = self._filter_by_repo(RepoRhodeCodeUi, q)
77 q = self._filter_by_repo(RepoRhodeCodeUi, q)
78 return q.all()
78 return q.all()
79
79
80 def get_ui_by_section_and_key(self, section, key):
80 def get_ui_by_section_and_key(self, section, key):
81 q = self.UiDbModel.query()
81 q = self.UiDbModel.query()
82 q = q.filter(self.UiDbModel.ui_section == section)
82 q = q.filter(self.UiDbModel.ui_section == section)
83 q = q.filter(self.UiDbModel.ui_key == key)
83 q = q.filter(self.UiDbModel.ui_key == key)
84 q = self._filter_by_repo(RepoRhodeCodeUi, q)
84 q = self._filter_by_repo(RepoRhodeCodeUi, q)
85 return q.scalar()
85 return q.scalar()
86
86
87 def get_ui(self, section=None, key=None):
87 def get_ui(self, section=None, key=None):
88 q = self.UiDbModel.query()
88 q = self.UiDbModel.query()
89 q = self._filter_by_repo(RepoRhodeCodeUi, q)
89 q = self._filter_by_repo(RepoRhodeCodeUi, q)
90
90
91 if section:
91 if section:
92 q = q.filter(self.UiDbModel.ui_section == section)
92 q = q.filter(self.UiDbModel.ui_section == section)
93 if key:
93 if key:
94 q = q.filter(self.UiDbModel.ui_key == key)
94 q = q.filter(self.UiDbModel.ui_key == key)
95
95
96 # TODO: mikhail: add caching
96 # TODO: mikhail: add caching
97 result = [
97 result = [
98 UiSetting(
98 UiSetting(
99 section=safe_str(r.ui_section), key=safe_str(r.ui_key),
99 section=safe_str(r.ui_section), key=safe_str(r.ui_key),
100 value=safe_str(r.ui_value), active=r.ui_active
100 value=safe_str(r.ui_value), active=r.ui_active
101 )
101 )
102 for r in q.all()
102 for r in q.all()
103 ]
103 ]
104 return result
104 return result
105
105
106 def get_builtin_hooks(self):
106 def get_builtin_hooks(self):
107 q = self.UiDbModel.query()
107 q = self.UiDbModel.query()
108 q = q.filter(self.UiDbModel.ui_key.in_(self.BUILTIN_HOOKS))
108 q = q.filter(self.UiDbModel.ui_key.in_(self.BUILTIN_HOOKS))
109 return self._get_hooks(q)
109 return self._get_hooks(q)
110
110
111 def get_custom_hooks(self):
111 def get_custom_hooks(self):
112 q = self.UiDbModel.query()
112 q = self.UiDbModel.query()
113 q = q.filter(~self.UiDbModel.ui_key.in_(self.BUILTIN_HOOKS))
113 q = q.filter(~self.UiDbModel.ui_key.in_(self.BUILTIN_HOOKS))
114 return self._get_hooks(q)
114 return self._get_hooks(q)
115
115
116 def create_ui_section_value(self, section, val, key=None, active=True):
116 def create_ui_section_value(self, section, val, key=None, active=True):
117 new_ui = self.UiDbModel()
117 new_ui = self.UiDbModel()
118 new_ui.ui_section = section
118 new_ui.ui_section = section
119 new_ui.ui_value = val
119 new_ui.ui_value = val
120 new_ui.ui_active = active
120 new_ui.ui_active = active
121
121
122 repository_id = ''
122 repository_id = ''
123 if self.repo:
123 if self.repo:
124 repo = self._get_repo(self.repo)
124 repo = self._get_repo(self.repo)
125 repository_id = repo.repo_id
125 repository_id = repo.repo_id
126 new_ui.repository_id = repository_id
126 new_ui.repository_id = repository_id
127
127
128 if not key:
128 if not key:
129 # keys are unique so they need appended info
129 # keys are unique so they need appended info
130 if self.repo:
130 if self.repo:
131 key = hashlib.sha1(
131 key = hashlib.sha1(
132 '{}{}{}'.format(section, val, repository_id)).hexdigest()
132 '{}{}{}'.format(section, val, repository_id)).hexdigest()
133 else:
133 else:
134 key = hashlib.sha1('{}{}'.format(section, val)).hexdigest()
134 key = hashlib.sha1('{}{}'.format(section, val)).hexdigest()
135
135
136 new_ui.ui_key = key
136 new_ui.ui_key = key
137
137
138 Session().add(new_ui)
138 Session().add(new_ui)
139 return new_ui
139 return new_ui
140
140
141 def create_or_update_hook(self, key, value):
141 def create_or_update_hook(self, key, value):
142 ui = (
142 ui = (
143 self.get_ui_by_section_and_key(self.HOOKS_SECTION, key) or
143 self.get_ui_by_section_and_key(self.HOOKS_SECTION, key) or
144 self.UiDbModel())
144 self.UiDbModel())
145 ui.ui_section = self.HOOKS_SECTION
145 ui.ui_section = self.HOOKS_SECTION
146 ui.ui_active = True
146 ui.ui_active = True
147 ui.ui_key = key
147 ui.ui_key = key
148 ui.ui_value = value
148 ui.ui_value = value
149
149
150 if self.repo:
150 if self.repo:
151 repo = self._get_repo(self.repo)
151 repo = self._get_repo(self.repo)
152 repository_id = repo.repo_id
152 repository_id = repo.repo_id
153 ui.repository_id = repository_id
153 ui.repository_id = repository_id
154
154
155 Session().add(ui)
155 Session().add(ui)
156 return ui
156 return ui
157
157
158 def delete_ui(self, id_):
158 def delete_ui(self, id_):
159 ui = self.UiDbModel.get(id_)
159 ui = self.UiDbModel.get(id_)
160 if not ui:
160 if not ui:
161 raise SettingNotFound(id_)
161 raise SettingNotFound(id_)
162 Session().delete(ui)
162 Session().delete(ui)
163
163
164 def get_setting_by_name(self, name):
164 def get_setting_by_name(self, name):
165 q = self._get_settings_query()
165 q = self._get_settings_query()
166 q = q.filter(self.SettingsDbModel.app_settings_name == name)
166 q = q.filter(self.SettingsDbModel.app_settings_name == name)
167 return q.scalar()
167 return q.scalar()
168
168
169 def create_or_update_setting(
169 def create_or_update_setting(
170 self, name, val=Optional(''), type_=Optional('unicode')):
170 self, name, val=Optional(''), type_=Optional('unicode')):
171 """
171 """
172 Creates or updates RhodeCode setting. If updates is triggered it will
172 Creates or updates RhodeCode setting. If updates is triggered it will
173 only update parameters that are explicityl set Optional instance will
173 only update parameters that are explicityl set Optional instance will
174 be skipped
174 be skipped
175
175
176 :param name:
176 :param name:
177 :param val:
177 :param val:
178 :param type_:
178 :param type_:
179 :return:
179 :return:
180 """
180 """
181
181
182 res = self.get_setting_by_name(name)
182 res = self.get_setting_by_name(name)
183 repo = self._get_repo(self.repo) if self.repo else None
183 repo = self._get_repo(self.repo) if self.repo else None
184
184
185 if not res:
185 if not res:
186 val = Optional.extract(val)
186 val = Optional.extract(val)
187 type_ = Optional.extract(type_)
187 type_ = Optional.extract(type_)
188
188
189 args = (
189 args = (
190 (repo.repo_id, name, val, type_)
190 (repo.repo_id, name, val, type_)
191 if repo else (name, val, type_))
191 if repo else (name, val, type_))
192 res = self.SettingsDbModel(*args)
192 res = self.SettingsDbModel(*args)
193
193
194 else:
194 else:
195 if self.repo:
195 if self.repo:
196 res.repository_id = repo.repo_id
196 res.repository_id = repo.repo_id
197
197
198 res.app_settings_name = name
198 res.app_settings_name = name
199 if not isinstance(type_, Optional):
199 if not isinstance(type_, Optional):
200 # update if set
200 # update if set
201 res.app_settings_type = type_
201 res.app_settings_type = type_
202 if not isinstance(val, Optional):
202 if not isinstance(val, Optional):
203 # update if set
203 # update if set
204 res.app_settings_value = val
204 res.app_settings_value = val
205
205
206 Session().add(res)
206 Session().add(res)
207 return res
207 return res
208
208
209 def invalidate_settings_cache(self):
209 def invalidate_settings_cache(self):
210 invalidation_namespace = CacheKey.SETTINGS_INVALIDATION_NAMESPACE
210 invalidation_namespace = CacheKey.SETTINGS_INVALIDATION_NAMESPACE
211 CacheKey.set_invalidate(invalidation_namespace)
211 CacheKey.set_invalidate(invalidation_namespace)
212
212
213 def get_all_settings(self, cache=False):
213 def get_all_settings(self, cache=False):
214 region = rc_cache.get_or_create_region('sql_cache_short')
214 region = rc_cache.get_or_create_region('sql_cache_short')
215 invalidation_namespace = CacheKey.SETTINGS_INVALIDATION_NAMESPACE
215 invalidation_namespace = CacheKey.SETTINGS_INVALIDATION_NAMESPACE
216
216
217 @region.conditional_cache_on_arguments(condition=cache)
217 @region.conditional_cache_on_arguments(condition=cache)
218 def _get_all_settings(name, key):
218 def _get_all_settings(name, key):
219 q = self._get_settings_query()
219 q = self._get_settings_query()
220 if not q:
220 if not q:
221 raise Exception('Could not get application settings !')
221 raise Exception('Could not get application settings !')
222
222
223 settings = {
223 settings = {
224 'rhodecode_' + result.app_settings_name: result.app_settings_value
224 'rhodecode_' + result.app_settings_name: result.app_settings_value
225 for result in q
225 for result in q
226 }
226 }
227 return settings
227 return settings
228
228
229 repo = self._get_repo(self.repo) if self.repo else None
229 repo = self._get_repo(self.repo) if self.repo else None
230 key = "settings_repo.{}".format(repo.repo_id) if repo else "settings_app"
230 key = "settings_repo.{}".format(repo.repo_id) if repo else "settings_app"
231
231
232 inv_context_manager = rc_cache.InvalidationContext(
232 inv_context_manager = rc_cache.InvalidationContext(
233 uid='cache_settings', invalidation_namespace=invalidation_namespace)
233 uid='cache_settings', invalidation_namespace=invalidation_namespace)
234 with inv_context_manager as invalidation_context:
234 with inv_context_manager as invalidation_context:
235 # check for stored invalidation signal, and maybe purge the cache
235 # check for stored invalidation signal, and maybe purge the cache
236 # before computing it again
236 # before computing it again
237 if invalidation_context.should_invalidate():
237 if invalidation_context.should_invalidate():
238 # NOTE:(marcink) we flush the whole sql_cache_short region, because it
238 # NOTE:(marcink) we flush the whole sql_cache_short region, because it
239 # reads different settings etc. It's little too much but those caches
239 # reads different settings etc. It's little too much but those caches
240 # are anyway very short lived and it's a safest way.
240 # are anyway very short lived and it's a safest way.
241 region = rc_cache.get_or_create_region('sql_cache_short')
241 region = rc_cache.get_or_create_region('sql_cache_short')
242 region.invalidate()
242 region.invalidate()
243
243
244 result = _get_all_settings('rhodecode_settings', key)
244 result = _get_all_settings('rhodecode_settings', key)
245 log.debug('Fetching app settings for key: %s took: %.3fs', key,
245 log.debug('Fetching app settings for key: %s took: %.4fs', key,
246 inv_context_manager.compute_time)
246 inv_context_manager.compute_time)
247
247
248 return result
248 return result
249
249
250 def get_auth_settings(self):
250 def get_auth_settings(self):
251 q = self._get_settings_query()
251 q = self._get_settings_query()
252 q = q.filter(
252 q = q.filter(
253 self.SettingsDbModel.app_settings_name.startswith('auth_'))
253 self.SettingsDbModel.app_settings_name.startswith('auth_'))
254 rows = q.all()
254 rows = q.all()
255 auth_settings = {
255 auth_settings = {
256 row.app_settings_name: row.app_settings_value for row in rows}
256 row.app_settings_name: row.app_settings_value for row in rows}
257 return auth_settings
257 return auth_settings
258
258
259 def get_auth_plugins(self):
259 def get_auth_plugins(self):
260 auth_plugins = self.get_setting_by_name("auth_plugins")
260 auth_plugins = self.get_setting_by_name("auth_plugins")
261 return auth_plugins.app_settings_value
261 return auth_plugins.app_settings_value
262
262
263 def get_default_repo_settings(self, strip_prefix=False):
263 def get_default_repo_settings(self, strip_prefix=False):
264 q = self._get_settings_query()
264 q = self._get_settings_query()
265 q = q.filter(
265 q = q.filter(
266 self.SettingsDbModel.app_settings_name.startswith('default_'))
266 self.SettingsDbModel.app_settings_name.startswith('default_'))
267 rows = q.all()
267 rows = q.all()
268
268
269 result = {}
269 result = {}
270 for row in rows:
270 for row in rows:
271 key = row.app_settings_name
271 key = row.app_settings_name
272 if strip_prefix:
272 if strip_prefix:
273 key = remove_prefix(key, prefix='default_')
273 key = remove_prefix(key, prefix='default_')
274 result.update({key: row.app_settings_value})
274 result.update({key: row.app_settings_value})
275 return result
275 return result
276
276
277 def get_repo(self):
277 def get_repo(self):
278 repo = self._get_repo(self.repo)
278 repo = self._get_repo(self.repo)
279 if not repo:
279 if not repo:
280 raise Exception(
280 raise Exception(
281 'Repository `{}` cannot be found inside the database'.format(
281 'Repository `{}` cannot be found inside the database'.format(
282 self.repo))
282 self.repo))
283 return repo
283 return repo
284
284
285 def _filter_by_repo(self, model, query):
285 def _filter_by_repo(self, model, query):
286 if self.repo:
286 if self.repo:
287 repo = self.get_repo()
287 repo = self.get_repo()
288 query = query.filter(model.repository_id == repo.repo_id)
288 query = query.filter(model.repository_id == repo.repo_id)
289 return query
289 return query
290
290
291 def _get_hooks(self, query):
291 def _get_hooks(self, query):
292 query = query.filter(self.UiDbModel.ui_section == self.HOOKS_SECTION)
292 query = query.filter(self.UiDbModel.ui_section == self.HOOKS_SECTION)
293 query = self._filter_by_repo(RepoRhodeCodeUi, query)
293 query = self._filter_by_repo(RepoRhodeCodeUi, query)
294 return query.all()
294 return query.all()
295
295
296 def _get_settings_query(self):
296 def _get_settings_query(self):
297 q = self.SettingsDbModel.query()
297 q = self.SettingsDbModel.query()
298 return self._filter_by_repo(RepoRhodeCodeSetting, q)
298 return self._filter_by_repo(RepoRhodeCodeSetting, q)
299
299
300 def list_enabled_social_plugins(self, settings):
300 def list_enabled_social_plugins(self, settings):
301 enabled = []
301 enabled = []
302 for plug in SOCIAL_PLUGINS_LIST:
302 for plug in SOCIAL_PLUGINS_LIST:
303 if str2bool(settings.get('rhodecode_auth_{}_enabled'.format(plug)
303 if str2bool(settings.get('rhodecode_auth_{}_enabled'.format(plug)
304 )):
304 )):
305 enabled.append(plug)
305 enabled.append(plug)
306 return enabled
306 return enabled
307
307
308
308
309 def assert_repo_settings(func):
309 def assert_repo_settings(func):
310 @wraps(func)
310 @wraps(func)
311 def _wrapper(self, *args, **kwargs):
311 def _wrapper(self, *args, **kwargs):
312 if not self.repo_settings:
312 if not self.repo_settings:
313 raise Exception('Repository is not specified')
313 raise Exception('Repository is not specified')
314 return func(self, *args, **kwargs)
314 return func(self, *args, **kwargs)
315 return _wrapper
315 return _wrapper
316
316
317
317
318 class IssueTrackerSettingsModel(object):
318 class IssueTrackerSettingsModel(object):
319 INHERIT_SETTINGS = 'inherit_issue_tracker_settings'
319 INHERIT_SETTINGS = 'inherit_issue_tracker_settings'
320 SETTINGS_PREFIX = 'issuetracker_'
320 SETTINGS_PREFIX = 'issuetracker_'
321
321
322 def __init__(self, sa=None, repo=None):
322 def __init__(self, sa=None, repo=None):
323 self.global_settings = SettingsModel(sa=sa)
323 self.global_settings = SettingsModel(sa=sa)
324 self.repo_settings = SettingsModel(sa=sa, repo=repo) if repo else None
324 self.repo_settings = SettingsModel(sa=sa, repo=repo) if repo else None
325
325
326 @property
326 @property
327 def inherit_global_settings(self):
327 def inherit_global_settings(self):
328 if not self.repo_settings:
328 if not self.repo_settings:
329 return True
329 return True
330 setting = self.repo_settings.get_setting_by_name(self.INHERIT_SETTINGS)
330 setting = self.repo_settings.get_setting_by_name(self.INHERIT_SETTINGS)
331 return setting.app_settings_value if setting else True
331 return setting.app_settings_value if setting else True
332
332
333 @inherit_global_settings.setter
333 @inherit_global_settings.setter
334 def inherit_global_settings(self, value):
334 def inherit_global_settings(self, value):
335 if self.repo_settings:
335 if self.repo_settings:
336 settings = self.repo_settings.create_or_update_setting(
336 settings = self.repo_settings.create_or_update_setting(
337 self.INHERIT_SETTINGS, value, type_='bool')
337 self.INHERIT_SETTINGS, value, type_='bool')
338 Session().add(settings)
338 Session().add(settings)
339
339
340 def _get_keyname(self, key, uid, prefix=''):
340 def _get_keyname(self, key, uid, prefix=''):
341 return '{0}{1}{2}_{3}'.format(
341 return '{0}{1}{2}_{3}'.format(
342 prefix, self.SETTINGS_PREFIX, key, uid)
342 prefix, self.SETTINGS_PREFIX, key, uid)
343
343
344 def _make_dict_for_settings(self, qs):
344 def _make_dict_for_settings(self, qs):
345 prefix_match = self._get_keyname('pat', '', 'rhodecode_')
345 prefix_match = self._get_keyname('pat', '', 'rhodecode_')
346
346
347 issuetracker_entries = {}
347 issuetracker_entries = {}
348 # create keys
348 # create keys
349 for k, v in qs.items():
349 for k, v in qs.items():
350 if k.startswith(prefix_match):
350 if k.startswith(prefix_match):
351 uid = k[len(prefix_match):]
351 uid = k[len(prefix_match):]
352 issuetracker_entries[uid] = None
352 issuetracker_entries[uid] = None
353
353
354 def url_cleaner(input_str):
354 def url_cleaner(input_str):
355 input_str = input_str.replace('"', '').replace("'", '')
355 input_str = input_str.replace('"', '').replace("'", '')
356 input_str = bleach.clean(input_str, strip=True)
356 input_str = bleach.clean(input_str, strip=True)
357 return input_str
357 return input_str
358
358
359 # populate
359 # populate
360 for uid in issuetracker_entries:
360 for uid in issuetracker_entries:
361 url_data = qs.get(self._get_keyname('url', uid, 'rhodecode_'))
361 url_data = qs.get(self._get_keyname('url', uid, 'rhodecode_'))
362
362
363 issuetracker_entries[uid] = AttributeDict({
363 issuetracker_entries[uid] = AttributeDict({
364 'pat': qs.get(
364 'pat': qs.get(
365 self._get_keyname('pat', uid, 'rhodecode_')),
365 self._get_keyname('pat', uid, 'rhodecode_')),
366 'url': url_cleaner(
366 'url': url_cleaner(
367 qs.get(self._get_keyname('url', uid, 'rhodecode_')) or ''),
367 qs.get(self._get_keyname('url', uid, 'rhodecode_')) or ''),
368 'pref': bleach.clean(
368 'pref': bleach.clean(
369 qs.get(self._get_keyname('pref', uid, 'rhodecode_')) or ''),
369 qs.get(self._get_keyname('pref', uid, 'rhodecode_')) or ''),
370 'desc': qs.get(
370 'desc': qs.get(
371 self._get_keyname('desc', uid, 'rhodecode_')),
371 self._get_keyname('desc', uid, 'rhodecode_')),
372 })
372 })
373
373
374 return issuetracker_entries
374 return issuetracker_entries
375
375
376 def get_global_settings(self, cache=False):
376 def get_global_settings(self, cache=False):
377 """
377 """
378 Returns list of global issue tracker settings
378 Returns list of global issue tracker settings
379 """
379 """
380 defaults = self.global_settings.get_all_settings(cache=cache)
380 defaults = self.global_settings.get_all_settings(cache=cache)
381 settings = self._make_dict_for_settings(defaults)
381 settings = self._make_dict_for_settings(defaults)
382 return settings
382 return settings
383
383
384 def get_repo_settings(self, cache=False):
384 def get_repo_settings(self, cache=False):
385 """
385 """
386 Returns list of issue tracker settings per repository
386 Returns list of issue tracker settings per repository
387 """
387 """
388 if not self.repo_settings:
388 if not self.repo_settings:
389 raise Exception('Repository is not specified')
389 raise Exception('Repository is not specified')
390 all_settings = self.repo_settings.get_all_settings(cache=cache)
390 all_settings = self.repo_settings.get_all_settings(cache=cache)
391 settings = self._make_dict_for_settings(all_settings)
391 settings = self._make_dict_for_settings(all_settings)
392 return settings
392 return settings
393
393
394 def get_settings(self, cache=False):
394 def get_settings(self, cache=False):
395 if self.inherit_global_settings:
395 if self.inherit_global_settings:
396 return self.get_global_settings(cache=cache)
396 return self.get_global_settings(cache=cache)
397 else:
397 else:
398 return self.get_repo_settings(cache=cache)
398 return self.get_repo_settings(cache=cache)
399
399
400 def delete_entries(self, uid):
400 def delete_entries(self, uid):
401 if self.repo_settings:
401 if self.repo_settings:
402 all_patterns = self.get_repo_settings()
402 all_patterns = self.get_repo_settings()
403 settings_model = self.repo_settings
403 settings_model = self.repo_settings
404 else:
404 else:
405 all_patterns = self.get_global_settings()
405 all_patterns = self.get_global_settings()
406 settings_model = self.global_settings
406 settings_model = self.global_settings
407 entries = all_patterns.get(uid, [])
407 entries = all_patterns.get(uid, [])
408
408
409 for del_key in entries:
409 for del_key in entries:
410 setting_name = self._get_keyname(del_key, uid)
410 setting_name = self._get_keyname(del_key, uid)
411 entry = settings_model.get_setting_by_name(setting_name)
411 entry = settings_model.get_setting_by_name(setting_name)
412 if entry:
412 if entry:
413 Session().delete(entry)
413 Session().delete(entry)
414
414
415 Session().commit()
415 Session().commit()
416
416
417 def create_or_update_setting(
417 def create_or_update_setting(
418 self, name, val=Optional(''), type_=Optional('unicode')):
418 self, name, val=Optional(''), type_=Optional('unicode')):
419 if self.repo_settings:
419 if self.repo_settings:
420 setting = self.repo_settings.create_or_update_setting(
420 setting = self.repo_settings.create_or_update_setting(
421 name, val, type_)
421 name, val, type_)
422 else:
422 else:
423 setting = self.global_settings.create_or_update_setting(
423 setting = self.global_settings.create_or_update_setting(
424 name, val, type_)
424 name, val, type_)
425 return setting
425 return setting
426
426
427
427
428 class VcsSettingsModel(object):
428 class VcsSettingsModel(object):
429
429
430 INHERIT_SETTINGS = 'inherit_vcs_settings'
430 INHERIT_SETTINGS = 'inherit_vcs_settings'
431 GENERAL_SETTINGS = (
431 GENERAL_SETTINGS = (
432 'use_outdated_comments',
432 'use_outdated_comments',
433 'pr_merge_enabled',
433 'pr_merge_enabled',
434 'hg_use_rebase_for_merging',
434 'hg_use_rebase_for_merging',
435 'hg_close_branch_before_merging',
435 'hg_close_branch_before_merging',
436 'git_use_rebase_for_merging',
436 'git_use_rebase_for_merging',
437 'git_close_branch_before_merging',
437 'git_close_branch_before_merging',
438 'diff_cache',
438 'diff_cache',
439 )
439 )
440
440
441 HOOKS_SETTINGS = (
441 HOOKS_SETTINGS = (
442 ('hooks', 'changegroup.repo_size'),
442 ('hooks', 'changegroup.repo_size'),
443 ('hooks', 'changegroup.push_logger'),
443 ('hooks', 'changegroup.push_logger'),
444 ('hooks', 'outgoing.pull_logger'),
444 ('hooks', 'outgoing.pull_logger'),
445 )
445 )
446 HG_SETTINGS = (
446 HG_SETTINGS = (
447 ('extensions', 'largefiles'),
447 ('extensions', 'largefiles'),
448 ('phases', 'publish'),
448 ('phases', 'publish'),
449 ('extensions', 'evolve'),
449 ('extensions', 'evolve'),
450 ('extensions', 'topic'),
450 ('extensions', 'topic'),
451 ('experimental', 'evolution'),
451 ('experimental', 'evolution'),
452 ('experimental', 'evolution.exchange'),
452 ('experimental', 'evolution.exchange'),
453 )
453 )
454 GIT_SETTINGS = (
454 GIT_SETTINGS = (
455 ('vcs_git_lfs', 'enabled'),
455 ('vcs_git_lfs', 'enabled'),
456 )
456 )
457 GLOBAL_HG_SETTINGS = (
457 GLOBAL_HG_SETTINGS = (
458 ('extensions', 'largefiles'),
458 ('extensions', 'largefiles'),
459 ('largefiles', 'usercache'),
459 ('largefiles', 'usercache'),
460 ('phases', 'publish'),
460 ('phases', 'publish'),
461 ('extensions', 'hgsubversion'),
461 ('extensions', 'hgsubversion'),
462 ('extensions', 'evolve'),
462 ('extensions', 'evolve'),
463 ('extensions', 'topic'),
463 ('extensions', 'topic'),
464 ('experimental', 'evolution'),
464 ('experimental', 'evolution'),
465 ('experimental', 'evolution.exchange'),
465 ('experimental', 'evolution.exchange'),
466 )
466 )
467
467
468 GLOBAL_GIT_SETTINGS = (
468 GLOBAL_GIT_SETTINGS = (
469 ('vcs_git_lfs', 'enabled'),
469 ('vcs_git_lfs', 'enabled'),
470 ('vcs_git_lfs', 'store_location')
470 ('vcs_git_lfs', 'store_location')
471 )
471 )
472
472
473 GLOBAL_SVN_SETTINGS = (
473 GLOBAL_SVN_SETTINGS = (
474 ('vcs_svn_proxy', 'http_requests_enabled'),
474 ('vcs_svn_proxy', 'http_requests_enabled'),
475 ('vcs_svn_proxy', 'http_server_url')
475 ('vcs_svn_proxy', 'http_server_url')
476 )
476 )
477
477
478 SVN_BRANCH_SECTION = 'vcs_svn_branch'
478 SVN_BRANCH_SECTION = 'vcs_svn_branch'
479 SVN_TAG_SECTION = 'vcs_svn_tag'
479 SVN_TAG_SECTION = 'vcs_svn_tag'
480 SSL_SETTING = ('web', 'push_ssl')
480 SSL_SETTING = ('web', 'push_ssl')
481 PATH_SETTING = ('paths', '/')
481 PATH_SETTING = ('paths', '/')
482
482
483 def __init__(self, sa=None, repo=None):
483 def __init__(self, sa=None, repo=None):
484 self.global_settings = SettingsModel(sa=sa)
484 self.global_settings = SettingsModel(sa=sa)
485 self.repo_settings = SettingsModel(sa=sa, repo=repo) if repo else None
485 self.repo_settings = SettingsModel(sa=sa, repo=repo) if repo else None
486 self._ui_settings = (
486 self._ui_settings = (
487 self.HG_SETTINGS + self.GIT_SETTINGS + self.HOOKS_SETTINGS)
487 self.HG_SETTINGS + self.GIT_SETTINGS + self.HOOKS_SETTINGS)
488 self._svn_sections = (self.SVN_BRANCH_SECTION, self.SVN_TAG_SECTION)
488 self._svn_sections = (self.SVN_BRANCH_SECTION, self.SVN_TAG_SECTION)
489
489
490 @property
490 @property
491 @assert_repo_settings
491 @assert_repo_settings
492 def inherit_global_settings(self):
492 def inherit_global_settings(self):
493 setting = self.repo_settings.get_setting_by_name(self.INHERIT_SETTINGS)
493 setting = self.repo_settings.get_setting_by_name(self.INHERIT_SETTINGS)
494 return setting.app_settings_value if setting else True
494 return setting.app_settings_value if setting else True
495
495
496 @inherit_global_settings.setter
496 @inherit_global_settings.setter
497 @assert_repo_settings
497 @assert_repo_settings
498 def inherit_global_settings(self, value):
498 def inherit_global_settings(self, value):
499 self.repo_settings.create_or_update_setting(
499 self.repo_settings.create_or_update_setting(
500 self.INHERIT_SETTINGS, value, type_='bool')
500 self.INHERIT_SETTINGS, value, type_='bool')
501
501
502 def get_global_svn_branch_patterns(self):
502 def get_global_svn_branch_patterns(self):
503 return self.global_settings.get_ui_by_section(self.SVN_BRANCH_SECTION)
503 return self.global_settings.get_ui_by_section(self.SVN_BRANCH_SECTION)
504
504
505 @assert_repo_settings
505 @assert_repo_settings
506 def get_repo_svn_branch_patterns(self):
506 def get_repo_svn_branch_patterns(self):
507 return self.repo_settings.get_ui_by_section(self.SVN_BRANCH_SECTION)
507 return self.repo_settings.get_ui_by_section(self.SVN_BRANCH_SECTION)
508
508
509 def get_global_svn_tag_patterns(self):
509 def get_global_svn_tag_patterns(self):
510 return self.global_settings.get_ui_by_section(self.SVN_TAG_SECTION)
510 return self.global_settings.get_ui_by_section(self.SVN_TAG_SECTION)
511
511
512 @assert_repo_settings
512 @assert_repo_settings
513 def get_repo_svn_tag_patterns(self):
513 def get_repo_svn_tag_patterns(self):
514 return self.repo_settings.get_ui_by_section(self.SVN_TAG_SECTION)
514 return self.repo_settings.get_ui_by_section(self.SVN_TAG_SECTION)
515
515
516 def get_global_settings(self):
516 def get_global_settings(self):
517 return self._collect_all_settings(global_=True)
517 return self._collect_all_settings(global_=True)
518
518
519 @assert_repo_settings
519 @assert_repo_settings
520 def get_repo_settings(self):
520 def get_repo_settings(self):
521 return self._collect_all_settings(global_=False)
521 return self._collect_all_settings(global_=False)
522
522
523 @assert_repo_settings
523 @assert_repo_settings
524 def create_or_update_repo_settings(
524 def create_or_update_repo_settings(
525 self, data, inherit_global_settings=False):
525 self, data, inherit_global_settings=False):
526 from rhodecode.model.scm import ScmModel
526 from rhodecode.model.scm import ScmModel
527
527
528 self.inherit_global_settings = inherit_global_settings
528 self.inherit_global_settings = inherit_global_settings
529
529
530 repo = self.repo_settings.get_repo()
530 repo = self.repo_settings.get_repo()
531 if not inherit_global_settings:
531 if not inherit_global_settings:
532 if repo.repo_type == 'svn':
532 if repo.repo_type == 'svn':
533 self.create_repo_svn_settings(data)
533 self.create_repo_svn_settings(data)
534 else:
534 else:
535 self.create_or_update_repo_hook_settings(data)
535 self.create_or_update_repo_hook_settings(data)
536 self.create_or_update_repo_pr_settings(data)
536 self.create_or_update_repo_pr_settings(data)
537
537
538 if repo.repo_type == 'hg':
538 if repo.repo_type == 'hg':
539 self.create_or_update_repo_hg_settings(data)
539 self.create_or_update_repo_hg_settings(data)
540
540
541 if repo.repo_type == 'git':
541 if repo.repo_type == 'git':
542 self.create_or_update_repo_git_settings(data)
542 self.create_or_update_repo_git_settings(data)
543
543
544 ScmModel().mark_for_invalidation(repo.repo_name, delete=True)
544 ScmModel().mark_for_invalidation(repo.repo_name, delete=True)
545
545
546 @assert_repo_settings
546 @assert_repo_settings
547 def create_or_update_repo_hook_settings(self, data):
547 def create_or_update_repo_hook_settings(self, data):
548 for section, key in self.HOOKS_SETTINGS:
548 for section, key in self.HOOKS_SETTINGS:
549 data_key = self._get_form_ui_key(section, key)
549 data_key = self._get_form_ui_key(section, key)
550 if data_key not in data:
550 if data_key not in data:
551 raise ValueError(
551 raise ValueError(
552 'The given data does not contain {} key'.format(data_key))
552 'The given data does not contain {} key'.format(data_key))
553
553
554 active = data.get(data_key)
554 active = data.get(data_key)
555 repo_setting = self.repo_settings.get_ui_by_section_and_key(
555 repo_setting = self.repo_settings.get_ui_by_section_and_key(
556 section, key)
556 section, key)
557 if not repo_setting:
557 if not repo_setting:
558 global_setting = self.global_settings.\
558 global_setting = self.global_settings.\
559 get_ui_by_section_and_key(section, key)
559 get_ui_by_section_and_key(section, key)
560 self.repo_settings.create_ui_section_value(
560 self.repo_settings.create_ui_section_value(
561 section, global_setting.ui_value, key=key, active=active)
561 section, global_setting.ui_value, key=key, active=active)
562 else:
562 else:
563 repo_setting.ui_active = active
563 repo_setting.ui_active = active
564 Session().add(repo_setting)
564 Session().add(repo_setting)
565
565
566 def update_global_hook_settings(self, data):
566 def update_global_hook_settings(self, data):
567 for section, key in self.HOOKS_SETTINGS:
567 for section, key in self.HOOKS_SETTINGS:
568 data_key = self._get_form_ui_key(section, key)
568 data_key = self._get_form_ui_key(section, key)
569 if data_key not in data:
569 if data_key not in data:
570 raise ValueError(
570 raise ValueError(
571 'The given data does not contain {} key'.format(data_key))
571 'The given data does not contain {} key'.format(data_key))
572 active = data.get(data_key)
572 active = data.get(data_key)
573 repo_setting = self.global_settings.get_ui_by_section_and_key(
573 repo_setting = self.global_settings.get_ui_by_section_and_key(
574 section, key)
574 section, key)
575 repo_setting.ui_active = active
575 repo_setting.ui_active = active
576 Session().add(repo_setting)
576 Session().add(repo_setting)
577
577
578 @assert_repo_settings
578 @assert_repo_settings
579 def create_or_update_repo_pr_settings(self, data):
579 def create_or_update_repo_pr_settings(self, data):
580 return self._create_or_update_general_settings(
580 return self._create_or_update_general_settings(
581 self.repo_settings, data)
581 self.repo_settings, data)
582
582
583 def create_or_update_global_pr_settings(self, data):
583 def create_or_update_global_pr_settings(self, data):
584 return self._create_or_update_general_settings(
584 return self._create_or_update_general_settings(
585 self.global_settings, data)
585 self.global_settings, data)
586
586
587 @assert_repo_settings
587 @assert_repo_settings
588 def create_repo_svn_settings(self, data):
588 def create_repo_svn_settings(self, data):
589 return self._create_svn_settings(self.repo_settings, data)
589 return self._create_svn_settings(self.repo_settings, data)
590
590
591 def _set_evolution(self, settings, is_enabled):
591 def _set_evolution(self, settings, is_enabled):
592 if is_enabled:
592 if is_enabled:
593 # if evolve is active set evolution=all
593 # if evolve is active set evolution=all
594
594
595 self._create_or_update_ui(
595 self._create_or_update_ui(
596 settings, *('experimental', 'evolution'), value='all',
596 settings, *('experimental', 'evolution'), value='all',
597 active=True)
597 active=True)
598 self._create_or_update_ui(
598 self._create_or_update_ui(
599 settings, *('experimental', 'evolution.exchange'), value='yes',
599 settings, *('experimental', 'evolution.exchange'), value='yes',
600 active=True)
600 active=True)
601 # if evolve is active set topics server support
601 # if evolve is active set topics server support
602 self._create_or_update_ui(
602 self._create_or_update_ui(
603 settings, *('extensions', 'topic'), value='',
603 settings, *('extensions', 'topic'), value='',
604 active=True)
604 active=True)
605
605
606 else:
606 else:
607 self._create_or_update_ui(
607 self._create_or_update_ui(
608 settings, *('experimental', 'evolution'), value='',
608 settings, *('experimental', 'evolution'), value='',
609 active=False)
609 active=False)
610 self._create_or_update_ui(
610 self._create_or_update_ui(
611 settings, *('experimental', 'evolution.exchange'), value='no',
611 settings, *('experimental', 'evolution.exchange'), value='no',
612 active=False)
612 active=False)
613 self._create_or_update_ui(
613 self._create_or_update_ui(
614 settings, *('extensions', 'topic'), value='',
614 settings, *('extensions', 'topic'), value='',
615 active=False)
615 active=False)
616
616
617 @assert_repo_settings
617 @assert_repo_settings
618 def create_or_update_repo_hg_settings(self, data):
618 def create_or_update_repo_hg_settings(self, data):
619 largefiles, phases, evolve = \
619 largefiles, phases, evolve = \
620 self.HG_SETTINGS[:3]
620 self.HG_SETTINGS[:3]
621 largefiles_key, phases_key, evolve_key = \
621 largefiles_key, phases_key, evolve_key = \
622 self._get_settings_keys(self.HG_SETTINGS[:3], data)
622 self._get_settings_keys(self.HG_SETTINGS[:3], data)
623
623
624 self._create_or_update_ui(
624 self._create_or_update_ui(
625 self.repo_settings, *largefiles, value='',
625 self.repo_settings, *largefiles, value='',
626 active=data[largefiles_key])
626 active=data[largefiles_key])
627 self._create_or_update_ui(
627 self._create_or_update_ui(
628 self.repo_settings, *evolve, value='',
628 self.repo_settings, *evolve, value='',
629 active=data[evolve_key])
629 active=data[evolve_key])
630 self._set_evolution(self.repo_settings, is_enabled=data[evolve_key])
630 self._set_evolution(self.repo_settings, is_enabled=data[evolve_key])
631
631
632 self._create_or_update_ui(
632 self._create_or_update_ui(
633 self.repo_settings, *phases, value=safe_str(data[phases_key]))
633 self.repo_settings, *phases, value=safe_str(data[phases_key]))
634
634
635 def create_or_update_global_hg_settings(self, data):
635 def create_or_update_global_hg_settings(self, data):
636 largefiles, largefiles_store, phases, hgsubversion, evolve \
636 largefiles, largefiles_store, phases, hgsubversion, evolve \
637 = self.GLOBAL_HG_SETTINGS[:5]
637 = self.GLOBAL_HG_SETTINGS[:5]
638 largefiles_key, largefiles_store_key, phases_key, subversion_key, evolve_key \
638 largefiles_key, largefiles_store_key, phases_key, subversion_key, evolve_key \
639 = self._get_settings_keys(self.GLOBAL_HG_SETTINGS[:5], data)
639 = self._get_settings_keys(self.GLOBAL_HG_SETTINGS[:5], data)
640
640
641 self._create_or_update_ui(
641 self._create_or_update_ui(
642 self.global_settings, *largefiles, value='',
642 self.global_settings, *largefiles, value='',
643 active=data[largefiles_key])
643 active=data[largefiles_key])
644 self._create_or_update_ui(
644 self._create_or_update_ui(
645 self.global_settings, *largefiles_store, value=data[largefiles_store_key])
645 self.global_settings, *largefiles_store, value=data[largefiles_store_key])
646 self._create_or_update_ui(
646 self._create_or_update_ui(
647 self.global_settings, *phases, value=safe_str(data[phases_key]))
647 self.global_settings, *phases, value=safe_str(data[phases_key]))
648 self._create_or_update_ui(
648 self._create_or_update_ui(
649 self.global_settings, *hgsubversion, active=data[subversion_key])
649 self.global_settings, *hgsubversion, active=data[subversion_key])
650 self._create_or_update_ui(
650 self._create_or_update_ui(
651 self.global_settings, *evolve, value='',
651 self.global_settings, *evolve, value='',
652 active=data[evolve_key])
652 active=data[evolve_key])
653 self._set_evolution(self.global_settings, is_enabled=data[evolve_key])
653 self._set_evolution(self.global_settings, is_enabled=data[evolve_key])
654
654
655 def create_or_update_repo_git_settings(self, data):
655 def create_or_update_repo_git_settings(self, data):
656 # NOTE(marcink): # comma makes unpack work properly
656 # NOTE(marcink): # comma makes unpack work properly
657 lfs_enabled, \
657 lfs_enabled, \
658 = self.GIT_SETTINGS
658 = self.GIT_SETTINGS
659
659
660 lfs_enabled_key, \
660 lfs_enabled_key, \
661 = self._get_settings_keys(self.GIT_SETTINGS, data)
661 = self._get_settings_keys(self.GIT_SETTINGS, data)
662
662
663 self._create_or_update_ui(
663 self._create_or_update_ui(
664 self.repo_settings, *lfs_enabled, value=data[lfs_enabled_key],
664 self.repo_settings, *lfs_enabled, value=data[lfs_enabled_key],
665 active=data[lfs_enabled_key])
665 active=data[lfs_enabled_key])
666
666
667 def create_or_update_global_git_settings(self, data):
667 def create_or_update_global_git_settings(self, data):
668 lfs_enabled, lfs_store_location \
668 lfs_enabled, lfs_store_location \
669 = self.GLOBAL_GIT_SETTINGS
669 = self.GLOBAL_GIT_SETTINGS
670 lfs_enabled_key, lfs_store_location_key \
670 lfs_enabled_key, lfs_store_location_key \
671 = self._get_settings_keys(self.GLOBAL_GIT_SETTINGS, data)
671 = self._get_settings_keys(self.GLOBAL_GIT_SETTINGS, data)
672
672
673 self._create_or_update_ui(
673 self._create_or_update_ui(
674 self.global_settings, *lfs_enabled, value=data[lfs_enabled_key],
674 self.global_settings, *lfs_enabled, value=data[lfs_enabled_key],
675 active=data[lfs_enabled_key])
675 active=data[lfs_enabled_key])
676 self._create_or_update_ui(
676 self._create_or_update_ui(
677 self.global_settings, *lfs_store_location,
677 self.global_settings, *lfs_store_location,
678 value=data[lfs_store_location_key])
678 value=data[lfs_store_location_key])
679
679
680 def create_or_update_global_svn_settings(self, data):
680 def create_or_update_global_svn_settings(self, data):
681 # branch/tags patterns
681 # branch/tags patterns
682 self._create_svn_settings(self.global_settings, data)
682 self._create_svn_settings(self.global_settings, data)
683
683
684 http_requests_enabled, http_server_url = self.GLOBAL_SVN_SETTINGS
684 http_requests_enabled, http_server_url = self.GLOBAL_SVN_SETTINGS
685 http_requests_enabled_key, http_server_url_key = self._get_settings_keys(
685 http_requests_enabled_key, http_server_url_key = self._get_settings_keys(
686 self.GLOBAL_SVN_SETTINGS, data)
686 self.GLOBAL_SVN_SETTINGS, data)
687
687
688 self._create_or_update_ui(
688 self._create_or_update_ui(
689 self.global_settings, *http_requests_enabled,
689 self.global_settings, *http_requests_enabled,
690 value=safe_str(data[http_requests_enabled_key]))
690 value=safe_str(data[http_requests_enabled_key]))
691 self._create_or_update_ui(
691 self._create_or_update_ui(
692 self.global_settings, *http_server_url,
692 self.global_settings, *http_server_url,
693 value=data[http_server_url_key])
693 value=data[http_server_url_key])
694
694
695 def update_global_ssl_setting(self, value):
695 def update_global_ssl_setting(self, value):
696 self._create_or_update_ui(
696 self._create_or_update_ui(
697 self.global_settings, *self.SSL_SETTING, value=value)
697 self.global_settings, *self.SSL_SETTING, value=value)
698
698
699 def update_global_path_setting(self, value):
699 def update_global_path_setting(self, value):
700 self._create_or_update_ui(
700 self._create_or_update_ui(
701 self.global_settings, *self.PATH_SETTING, value=value)
701 self.global_settings, *self.PATH_SETTING, value=value)
702
702
703 @assert_repo_settings
703 @assert_repo_settings
704 def delete_repo_svn_pattern(self, id_):
704 def delete_repo_svn_pattern(self, id_):
705 ui = self.repo_settings.UiDbModel.get(id_)
705 ui = self.repo_settings.UiDbModel.get(id_)
706 if ui and ui.repository.repo_name == self.repo_settings.repo:
706 if ui and ui.repository.repo_name == self.repo_settings.repo:
707 # only delete if it's the same repo as initialized settings
707 # only delete if it's the same repo as initialized settings
708 self.repo_settings.delete_ui(id_)
708 self.repo_settings.delete_ui(id_)
709 else:
709 else:
710 # raise error as if we wouldn't find this option
710 # raise error as if we wouldn't find this option
711 self.repo_settings.delete_ui(-1)
711 self.repo_settings.delete_ui(-1)
712
712
713 def delete_global_svn_pattern(self, id_):
713 def delete_global_svn_pattern(self, id_):
714 self.global_settings.delete_ui(id_)
714 self.global_settings.delete_ui(id_)
715
715
716 @assert_repo_settings
716 @assert_repo_settings
717 def get_repo_ui_settings(self, section=None, key=None):
717 def get_repo_ui_settings(self, section=None, key=None):
718 global_uis = self.global_settings.get_ui(section, key)
718 global_uis = self.global_settings.get_ui(section, key)
719 repo_uis = self.repo_settings.get_ui(section, key)
719 repo_uis = self.repo_settings.get_ui(section, key)
720
720
721 filtered_repo_uis = self._filter_ui_settings(repo_uis)
721 filtered_repo_uis = self._filter_ui_settings(repo_uis)
722 filtered_repo_uis_keys = [
722 filtered_repo_uis_keys = [
723 (s.section, s.key) for s in filtered_repo_uis]
723 (s.section, s.key) for s in filtered_repo_uis]
724
724
725 def _is_global_ui_filtered(ui):
725 def _is_global_ui_filtered(ui):
726 return (
726 return (
727 (ui.section, ui.key) in filtered_repo_uis_keys
727 (ui.section, ui.key) in filtered_repo_uis_keys
728 or ui.section in self._svn_sections)
728 or ui.section in self._svn_sections)
729
729
730 filtered_global_uis = [
730 filtered_global_uis = [
731 ui for ui in global_uis if not _is_global_ui_filtered(ui)]
731 ui for ui in global_uis if not _is_global_ui_filtered(ui)]
732
732
733 return filtered_global_uis + filtered_repo_uis
733 return filtered_global_uis + filtered_repo_uis
734
734
735 def get_global_ui_settings(self, section=None, key=None):
735 def get_global_ui_settings(self, section=None, key=None):
736 return self.global_settings.get_ui(section, key)
736 return self.global_settings.get_ui(section, key)
737
737
738 def get_ui_settings_as_config_obj(self, section=None, key=None):
738 def get_ui_settings_as_config_obj(self, section=None, key=None):
739 config = base.Config()
739 config = base.Config()
740
740
741 ui_settings = self.get_ui_settings(section=section, key=key)
741 ui_settings = self.get_ui_settings(section=section, key=key)
742
742
743 for entry in ui_settings:
743 for entry in ui_settings:
744 config.set(entry.section, entry.key, entry.value)
744 config.set(entry.section, entry.key, entry.value)
745
745
746 return config
746 return config
747
747
748 def get_ui_settings(self, section=None, key=None):
748 def get_ui_settings(self, section=None, key=None):
749 if not self.repo_settings or self.inherit_global_settings:
749 if not self.repo_settings or self.inherit_global_settings:
750 return self.get_global_ui_settings(section, key)
750 return self.get_global_ui_settings(section, key)
751 else:
751 else:
752 return self.get_repo_ui_settings(section, key)
752 return self.get_repo_ui_settings(section, key)
753
753
754 def get_svn_patterns(self, section=None):
754 def get_svn_patterns(self, section=None):
755 if not self.repo_settings:
755 if not self.repo_settings:
756 return self.get_global_ui_settings(section)
756 return self.get_global_ui_settings(section)
757 else:
757 else:
758 return self.get_repo_ui_settings(section)
758 return self.get_repo_ui_settings(section)
759
759
760 @assert_repo_settings
760 @assert_repo_settings
761 def get_repo_general_settings(self):
761 def get_repo_general_settings(self):
762 global_settings = self.global_settings.get_all_settings()
762 global_settings = self.global_settings.get_all_settings()
763 repo_settings = self.repo_settings.get_all_settings()
763 repo_settings = self.repo_settings.get_all_settings()
764 filtered_repo_settings = self._filter_general_settings(repo_settings)
764 filtered_repo_settings = self._filter_general_settings(repo_settings)
765 global_settings.update(filtered_repo_settings)
765 global_settings.update(filtered_repo_settings)
766 return global_settings
766 return global_settings
767
767
768 def get_global_general_settings(self):
768 def get_global_general_settings(self):
769 return self.global_settings.get_all_settings()
769 return self.global_settings.get_all_settings()
770
770
771 def get_general_settings(self):
771 def get_general_settings(self):
772 if not self.repo_settings or self.inherit_global_settings:
772 if not self.repo_settings or self.inherit_global_settings:
773 return self.get_global_general_settings()
773 return self.get_global_general_settings()
774 else:
774 else:
775 return self.get_repo_general_settings()
775 return self.get_repo_general_settings()
776
776
777 def get_repos_location(self):
777 def get_repos_location(self):
778 return self.global_settings.get_ui_by_key('/').ui_value
778 return self.global_settings.get_ui_by_key('/').ui_value
779
779
780 def _filter_ui_settings(self, settings):
780 def _filter_ui_settings(self, settings):
781 filtered_settings = [
781 filtered_settings = [
782 s for s in settings if self._should_keep_setting(s)]
782 s for s in settings if self._should_keep_setting(s)]
783 return filtered_settings
783 return filtered_settings
784
784
785 def _should_keep_setting(self, setting):
785 def _should_keep_setting(self, setting):
786 keep = (
786 keep = (
787 (setting.section, setting.key) in self._ui_settings or
787 (setting.section, setting.key) in self._ui_settings or
788 setting.section in self._svn_sections)
788 setting.section in self._svn_sections)
789 return keep
789 return keep
790
790
791 def _filter_general_settings(self, settings):
791 def _filter_general_settings(self, settings):
792 keys = ['rhodecode_{}'.format(key) for key in self.GENERAL_SETTINGS]
792 keys = ['rhodecode_{}'.format(key) for key in self.GENERAL_SETTINGS]
793 return {
793 return {
794 k: settings[k]
794 k: settings[k]
795 for k in settings if k in keys}
795 for k in settings if k in keys}
796
796
797 def _collect_all_settings(self, global_=False):
797 def _collect_all_settings(self, global_=False):
798 settings = self.global_settings if global_ else self.repo_settings
798 settings = self.global_settings if global_ else self.repo_settings
799 result = {}
799 result = {}
800
800
801 for section, key in self._ui_settings:
801 for section, key in self._ui_settings:
802 ui = settings.get_ui_by_section_and_key(section, key)
802 ui = settings.get_ui_by_section_and_key(section, key)
803 result_key = self._get_form_ui_key(section, key)
803 result_key = self._get_form_ui_key(section, key)
804
804
805 if ui:
805 if ui:
806 if section in ('hooks', 'extensions'):
806 if section in ('hooks', 'extensions'):
807 result[result_key] = ui.ui_active
807 result[result_key] = ui.ui_active
808 elif result_key in ['vcs_git_lfs_enabled']:
808 elif result_key in ['vcs_git_lfs_enabled']:
809 result[result_key] = ui.ui_active
809 result[result_key] = ui.ui_active
810 else:
810 else:
811 result[result_key] = ui.ui_value
811 result[result_key] = ui.ui_value
812
812
813 for name in self.GENERAL_SETTINGS:
813 for name in self.GENERAL_SETTINGS:
814 setting = settings.get_setting_by_name(name)
814 setting = settings.get_setting_by_name(name)
815 if setting:
815 if setting:
816 result_key = 'rhodecode_{}'.format(name)
816 result_key = 'rhodecode_{}'.format(name)
817 result[result_key] = setting.app_settings_value
817 result[result_key] = setting.app_settings_value
818
818
819 return result
819 return result
820
820
821 def _get_form_ui_key(self, section, key):
821 def _get_form_ui_key(self, section, key):
822 return '{section}_{key}'.format(
822 return '{section}_{key}'.format(
823 section=section, key=key.replace('.', '_'))
823 section=section, key=key.replace('.', '_'))
824
824
825 def _create_or_update_ui(
825 def _create_or_update_ui(
826 self, settings, section, key, value=None, active=None):
826 self, settings, section, key, value=None, active=None):
827 ui = settings.get_ui_by_section_and_key(section, key)
827 ui = settings.get_ui_by_section_and_key(section, key)
828 if not ui:
828 if not ui:
829 active = True if active is None else active
829 active = True if active is None else active
830 settings.create_ui_section_value(
830 settings.create_ui_section_value(
831 section, value, key=key, active=active)
831 section, value, key=key, active=active)
832 else:
832 else:
833 if active is not None:
833 if active is not None:
834 ui.ui_active = active
834 ui.ui_active = active
835 if value is not None:
835 if value is not None:
836 ui.ui_value = value
836 ui.ui_value = value
837 Session().add(ui)
837 Session().add(ui)
838
838
839 def _create_svn_settings(self, settings, data):
839 def _create_svn_settings(self, settings, data):
840 svn_settings = {
840 svn_settings = {
841 'new_svn_branch': self.SVN_BRANCH_SECTION,
841 'new_svn_branch': self.SVN_BRANCH_SECTION,
842 'new_svn_tag': self.SVN_TAG_SECTION
842 'new_svn_tag': self.SVN_TAG_SECTION
843 }
843 }
844 for key in svn_settings:
844 for key in svn_settings:
845 if data.get(key):
845 if data.get(key):
846 settings.create_ui_section_value(svn_settings[key], data[key])
846 settings.create_ui_section_value(svn_settings[key], data[key])
847
847
848 def _create_or_update_general_settings(self, settings, data):
848 def _create_or_update_general_settings(self, settings, data):
849 for name in self.GENERAL_SETTINGS:
849 for name in self.GENERAL_SETTINGS:
850 data_key = 'rhodecode_{}'.format(name)
850 data_key = 'rhodecode_{}'.format(name)
851 if data_key not in data:
851 if data_key not in data:
852 raise ValueError(
852 raise ValueError(
853 'The given data does not contain {} key'.format(data_key))
853 'The given data does not contain {} key'.format(data_key))
854 setting = settings.create_or_update_setting(
854 setting = settings.create_or_update_setting(
855 name, data[data_key], 'bool')
855 name, data[data_key], 'bool')
856 Session().add(setting)
856 Session().add(setting)
857
857
858 def _get_settings_keys(self, settings, data):
858 def _get_settings_keys(self, settings, data):
859 data_keys = [self._get_form_ui_key(*s) for s in settings]
859 data_keys = [self._get_form_ui_key(*s) for s in settings]
860 for data_key in data_keys:
860 for data_key in data_keys:
861 if data_key not in data:
861 if data_key not in data:
862 raise ValueError(
862 raise ValueError(
863 'The given data does not contain {} key'.format(data_key))
863 'The given data does not contain {} key'.format(data_key))
864 return data_keys
864 return data_keys
865
865
866 def create_largeobjects_dirs_if_needed(self, repo_store_path):
866 def create_largeobjects_dirs_if_needed(self, repo_store_path):
867 """
867 """
868 This is subscribed to the `pyramid.events.ApplicationCreated` event. It
868 This is subscribed to the `pyramid.events.ApplicationCreated` event. It
869 does a repository scan if enabled in the settings.
869 does a repository scan if enabled in the settings.
870 """
870 """
871
871
872 from rhodecode.lib.vcs.backends.hg import largefiles_store
872 from rhodecode.lib.vcs.backends.hg import largefiles_store
873 from rhodecode.lib.vcs.backends.git import lfs_store
873 from rhodecode.lib.vcs.backends.git import lfs_store
874
874
875 paths = [
875 paths = [
876 largefiles_store(repo_store_path),
876 largefiles_store(repo_store_path),
877 lfs_store(repo_store_path)]
877 lfs_store(repo_store_path)]
878
878
879 for path in paths:
879 for path in paths:
880 if os.path.isdir(path):
880 if os.path.isdir(path):
881 continue
881 continue
882 if os.path.isfile(path):
882 if os.path.isfile(path):
883 continue
883 continue
884 # not a file nor dir, we try to create it
884 # not a file nor dir, we try to create it
885 try:
885 try:
886 os.makedirs(path)
886 os.makedirs(path)
887 except Exception:
887 except Exception:
888 log.warning('Failed to create largefiles dir:%s', path)
888 log.warning('Failed to create largefiles dir:%s', path)
@@ -1,73 +1,73 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import timeit
21 import timeit
22 import logging
22 import logging
23 import click
23 import click
24
24
25 log = logging.getLogger(__name__)
25 log = logging.getLogger(__name__)
26
26
27
27
28 @click.command()
28 @click.command()
29 @click.option('--server', help='Server url to connect to. e.g http://rc.local.com', required=True)
29 @click.option('--server', help='Server url to connect to. e.g http://rc.local.com', required=True)
30 @click.option('--pages', help='load pages to visit from a file', required=True, type=click.File())
30 @click.option('--pages', help='load pages to visit from a file', required=True, type=click.File())
31 @click.option('--repeat', help='number of times to repeat', default=10, type=int)
31 @click.option('--repeat', help='number of times to repeat', default=10, type=int)
32 def main(server, repeat, pages):
32 def main(server, repeat, pages):
33
33
34 print("Repeating each URL %d times\n" % repeat)
34 print("Repeating each URL %d times\n" % repeat)
35 pages = pages.readlines()
35 pages = pages.readlines()
36
36
37 for page_url in pages:
37 for page_url in pages:
38
38
39 url = "%s/%s" % (server, page_url.strip())
39 url = "%s/%s" % (server, page_url.strip())
40 print(url)
40 print(url)
41
41
42 stmt = "requests.get('%s', timeout=120)" % url
42 stmt = "requests.get('%s', timeout=120)" % url
43 t = timeit.Timer(stmt=stmt, setup="import requests")
43 t = timeit.Timer(stmt=stmt, setup="import requests")
44
44
45 result = t.repeat(repeat=repeat, number=1)
45 result = t.repeat(repeat=repeat, number=1)
46 print(" %.3f (min) - %.3f (max) - %.3f (avg)\n" %
46 print(" %.4f (min) - %.4f (max) - %.4f (avg)\n" %
47 (min(result), max(result), sum(result) / len(result)))
47 (min(result), max(result), sum(result) / len(result)))
48
48
49
49
50 if __name__ == '__main__':
50 if __name__ == '__main__':
51 main()
51 main()
52
52
53
53
54
54
55
55
56
56
57
57
58
58
59
59
60
60
61
61
62
62
63
63
64
64
65
65
66
66
67
67
68
68
69
69
70
70
71
71
72
72
73
73
@@ -1,203 +1,203 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2019 RhodeCode GmbH
3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Test suite for making push/pull operations
22 Test suite for making push/pull operations
23 """
23 """
24
24
25 import os
25 import os
26 import sys
26 import sys
27 import shutil
27 import shutil
28 import logging
28 import logging
29 from os.path import join as jn
29 from os.path import join as jn
30 from os.path import dirname as dn
30 from os.path import dirname as dn
31
31
32 from tempfile import _RandomNameSequence
32 from tempfile import _RandomNameSequence
33 from subprocess32 import Popen, PIPE
33 from subprocess32 import Popen, PIPE
34
34
35 from rhodecode.lib.utils2 import engine_from_config
35 from rhodecode.lib.utils2 import engine_from_config
36 from rhodecode.lib.auth import get_crypt_password
36 from rhodecode.lib.auth import get_crypt_password
37 from rhodecode.model import init_model
37 from rhodecode.model import init_model
38 from rhodecode.model import meta
38 from rhodecode.model import meta
39 from rhodecode.model.db import User, Repository
39 from rhodecode.model.db import User, Repository
40
40
41 from rhodecode.tests import TESTS_TMP_PATH, HG_REPO
41 from rhodecode.tests import TESTS_TMP_PATH, HG_REPO
42
42
43 rel_path = dn(dn(dn(dn(os.path.abspath(__file__)))))
43 rel_path = dn(dn(dn(dn(os.path.abspath(__file__)))))
44
44
45
45
46 USER = 'test_admin'
46 USER = 'test_admin'
47 PASS = 'test12'
47 PASS = 'test12'
48 HOST = 'rc.local'
48 HOST = 'rc.local'
49 METHOD = 'pull'
49 METHOD = 'pull'
50 DEBUG = True
50 DEBUG = True
51 log = logging.getLogger(__name__)
51 log = logging.getLogger(__name__)
52
52
53
53
54 class Command(object):
54 class Command(object):
55
55
56 def __init__(self, cwd):
56 def __init__(self, cwd):
57 self.cwd = cwd
57 self.cwd = cwd
58
58
59 def execute(self, cmd, *args):
59 def execute(self, cmd, *args):
60 """Runs command on the system with given ``args``.
60 """Runs command on the system with given ``args``.
61 """
61 """
62
62
63 command = cmd + ' ' + ' '.join(args)
63 command = cmd + ' ' + ' '.join(args)
64 log.debug('Executing %s', command)
64 log.debug('Executing %s', command)
65 if DEBUG:
65 if DEBUG:
66 print(command)
66 print(command)
67 p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.cwd)
67 p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE, cwd=self.cwd)
68 stdout, stderr = p.communicate()
68 stdout, stderr = p.communicate()
69 if DEBUG:
69 if DEBUG:
70 print('{} {}'.format(stdout, stderr))
70 print('{} {}'.format(stdout, stderr))
71 return stdout, stderr
71 return stdout, stderr
72
72
73
73
74 def get_session():
74 def get_session():
75 conf = {}
75 conf = {}
76 engine = engine_from_config(conf, 'sqlalchemy.db1.')
76 engine = engine_from_config(conf, 'sqlalchemy.db1.')
77 init_model(engine)
77 init_model(engine)
78 sa = meta.Session
78 sa = meta.Session
79 return sa
79 return sa
80
80
81
81
82 def create_test_user(force=True):
82 def create_test_user(force=True):
83 print('creating test user')
83 print('creating test user')
84 sa = get_session()
84 sa = get_session()
85
85
86 user = sa.query(User).filter(User.username == USER).scalar()
86 user = sa.query(User).filter(User.username == USER).scalar()
87
87
88 if force and user is not None:
88 if force and user is not None:
89 print('removing current user')
89 print('removing current user')
90 for repo in sa.query(Repository).filter(Repository.user == user).all():
90 for repo in sa.query(Repository).filter(Repository.user == user).all():
91 sa.delete(repo)
91 sa.delete(repo)
92 sa.delete(user)
92 sa.delete(user)
93 sa.commit()
93 sa.commit()
94
94
95 if user is None or force:
95 if user is None or force:
96 print('creating new one')
96 print('creating new one')
97 new_usr = User()
97 new_usr = User()
98 new_usr.username = USER
98 new_usr.username = USER
99 new_usr.password = get_crypt_password(PASS)
99 new_usr.password = get_crypt_password(PASS)
100 new_usr.email = 'mail@mail.com'
100 new_usr.email = 'mail@mail.com'
101 new_usr.name = 'test'
101 new_usr.name = 'test'
102 new_usr.lastname = 'lasttestname'
102 new_usr.lastname = 'lasttestname'
103 new_usr.active = True
103 new_usr.active = True
104 new_usr.admin = True
104 new_usr.admin = True
105 sa.add(new_usr)
105 sa.add(new_usr)
106 sa.commit()
106 sa.commit()
107
107
108 print('done')
108 print('done')
109
109
110
110
111 def create_test_repo(force=True):
111 def create_test_repo(force=True):
112 print('creating test repo')
112 print('creating test repo')
113 from rhodecode.model.repo import RepoModel
113 from rhodecode.model.repo import RepoModel
114 sa = get_session()
114 sa = get_session()
115
115
116 user = sa.query(User).filter(User.username == USER).scalar()
116 user = sa.query(User).filter(User.username == USER).scalar()
117 if user is None:
117 if user is None:
118 raise Exception('user not found')
118 raise Exception('user not found')
119
119
120 repo = sa.query(Repository).filter(Repository.repo_name == HG_REPO).scalar()
120 repo = sa.query(Repository).filter(Repository.repo_name == HG_REPO).scalar()
121
121
122 if repo is None:
122 if repo is None:
123 print('repo not found creating')
123 print('repo not found creating')
124
124
125 form_data = {'repo_name': HG_REPO,
125 form_data = {'repo_name': HG_REPO,
126 'repo_type': 'hg',
126 'repo_type': 'hg',
127 'private':False,
127 'private':False,
128 'clone_uri': '' }
128 'clone_uri': '' }
129 rm = RepoModel(sa)
129 rm = RepoModel(sa)
130 rm.base_path = '/home/hg'
130 rm.base_path = '/home/hg'
131 rm.create(form_data, user)
131 rm.create(form_data, user)
132
132
133 print('done')
133 print('done')
134
134
135
135
136 def get_anonymous_access():
136 def get_anonymous_access():
137 sa = get_session()
137 sa = get_session()
138 return sa.query(User).filter(User.username == 'default').one().active
138 return sa.query(User).filter(User.username == 'default').one().active
139
139
140
140
141 #==============================================================================
141 #==============================================================================
142 # TESTS
142 # TESTS
143 #==============================================================================
143 #==============================================================================
144 def test_clone_with_credentials(repo=HG_REPO, method=METHOD,
144 def test_clone_with_credentials(repo=HG_REPO, method=METHOD,
145 seq=None, backend='hg', check_output=True):
145 seq=None, backend='hg', check_output=True):
146 cwd = path = jn(TESTS_TMP_PATH, repo)
146 cwd = path = jn(TESTS_TMP_PATH, repo)
147
147
148 if seq is None:
148 if seq is None:
149 seq = _RandomNameSequence().next()
149 seq = _RandomNameSequence().next()
150
150
151 try:
151 try:
152 shutil.rmtree(path, ignore_errors=True)
152 shutil.rmtree(path, ignore_errors=True)
153 os.makedirs(path)
153 os.makedirs(path)
154 except OSError:
154 except OSError:
155 raise
155 raise
156
156
157 clone_url = 'http://%(user)s:%(pass)s@%(host)s/%(cloned_repo)s' % \
157 clone_url = 'http://%(user)s:%(pass)s@%(host)s/%(cloned_repo)s' % \
158 {'user': USER,
158 {'user': USER,
159 'pass': PASS,
159 'pass': PASS,
160 'host': HOST,
160 'host': HOST,
161 'cloned_repo': repo, }
161 'cloned_repo': repo, }
162
162
163 dest = path + seq
163 dest = path + seq
164 if method == 'pull':
164 if method == 'pull':
165 stdout, stderr = Command(cwd).execute(backend, method, '--cwd', dest, clone_url)
165 stdout, stderr = Command(cwd).execute(backend, method, '--cwd', dest, clone_url)
166 else:
166 else:
167 stdout, stderr = Command(cwd).execute(backend, method, clone_url, dest)
167 stdout, stderr = Command(cwd).execute(backend, method, clone_url, dest)
168 if check_output:
168 if check_output:
169 if backend == 'hg':
169 if backend == 'hg':
170 assert """adding file changes""" in stdout, 'no messages about cloning'
170 assert """adding file changes""" in stdout, 'no messages about cloning'
171 assert """abort""" not in stderr, 'got error from clone'
171 assert """abort""" not in stderr, 'got error from clone'
172 elif backend == 'git':
172 elif backend == 'git':
173 assert """Cloning into""" in stdout, 'no messages about cloning'
173 assert """Cloning into""" in stdout, 'no messages about cloning'
174
174
175
175
176 if __name__ == '__main__':
176 if __name__ == '__main__':
177 try:
177 try:
178 create_test_user(force=False)
178 create_test_user(force=False)
179 seq = None
179 seq = None
180 import time
180 import time
181
181
182 try:
182 try:
183 METHOD = sys.argv[3]
183 METHOD = sys.argv[3]
184 except Exception:
184 except Exception:
185 pass
185 pass
186
186
187 try:
187 try:
188 backend = sys.argv[4]
188 backend = sys.argv[4]
189 except Exception:
189 except Exception:
190 backend = 'hg'
190 backend = 'hg'
191
191
192 if METHOD == 'pull':
192 if METHOD == 'pull':
193 seq = _RandomNameSequence().next()
193 seq = _RandomNameSequence().next()
194 test_clone_with_credentials(repo=sys.argv[1], method='clone',
194 test_clone_with_credentials(repo=sys.argv[1], method='clone',
195 seq=seq, backend=backend)
195 seq=seq, backend=backend)
196 s = time.time()
196 s = time.time()
197 for i in range(1, int(sys.argv[2]) + 1):
197 for i in range(1, int(sys.argv[2]) + 1):
198 print('take {}'.format(i))
198 print('take {}'.format(i))
199 test_clone_with_credentials(repo=sys.argv[1], method=METHOD,
199 test_clone_with_credentials(repo=sys.argv[1], method=METHOD,
200 seq=seq, backend=backend)
200 seq=seq, backend=backend)
201 print('time taken %.3f' % (time.time() - s))
201 print('time taken %.4f' % (time.time() - s))
202 except Exception as e:
202 except Exception as e:
203 sys.exit('stop on %s' % e)
203 sys.exit('stop on %s' % e)
General Comments 0
You need to be logged in to leave comments. Login now