##// END OF EJS Templates
auth-tokens: disable authenticating by builtin token.
marcink -
r1477:9f5f9c33 default
parent child Browse files
Show More
@@ -1,536 +1,536 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2017 RhodeCode GmbH
3 # Copyright (C) 2011-2017 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 inspect
21 import inspect
22 import itertools
22 import itertools
23 import logging
23 import logging
24 import types
24 import types
25 import fnmatch
25 import fnmatch
26
26
27 import decorator
27 import decorator
28 import venusian
28 import venusian
29 from collections import OrderedDict
29 from collections import OrderedDict
30
30
31 from pyramid.exceptions import ConfigurationError
31 from pyramid.exceptions import ConfigurationError
32 from pyramid.renderers import render
32 from pyramid.renderers import render
33 from pyramid.response import Response
33 from pyramid.response import Response
34 from pyramid.httpexceptions import HTTPNotFound
34 from pyramid.httpexceptions import HTTPNotFound
35
35
36 from rhodecode.api.exc import (
36 from rhodecode.api.exc import (
37 JSONRPCBaseError, JSONRPCError, JSONRPCForbidden, JSONRPCValidationError)
37 JSONRPCBaseError, JSONRPCError, JSONRPCForbidden, JSONRPCValidationError)
38 from rhodecode.lib.auth import AuthUser
38 from rhodecode.lib.auth import AuthUser
39 from rhodecode.lib.base import get_ip_addr
39 from rhodecode.lib.base import get_ip_addr
40 from rhodecode.lib.ext_json import json
40 from rhodecode.lib.ext_json import json
41 from rhodecode.lib.utils2 import safe_str
41 from rhodecode.lib.utils2 import safe_str
42 from rhodecode.lib.plugins.utils import get_plugin_settings
42 from rhodecode.lib.plugins.utils import get_plugin_settings
43 from rhodecode.model.db import User, UserApiKeys
43 from rhodecode.model.db import User, UserApiKeys
44
44
45 log = logging.getLogger(__name__)
45 log = logging.getLogger(__name__)
46
46
47 DEFAULT_RENDERER = 'jsonrpc_renderer'
47 DEFAULT_RENDERER = 'jsonrpc_renderer'
48 DEFAULT_URL = '/_admin/apiv2'
48 DEFAULT_URL = '/_admin/apiv2'
49
49
50
50
51 def find_methods(jsonrpc_methods, pattern):
51 def find_methods(jsonrpc_methods, pattern):
52 matches = OrderedDict()
52 matches = OrderedDict()
53 if not isinstance(pattern, (list, tuple)):
53 if not isinstance(pattern, (list, tuple)):
54 pattern = [pattern]
54 pattern = [pattern]
55
55
56 for single_pattern in pattern:
56 for single_pattern in pattern:
57 for method_name, method in jsonrpc_methods.items():
57 for method_name, method in jsonrpc_methods.items():
58 if fnmatch.fnmatch(method_name, single_pattern):
58 if fnmatch.fnmatch(method_name, single_pattern):
59 matches[method_name] = method
59 matches[method_name] = method
60 return matches
60 return matches
61
61
62
62
63 class ExtJsonRenderer(object):
63 class ExtJsonRenderer(object):
64 """
64 """
65 Custom renderer that mkaes use of our ext_json lib
65 Custom renderer that mkaes use of our ext_json lib
66
66
67 """
67 """
68
68
69 def __init__(self, serializer=json.dumps, **kw):
69 def __init__(self, serializer=json.dumps, **kw):
70 """ Any keyword arguments will be passed to the ``serializer``
70 """ Any keyword arguments will be passed to the ``serializer``
71 function."""
71 function."""
72 self.serializer = serializer
72 self.serializer = serializer
73 self.kw = kw
73 self.kw = kw
74
74
75 def __call__(self, info):
75 def __call__(self, info):
76 """ Returns a plain JSON-encoded string with content-type
76 """ Returns a plain JSON-encoded string with content-type
77 ``application/json``. The content-type may be overridden by
77 ``application/json``. The content-type may be overridden by
78 setting ``request.response.content_type``."""
78 setting ``request.response.content_type``."""
79
79
80 def _render(value, system):
80 def _render(value, system):
81 request = system.get('request')
81 request = system.get('request')
82 if request is not None:
82 if request is not None:
83 response = request.response
83 response = request.response
84 ct = response.content_type
84 ct = response.content_type
85 if ct == response.default_content_type:
85 if ct == response.default_content_type:
86 response.content_type = 'application/json'
86 response.content_type = 'application/json'
87
87
88 return self.serializer(value, **self.kw)
88 return self.serializer(value, **self.kw)
89
89
90 return _render
90 return _render
91
91
92
92
93 def jsonrpc_response(request, result):
93 def jsonrpc_response(request, result):
94 rpc_id = getattr(request, 'rpc_id', None)
94 rpc_id = getattr(request, 'rpc_id', None)
95 response = request.response
95 response = request.response
96
96
97 # store content_type before render is called
97 # store content_type before render is called
98 ct = response.content_type
98 ct = response.content_type
99
99
100 ret_value = ''
100 ret_value = ''
101 if rpc_id:
101 if rpc_id:
102 ret_value = {
102 ret_value = {
103 'id': rpc_id,
103 'id': rpc_id,
104 'result': result,
104 'result': result,
105 'error': None,
105 'error': None,
106 }
106 }
107
107
108 # fetch deprecation warnings, and store it inside results
108 # fetch deprecation warnings, and store it inside results
109 deprecation = getattr(request, 'rpc_deprecation', None)
109 deprecation = getattr(request, 'rpc_deprecation', None)
110 if deprecation:
110 if deprecation:
111 ret_value['DEPRECATION_WARNING'] = deprecation
111 ret_value['DEPRECATION_WARNING'] = deprecation
112
112
113 raw_body = render(DEFAULT_RENDERER, ret_value, request=request)
113 raw_body = render(DEFAULT_RENDERER, ret_value, request=request)
114 response.body = safe_str(raw_body, response.charset)
114 response.body = safe_str(raw_body, response.charset)
115
115
116 if ct == response.default_content_type:
116 if ct == response.default_content_type:
117 response.content_type = 'application/json'
117 response.content_type = 'application/json'
118
118
119 return response
119 return response
120
120
121
121
122 def jsonrpc_error(request, message, retid=None, code=None):
122 def jsonrpc_error(request, message, retid=None, code=None):
123 """
123 """
124 Generate a Response object with a JSON-RPC error body
124 Generate a Response object with a JSON-RPC error body
125
125
126 :param code:
126 :param code:
127 :param retid:
127 :param retid:
128 :param message:
128 :param message:
129 """
129 """
130 err_dict = {'id': retid, 'result': None, 'error': message}
130 err_dict = {'id': retid, 'result': None, 'error': message}
131 body = render(DEFAULT_RENDERER, err_dict, request=request).encode('utf-8')
131 body = render(DEFAULT_RENDERER, err_dict, request=request).encode('utf-8')
132 return Response(
132 return Response(
133 body=body,
133 body=body,
134 status=code,
134 status=code,
135 content_type='application/json'
135 content_type='application/json'
136 )
136 )
137
137
138
138
139 def exception_view(exc, request):
139 def exception_view(exc, request):
140 rpc_id = getattr(request, 'rpc_id', None)
140 rpc_id = getattr(request, 'rpc_id', None)
141
141
142 fault_message = 'undefined error'
142 fault_message = 'undefined error'
143 if isinstance(exc, JSONRPCError):
143 if isinstance(exc, JSONRPCError):
144 fault_message = exc.message
144 fault_message = exc.message
145 log.debug('json-rpc error rpc_id:%s "%s"', rpc_id, fault_message)
145 log.debug('json-rpc error rpc_id:%s "%s"', rpc_id, fault_message)
146 elif isinstance(exc, JSONRPCValidationError):
146 elif isinstance(exc, JSONRPCValidationError):
147 colander_exc = exc.colander_exception
147 colander_exc = exc.colander_exception
148 # TODO(marcink): think maybe of nicer way to serialize errors ?
148 # TODO(marcink): think maybe of nicer way to serialize errors ?
149 fault_message = colander_exc.asdict()
149 fault_message = colander_exc.asdict()
150 log.debug('json-rpc error rpc_id:%s "%s"', rpc_id, fault_message)
150 log.debug('json-rpc error rpc_id:%s "%s"', rpc_id, fault_message)
151 elif isinstance(exc, JSONRPCForbidden):
151 elif isinstance(exc, JSONRPCForbidden):
152 fault_message = 'Access was denied to this resource.'
152 fault_message = 'Access was denied to this resource.'
153 log.warning('json-rpc forbidden call rpc_id:%s "%s"', rpc_id, fault_message)
153 log.warning('json-rpc forbidden call rpc_id:%s "%s"', rpc_id, fault_message)
154 elif isinstance(exc, HTTPNotFound):
154 elif isinstance(exc, HTTPNotFound):
155 method = request.rpc_method
155 method = request.rpc_method
156 log.debug('json-rpc method `%s` not found in list of '
156 log.debug('json-rpc method `%s` not found in list of '
157 'api calls: %s, rpc_id:%s',
157 'api calls: %s, rpc_id:%s',
158 method, request.registry.jsonrpc_methods.keys(), rpc_id)
158 method, request.registry.jsonrpc_methods.keys(), rpc_id)
159
159
160 similar = 'none'
160 similar = 'none'
161 try:
161 try:
162 similar_paterns = ['*{}*'.format(x) for x in method.split('_')]
162 similar_paterns = ['*{}*'.format(x) for x in method.split('_')]
163 similar_found = find_methods(
163 similar_found = find_methods(
164 request.registry.jsonrpc_methods, similar_paterns)
164 request.registry.jsonrpc_methods, similar_paterns)
165 similar = ', '.join(similar_found.keys()) or similar
165 similar = ', '.join(similar_found.keys()) or similar
166 except Exception:
166 except Exception:
167 # make the whole above block safe
167 # make the whole above block safe
168 pass
168 pass
169
169
170 fault_message = "No such method: {}. Similar methods: {}".format(
170 fault_message = "No such method: {}. Similar methods: {}".format(
171 method, similar)
171 method, similar)
172
172
173 return jsonrpc_error(request, fault_message, rpc_id)
173 return jsonrpc_error(request, fault_message, rpc_id)
174
174
175
175
176 def request_view(request):
176 def request_view(request):
177 """
177 """
178 Main request handling method. It handles all logic to call a specific
178 Main request handling method. It handles all logic to call a specific
179 exposed method
179 exposed method
180 """
180 """
181
181
182 # check if we can find this session using api_key, get_by_auth_token
182 # check if we can find this session using api_key, get_by_auth_token
183 # search not expired tokens only
183 # search not expired tokens only
184
184
185 try:
185 try:
186 api_user = User.get_by_auth_token(request.rpc_api_key)
186 api_user = User.get_by_auth_token(request.rpc_api_key)
187
187
188 if api_user is None:
188 if api_user is None:
189 return jsonrpc_error(
189 return jsonrpc_error(
190 request, retid=request.rpc_id, message='Invalid API KEY')
190 request, retid=request.rpc_id, message='Invalid API KEY')
191
191
192 if not api_user.active:
192 if not api_user.active:
193 return jsonrpc_error(
193 return jsonrpc_error(
194 request, retid=request.rpc_id,
194 request, retid=request.rpc_id,
195 message='Request from this user not allowed')
195 message='Request from this user not allowed')
196
196
197 # check if we are allowed to use this IP
197 # check if we are allowed to use this IP
198 auth_u = AuthUser(
198 auth_u = AuthUser(
199 api_user.user_id, request.rpc_api_key, ip_addr=request.rpc_ip_addr)
199 api_user.user_id, request.rpc_api_key, ip_addr=request.rpc_ip_addr)
200 if not auth_u.ip_allowed:
200 if not auth_u.ip_allowed:
201 return jsonrpc_error(
201 return jsonrpc_error(
202 request, retid=request.rpc_id,
202 request, retid=request.rpc_id,
203 message='Request from IP:%s not allowed' % (
203 message='Request from IP:%s not allowed' % (
204 request.rpc_ip_addr,))
204 request.rpc_ip_addr,))
205 else:
205 else:
206 log.info('Access for IP:%s allowed' % (request.rpc_ip_addr,))
206 log.info('Access for IP:%s allowed' % (request.rpc_ip_addr,))
207
207
208 # register our auth-user
208 # register our auth-user
209 request.rpc_user = auth_u
209 request.rpc_user = auth_u
210
210
211 # now check if token is valid for API
211 # now check if token is valid for API
212 auth_token = request.rpc_api_key
212 auth_token = request.rpc_api_key
213 token_match = api_user.authenticate_by_token(
213 token_match = api_user.authenticate_by_token(
214 auth_token, roles=[UserApiKeys.ROLE_API], include_builtin_token=True)
214 auth_token, roles=[UserApiKeys.ROLE_API])
215 invalid_token = not token_match
215 invalid_token = not token_match
216
216
217 log.debug('Checking if API KEY is valid with proper role')
217 log.debug('Checking if API KEY is valid with proper role')
218 if invalid_token:
218 if invalid_token:
219 return jsonrpc_error(
219 return jsonrpc_error(
220 request, retid=request.rpc_id,
220 request, retid=request.rpc_id,
221 message='API KEY invalid or, has bad role for an API call')
221 message='API KEY invalid or, has bad role for an API call')
222
222
223 except Exception:
223 except Exception:
224 log.exception('Error on API AUTH')
224 log.exception('Error on API AUTH')
225 return jsonrpc_error(
225 return jsonrpc_error(
226 request, retid=request.rpc_id, message='Invalid API KEY')
226 request, retid=request.rpc_id, message='Invalid API KEY')
227
227
228 method = request.rpc_method
228 method = request.rpc_method
229 func = request.registry.jsonrpc_methods[method]
229 func = request.registry.jsonrpc_methods[method]
230
230
231 # now that we have a method, add request._req_params to
231 # now that we have a method, add request._req_params to
232 # self.kargs and dispatch control to WGIController
232 # self.kargs and dispatch control to WGIController
233 argspec = inspect.getargspec(func)
233 argspec = inspect.getargspec(func)
234 arglist = argspec[0]
234 arglist = argspec[0]
235 defaults = map(type, argspec[3] or [])
235 defaults = map(type, argspec[3] or [])
236 default_empty = types.NotImplementedType
236 default_empty = types.NotImplementedType
237
237
238 # kw arguments required by this method
238 # kw arguments required by this method
239 func_kwargs = dict(itertools.izip_longest(
239 func_kwargs = dict(itertools.izip_longest(
240 reversed(arglist), reversed(defaults), fillvalue=default_empty))
240 reversed(arglist), reversed(defaults), fillvalue=default_empty))
241
241
242 # This attribute will need to be first param of a method that uses
242 # This attribute will need to be first param of a method that uses
243 # api_key, which is translated to instance of user at that name
243 # api_key, which is translated to instance of user at that name
244 user_var = 'apiuser'
244 user_var = 'apiuser'
245 request_var = 'request'
245 request_var = 'request'
246
246
247 for arg in [user_var, request_var]:
247 for arg in [user_var, request_var]:
248 if arg not in arglist:
248 if arg not in arglist:
249 return jsonrpc_error(
249 return jsonrpc_error(
250 request,
250 request,
251 retid=request.rpc_id,
251 retid=request.rpc_id,
252 message='This method [%s] does not support '
252 message='This method [%s] does not support '
253 'required parameter `%s`' % (func.__name__, arg))
253 'required parameter `%s`' % (func.__name__, arg))
254
254
255 # get our arglist and check if we provided them as args
255 # get our arglist and check if we provided them as args
256 for arg, default in func_kwargs.items():
256 for arg, default in func_kwargs.items():
257 if arg in [user_var, request_var]:
257 if arg in [user_var, request_var]:
258 # user_var and request_var are pre-hardcoded parameters and we
258 # user_var and request_var are pre-hardcoded parameters and we
259 # don't need to do any translation
259 # don't need to do any translation
260 continue
260 continue
261
261
262 # skip the required param check if it's default value is
262 # skip the required param check if it's default value is
263 # NotImplementedType (default_empty)
263 # NotImplementedType (default_empty)
264 if default == default_empty and arg not in request.rpc_params:
264 if default == default_empty and arg not in request.rpc_params:
265 return jsonrpc_error(
265 return jsonrpc_error(
266 request,
266 request,
267 retid=request.rpc_id,
267 retid=request.rpc_id,
268 message=('Missing non optional `%s` arg in JSON DATA' % arg)
268 message=('Missing non optional `%s` arg in JSON DATA' % arg)
269 )
269 )
270
270
271 # sanitize extra passed arguments
271 # sanitize extra passed arguments
272 for k in request.rpc_params.keys()[:]:
272 for k in request.rpc_params.keys()[:]:
273 if k not in func_kwargs:
273 if k not in func_kwargs:
274 del request.rpc_params[k]
274 del request.rpc_params[k]
275
275
276 call_params = request.rpc_params
276 call_params = request.rpc_params
277 call_params.update({
277 call_params.update({
278 'request': request,
278 'request': request,
279 'apiuser': auth_u
279 'apiuser': auth_u
280 })
280 })
281 try:
281 try:
282 ret_value = func(**call_params)
282 ret_value = func(**call_params)
283 return jsonrpc_response(request, ret_value)
283 return jsonrpc_response(request, ret_value)
284 except JSONRPCBaseError:
284 except JSONRPCBaseError:
285 raise
285 raise
286 except Exception:
286 except Exception:
287 log.exception('Unhandled exception occurred on api call: %s', func)
287 log.exception('Unhandled exception occurred on api call: %s', func)
288 return jsonrpc_error(request, retid=request.rpc_id,
288 return jsonrpc_error(request, retid=request.rpc_id,
289 message='Internal server error')
289 message='Internal server error')
290
290
291
291
292 def setup_request(request):
292 def setup_request(request):
293 """
293 """
294 Parse a JSON-RPC request body. It's used inside the predicates method
294 Parse a JSON-RPC request body. It's used inside the predicates method
295 to validate and bootstrap requests for usage in rpc calls.
295 to validate and bootstrap requests for usage in rpc calls.
296
296
297 We need to raise JSONRPCError here if we want to return some errors back to
297 We need to raise JSONRPCError here if we want to return some errors back to
298 user.
298 user.
299 """
299 """
300
300
301 log.debug('Executing setup request: %r', request)
301 log.debug('Executing setup request: %r', request)
302 request.rpc_ip_addr = get_ip_addr(request.environ)
302 request.rpc_ip_addr = get_ip_addr(request.environ)
303 # TODO(marcink): deprecate GET at some point
303 # TODO(marcink): deprecate GET at some point
304 if request.method not in ['POST', 'GET']:
304 if request.method not in ['POST', 'GET']:
305 log.debug('unsupported request method "%s"', request.method)
305 log.debug('unsupported request method "%s"', request.method)
306 raise JSONRPCError(
306 raise JSONRPCError(
307 'unsupported request method "%s". Please use POST' % request.method)
307 'unsupported request method "%s". Please use POST' % request.method)
308
308
309 if 'CONTENT_LENGTH' not in request.environ:
309 if 'CONTENT_LENGTH' not in request.environ:
310 log.debug("No Content-Length")
310 log.debug("No Content-Length")
311 raise JSONRPCError("Empty body, No Content-Length in request")
311 raise JSONRPCError("Empty body, No Content-Length in request")
312
312
313 else:
313 else:
314 length = request.environ['CONTENT_LENGTH']
314 length = request.environ['CONTENT_LENGTH']
315 log.debug('Content-Length: %s', length)
315 log.debug('Content-Length: %s', length)
316
316
317 if length == 0:
317 if length == 0:
318 log.debug("Content-Length is 0")
318 log.debug("Content-Length is 0")
319 raise JSONRPCError("Content-Length is 0")
319 raise JSONRPCError("Content-Length is 0")
320
320
321 raw_body = request.body
321 raw_body = request.body
322 try:
322 try:
323 json_body = json.loads(raw_body)
323 json_body = json.loads(raw_body)
324 except ValueError as e:
324 except ValueError as e:
325 # catch JSON errors Here
325 # catch JSON errors Here
326 raise JSONRPCError("JSON parse error ERR:%s RAW:%r" % (e, raw_body))
326 raise JSONRPCError("JSON parse error ERR:%s RAW:%r" % (e, raw_body))
327
327
328 request.rpc_id = json_body.get('id')
328 request.rpc_id = json_body.get('id')
329 request.rpc_method = json_body.get('method')
329 request.rpc_method = json_body.get('method')
330
330
331 # check required base parameters
331 # check required base parameters
332 try:
332 try:
333 api_key = json_body.get('api_key')
333 api_key = json_body.get('api_key')
334 if not api_key:
334 if not api_key:
335 api_key = json_body.get('auth_token')
335 api_key = json_body.get('auth_token')
336
336
337 if not api_key:
337 if not api_key:
338 raise KeyError('api_key or auth_token')
338 raise KeyError('api_key or auth_token')
339
339
340 # TODO(marcink): support passing in token in request header
340 # TODO(marcink): support passing in token in request header
341
341
342 request.rpc_api_key = api_key
342 request.rpc_api_key = api_key
343 request.rpc_id = json_body['id']
343 request.rpc_id = json_body['id']
344 request.rpc_method = json_body['method']
344 request.rpc_method = json_body['method']
345 request.rpc_params = json_body['args'] \
345 request.rpc_params = json_body['args'] \
346 if isinstance(json_body['args'], dict) else {}
346 if isinstance(json_body['args'], dict) else {}
347
347
348 log.debug(
348 log.debug(
349 'method: %s, params: %s' % (request.rpc_method, request.rpc_params))
349 'method: %s, params: %s' % (request.rpc_method, request.rpc_params))
350 except KeyError as e:
350 except KeyError as e:
351 raise JSONRPCError('Incorrect JSON data. Missing %s' % e)
351 raise JSONRPCError('Incorrect JSON data. Missing %s' % e)
352
352
353 log.debug('setup complete, now handling method:%s rpcid:%s',
353 log.debug('setup complete, now handling method:%s rpcid:%s',
354 request.rpc_method, request.rpc_id, )
354 request.rpc_method, request.rpc_id, )
355
355
356
356
357 class RoutePredicate(object):
357 class RoutePredicate(object):
358 def __init__(self, val, config):
358 def __init__(self, val, config):
359 self.val = val
359 self.val = val
360
360
361 def text(self):
361 def text(self):
362 return 'jsonrpc route = %s' % self.val
362 return 'jsonrpc route = %s' % self.val
363
363
364 phash = text
364 phash = text
365
365
366 def __call__(self, info, request):
366 def __call__(self, info, request):
367 if self.val:
367 if self.val:
368 # potentially setup and bootstrap our call
368 # potentially setup and bootstrap our call
369 setup_request(request)
369 setup_request(request)
370
370
371 # Always return True so that even if it isn't a valid RPC it
371 # Always return True so that even if it isn't a valid RPC it
372 # will fall through to the underlaying handlers like notfound_view
372 # will fall through to the underlaying handlers like notfound_view
373 return True
373 return True
374
374
375
375
376 class NotFoundPredicate(object):
376 class NotFoundPredicate(object):
377 def __init__(self, val, config):
377 def __init__(self, val, config):
378 self.val = val
378 self.val = val
379 self.methods = config.registry.jsonrpc_methods
379 self.methods = config.registry.jsonrpc_methods
380
380
381 def text(self):
381 def text(self):
382 return 'jsonrpc method not found = {}.'.format(self.val)
382 return 'jsonrpc method not found = {}.'.format(self.val)
383
383
384 phash = text
384 phash = text
385
385
386 def __call__(self, info, request):
386 def __call__(self, info, request):
387 return hasattr(request, 'rpc_method')
387 return hasattr(request, 'rpc_method')
388
388
389
389
390 class MethodPredicate(object):
390 class MethodPredicate(object):
391 def __init__(self, val, config):
391 def __init__(self, val, config):
392 self.method = val
392 self.method = val
393
393
394 def text(self):
394 def text(self):
395 return 'jsonrpc method = %s' % self.method
395 return 'jsonrpc method = %s' % self.method
396
396
397 phash = text
397 phash = text
398
398
399 def __call__(self, context, request):
399 def __call__(self, context, request):
400 # we need to explicitly return False here, so pyramid doesn't try to
400 # we need to explicitly return False here, so pyramid doesn't try to
401 # execute our view directly. We need our main handler to execute things
401 # execute our view directly. We need our main handler to execute things
402 return getattr(request, 'rpc_method') == self.method
402 return getattr(request, 'rpc_method') == self.method
403
403
404
404
405 def add_jsonrpc_method(config, view, **kwargs):
405 def add_jsonrpc_method(config, view, **kwargs):
406 # pop the method name
406 # pop the method name
407 method = kwargs.pop('method', None)
407 method = kwargs.pop('method', None)
408
408
409 if method is None:
409 if method is None:
410 raise ConfigurationError(
410 raise ConfigurationError(
411 'Cannot register a JSON-RPC method without specifying the '
411 'Cannot register a JSON-RPC method without specifying the '
412 '"method"')
412 '"method"')
413
413
414 # we define custom predicate, to enable to detect conflicting methods,
414 # we define custom predicate, to enable to detect conflicting methods,
415 # those predicates are kind of "translation" from the decorator variables
415 # those predicates are kind of "translation" from the decorator variables
416 # to internal predicates names
416 # to internal predicates names
417
417
418 kwargs['jsonrpc_method'] = method
418 kwargs['jsonrpc_method'] = method
419
419
420 # register our view into global view store for validation
420 # register our view into global view store for validation
421 config.registry.jsonrpc_methods[method] = view
421 config.registry.jsonrpc_methods[method] = view
422
422
423 # we're using our main request_view handler, here, so each method
423 # we're using our main request_view handler, here, so each method
424 # has a unified handler for itself
424 # has a unified handler for itself
425 config.add_view(request_view, route_name='apiv2', **kwargs)
425 config.add_view(request_view, route_name='apiv2', **kwargs)
426
426
427
427
428 class jsonrpc_method(object):
428 class jsonrpc_method(object):
429 """
429 """
430 decorator that works similar to @add_view_config decorator,
430 decorator that works similar to @add_view_config decorator,
431 but tailored for our JSON RPC
431 but tailored for our JSON RPC
432 """
432 """
433
433
434 venusian = venusian # for testing injection
434 venusian = venusian # for testing injection
435
435
436 def __init__(self, method=None, **kwargs):
436 def __init__(self, method=None, **kwargs):
437 self.method = method
437 self.method = method
438 self.kwargs = kwargs
438 self.kwargs = kwargs
439
439
440 def __call__(self, wrapped):
440 def __call__(self, wrapped):
441 kwargs = self.kwargs.copy()
441 kwargs = self.kwargs.copy()
442 kwargs['method'] = self.method or wrapped.__name__
442 kwargs['method'] = self.method or wrapped.__name__
443 depth = kwargs.pop('_depth', 0)
443 depth = kwargs.pop('_depth', 0)
444
444
445 def callback(context, name, ob):
445 def callback(context, name, ob):
446 config = context.config.with_package(info.module)
446 config = context.config.with_package(info.module)
447 config.add_jsonrpc_method(view=ob, **kwargs)
447 config.add_jsonrpc_method(view=ob, **kwargs)
448
448
449 info = venusian.attach(wrapped, callback, category='pyramid',
449 info = venusian.attach(wrapped, callback, category='pyramid',
450 depth=depth + 1)
450 depth=depth + 1)
451 if info.scope == 'class':
451 if info.scope == 'class':
452 # ensure that attr is set if decorating a class method
452 # ensure that attr is set if decorating a class method
453 kwargs.setdefault('attr', wrapped.__name__)
453 kwargs.setdefault('attr', wrapped.__name__)
454
454
455 kwargs['_info'] = info.codeinfo # fbo action_method
455 kwargs['_info'] = info.codeinfo # fbo action_method
456 return wrapped
456 return wrapped
457
457
458
458
459 class jsonrpc_deprecated_method(object):
459 class jsonrpc_deprecated_method(object):
460 """
460 """
461 Marks method as deprecated, adds log.warning, and inject special key to
461 Marks method as deprecated, adds log.warning, and inject special key to
462 the request variable to mark method as deprecated.
462 the request variable to mark method as deprecated.
463 Also injects special docstring that extract_docs will catch to mark
463 Also injects special docstring that extract_docs will catch to mark
464 method as deprecated.
464 method as deprecated.
465
465
466 :param use_method: specify which method should be used instead of
466 :param use_method: specify which method should be used instead of
467 the decorated one
467 the decorated one
468
468
469 Use like::
469 Use like::
470
470
471 @jsonrpc_method()
471 @jsonrpc_method()
472 @jsonrpc_deprecated_method(use_method='new_func', deprecated_at_version='3.0.0')
472 @jsonrpc_deprecated_method(use_method='new_func', deprecated_at_version='3.0.0')
473 def old_func(request, apiuser, arg1, arg2):
473 def old_func(request, apiuser, arg1, arg2):
474 ...
474 ...
475 """
475 """
476
476
477 def __init__(self, use_method, deprecated_at_version):
477 def __init__(self, use_method, deprecated_at_version):
478 self.use_method = use_method
478 self.use_method = use_method
479 self.deprecated_at_version = deprecated_at_version
479 self.deprecated_at_version = deprecated_at_version
480 self.deprecated_msg = ''
480 self.deprecated_msg = ''
481
481
482 def __call__(self, func):
482 def __call__(self, func):
483 self.deprecated_msg = 'Please use method `{method}` instead.'.format(
483 self.deprecated_msg = 'Please use method `{method}` instead.'.format(
484 method=self.use_method)
484 method=self.use_method)
485
485
486 docstring = """\n
486 docstring = """\n
487 .. deprecated:: {version}
487 .. deprecated:: {version}
488
488
489 {deprecation_message}
489 {deprecation_message}
490
490
491 {original_docstring}
491 {original_docstring}
492 """
492 """
493 func.__doc__ = docstring.format(
493 func.__doc__ = docstring.format(
494 version=self.deprecated_at_version,
494 version=self.deprecated_at_version,
495 deprecation_message=self.deprecated_msg,
495 deprecation_message=self.deprecated_msg,
496 original_docstring=func.__doc__)
496 original_docstring=func.__doc__)
497 return decorator.decorator(self.__wrapper, func)
497 return decorator.decorator(self.__wrapper, func)
498
498
499 def __wrapper(self, func, *fargs, **fkwargs):
499 def __wrapper(self, func, *fargs, **fkwargs):
500 log.warning('DEPRECATED API CALL on function %s, please '
500 log.warning('DEPRECATED API CALL on function %s, please '
501 'use `%s` instead', func, self.use_method)
501 'use `%s` instead', func, self.use_method)
502 # alter function docstring to mark as deprecated, this is picked up
502 # alter function docstring to mark as deprecated, this is picked up
503 # via fabric file that generates API DOC.
503 # via fabric file that generates API DOC.
504 result = func(*fargs, **fkwargs)
504 result = func(*fargs, **fkwargs)
505
505
506 request = fargs[0]
506 request = fargs[0]
507 request.rpc_deprecation = 'DEPRECATED METHOD ' + self.deprecated_msg
507 request.rpc_deprecation = 'DEPRECATED METHOD ' + self.deprecated_msg
508 return result
508 return result
509
509
510
510
511 def includeme(config):
511 def includeme(config):
512 plugin_module = 'rhodecode.api'
512 plugin_module = 'rhodecode.api'
513 plugin_settings = get_plugin_settings(
513 plugin_settings = get_plugin_settings(
514 plugin_module, config.registry.settings)
514 plugin_module, config.registry.settings)
515
515
516 if not hasattr(config.registry, 'jsonrpc_methods'):
516 if not hasattr(config.registry, 'jsonrpc_methods'):
517 config.registry.jsonrpc_methods = OrderedDict()
517 config.registry.jsonrpc_methods = OrderedDict()
518
518
519 # match filter by given method only
519 # match filter by given method only
520 config.add_view_predicate('jsonrpc_method', MethodPredicate)
520 config.add_view_predicate('jsonrpc_method', MethodPredicate)
521
521
522 config.add_renderer(DEFAULT_RENDERER, ExtJsonRenderer(
522 config.add_renderer(DEFAULT_RENDERER, ExtJsonRenderer(
523 serializer=json.dumps, indent=4))
523 serializer=json.dumps, indent=4))
524 config.add_directive('add_jsonrpc_method', add_jsonrpc_method)
524 config.add_directive('add_jsonrpc_method', add_jsonrpc_method)
525
525
526 config.add_route_predicate(
526 config.add_route_predicate(
527 'jsonrpc_call', RoutePredicate)
527 'jsonrpc_call', RoutePredicate)
528
528
529 config.add_route(
529 config.add_route(
530 'apiv2', plugin_settings.get('url', DEFAULT_URL), jsonrpc_call=True)
530 'apiv2', plugin_settings.get('url', DEFAULT_URL), jsonrpc_call=True)
531
531
532 config.scan(plugin_module, ignore='rhodecode.api.tests')
532 config.scan(plugin_module, ignore='rhodecode.api.tests')
533 # register some exception handling view
533 # register some exception handling view
534 config.add_view(exception_view, context=JSONRPCBaseError)
534 config.add_view(exception_view, context=JSONRPCBaseError)
535 config.add_view_predicate('jsonrpc_method_not_found', NotFoundPredicate)
535 config.add_view_predicate('jsonrpc_method_not_found', NotFoundPredicate)
536 config.add_notfound_view(exception_view, jsonrpc_method_not_found=True)
536 config.add_notfound_view(exception_view, jsonrpc_method_not_found=True)
@@ -1,1929 +1,1929 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 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 inspect
25 import inspect
26 import collections
26 import collections
27 import fnmatch
27 import fnmatch
28 import hashlib
28 import hashlib
29 import itertools
29 import itertools
30 import logging
30 import logging
31 import os
31 import os
32 import random
32 import random
33 import time
33 import time
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 from pyramid.httpexceptions import HTTPForbidden
38 from pyramid.httpexceptions import HTTPForbidden
39 from pylons import url, request
39 from pylons import url, request
40 from pylons.controllers.util import abort, redirect
40 from pylons.controllers.util import abort, redirect
41 from pylons.i18n.translation import _
41 from pylons.i18n.translation import _
42 from sqlalchemy import or_
42 from sqlalchemy import or_
43 from sqlalchemy.orm.exc import ObjectDeletedError
43 from sqlalchemy.orm.exc import ObjectDeletedError
44 from sqlalchemy.orm import joinedload
44 from sqlalchemy.orm import joinedload
45 from zope.cachedescriptors.property import Lazy as LazyProperty
45 from zope.cachedescriptors.property import Lazy as LazyProperty
46
46
47 import rhodecode
47 import rhodecode
48 from rhodecode.model import meta
48 from rhodecode.model import meta
49 from rhodecode.model.meta import Session
49 from rhodecode.model.meta import Session
50 from rhodecode.model.user import UserModel
50 from rhodecode.model.user import UserModel
51 from rhodecode.model.db import (
51 from rhodecode.model.db import (
52 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
52 User, Repository, Permission, UserToPerm, UserGroupToPerm, UserGroupMember,
53 UserIpMap, UserApiKeys, RepoGroup)
53 UserIpMap, UserApiKeys, RepoGroup)
54 from rhodecode.lib import caches
54 from rhodecode.lib import caches
55 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
55 from rhodecode.lib.utils2 import safe_unicode, aslist, safe_str, md5
56 from rhodecode.lib.utils import (
56 from rhodecode.lib.utils import (
57 get_repo_slug, get_repo_group_slug, get_user_group_slug)
57 get_repo_slug, get_repo_group_slug, get_user_group_slug)
58 from rhodecode.lib.caching_query import FromCache
58 from rhodecode.lib.caching_query import FromCache
59
59
60
60
61 if rhodecode.is_unix:
61 if rhodecode.is_unix:
62 import bcrypt
62 import bcrypt
63
63
64 log = logging.getLogger(__name__)
64 log = logging.getLogger(__name__)
65
65
66 csrf_token_key = "csrf_token"
66 csrf_token_key = "csrf_token"
67
67
68
68
69 class PasswordGenerator(object):
69 class PasswordGenerator(object):
70 """
70 """
71 This is a simple class for generating password from different sets of
71 This is a simple class for generating password from different sets of
72 characters
72 characters
73 usage::
73 usage::
74
74
75 passwd_gen = PasswordGenerator()
75 passwd_gen = PasswordGenerator()
76 #print 8-letter password containing only big and small letters
76 #print 8-letter password containing only big and small letters
77 of alphabet
77 of alphabet
78 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
78 passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
79 """
79 """
80 ALPHABETS_NUM = r'''1234567890'''
80 ALPHABETS_NUM = r'''1234567890'''
81 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
81 ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
82 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
82 ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
83 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
83 ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
84 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
84 ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
85 + ALPHABETS_NUM + ALPHABETS_SPECIAL
85 + ALPHABETS_NUM + ALPHABETS_SPECIAL
86 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
86 ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
87 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
87 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
88 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
88 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
89 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
89 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
90
90
91 def __init__(self, passwd=''):
91 def __init__(self, passwd=''):
92 self.passwd = passwd
92 self.passwd = passwd
93
93
94 def gen_password(self, length, type_=None):
94 def gen_password(self, length, type_=None):
95 if type_ is None:
95 if type_ is None:
96 type_ = self.ALPHABETS_FULL
96 type_ = self.ALPHABETS_FULL
97 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
97 self.passwd = ''.join([random.choice(type_) for _ in xrange(length)])
98 return self.passwd
98 return self.passwd
99
99
100
100
101 class _RhodeCodeCryptoBase(object):
101 class _RhodeCodeCryptoBase(object):
102 ENC_PREF = None
102 ENC_PREF = None
103
103
104 def hash_create(self, str_):
104 def hash_create(self, str_):
105 """
105 """
106 hash the string using
106 hash the string using
107
107
108 :param str_: password to hash
108 :param str_: password to hash
109 """
109 """
110 raise NotImplementedError
110 raise NotImplementedError
111
111
112 def hash_check_with_upgrade(self, password, hashed):
112 def hash_check_with_upgrade(self, password, hashed):
113 """
113 """
114 Returns tuple in which first element is boolean that states that
114 Returns tuple in which first element is boolean that states that
115 given password matches it's hashed version, and the second is new hash
115 given password matches it's hashed version, and the second is new hash
116 of the password, in case this password should be migrated to new
116 of the password, in case this password should be migrated to new
117 cipher.
117 cipher.
118 """
118 """
119 checked_hash = self.hash_check(password, hashed)
119 checked_hash = self.hash_check(password, hashed)
120 return checked_hash, None
120 return checked_hash, None
121
121
122 def hash_check(self, password, hashed):
122 def hash_check(self, password, hashed):
123 """
123 """
124 Checks matching password with it's hashed value.
124 Checks matching password with it's hashed value.
125
125
126 :param password: password
126 :param password: password
127 :param hashed: password in hashed form
127 :param hashed: password in hashed form
128 """
128 """
129 raise NotImplementedError
129 raise NotImplementedError
130
130
131 def _assert_bytes(self, value):
131 def _assert_bytes(self, value):
132 """
132 """
133 Passing in an `unicode` object can lead to hard to detect issues
133 Passing in an `unicode` object can lead to hard to detect issues
134 if passwords contain non-ascii characters. Doing a type check
134 if passwords contain non-ascii characters. Doing a type check
135 during runtime, so that such mistakes are detected early on.
135 during runtime, so that such mistakes are detected early on.
136 """
136 """
137 if not isinstance(value, str):
137 if not isinstance(value, str):
138 raise TypeError(
138 raise TypeError(
139 "Bytestring required as input, got %r." % (value, ))
139 "Bytestring required as input, got %r." % (value, ))
140
140
141
141
142 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
142 class _RhodeCodeCryptoBCrypt(_RhodeCodeCryptoBase):
143 ENC_PREF = '$2a$10'
143 ENC_PREF = '$2a$10'
144
144
145 def hash_create(self, str_):
145 def hash_create(self, str_):
146 self._assert_bytes(str_)
146 self._assert_bytes(str_)
147 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
147 return bcrypt.hashpw(str_, bcrypt.gensalt(10))
148
148
149 def hash_check_with_upgrade(self, password, hashed):
149 def hash_check_with_upgrade(self, password, hashed):
150 """
150 """
151 Returns tuple in which first element is boolean that states that
151 Returns tuple in which first element is boolean that states that
152 given password matches it's hashed version, and the second is new hash
152 given password matches it's hashed version, and the second is new hash
153 of the password, in case this password should be migrated to new
153 of the password, in case this password should be migrated to new
154 cipher.
154 cipher.
155
155
156 This implements special upgrade logic which works like that:
156 This implements special upgrade logic which works like that:
157 - check if the given password == bcrypted hash, if yes then we
157 - check if the given password == bcrypted hash, if yes then we
158 properly used password and it was already in bcrypt. Proceed
158 properly used password and it was already in bcrypt. Proceed
159 without any changes
159 without any changes
160 - if bcrypt hash check is not working try with sha256. If hash compare
160 - if bcrypt hash check is not working try with sha256. If hash compare
161 is ok, it means we using correct but old hashed password. indicate
161 is ok, it means we using correct but old hashed password. indicate
162 hash change and proceed
162 hash change and proceed
163 """
163 """
164
164
165 new_hash = None
165 new_hash = None
166
166
167 # regular pw check
167 # regular pw check
168 password_match_bcrypt = self.hash_check(password, hashed)
168 password_match_bcrypt = self.hash_check(password, hashed)
169
169
170 # now we want to know if the password was maybe from sha256
170 # now we want to know if the password was maybe from sha256
171 # basically calling _RhodeCodeCryptoSha256().hash_check()
171 # basically calling _RhodeCodeCryptoSha256().hash_check()
172 if not password_match_bcrypt:
172 if not password_match_bcrypt:
173 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
173 if _RhodeCodeCryptoSha256().hash_check(password, hashed):
174 new_hash = self.hash_create(password) # make new bcrypt hash
174 new_hash = self.hash_create(password) # make new bcrypt hash
175 password_match_bcrypt = True
175 password_match_bcrypt = True
176
176
177 return password_match_bcrypt, new_hash
177 return password_match_bcrypt, new_hash
178
178
179 def hash_check(self, password, hashed):
179 def hash_check(self, password, hashed):
180 """
180 """
181 Checks matching password with it's hashed value.
181 Checks matching password with it's hashed value.
182
182
183 :param password: password
183 :param password: password
184 :param hashed: password in hashed form
184 :param hashed: password in hashed form
185 """
185 """
186 self._assert_bytes(password)
186 self._assert_bytes(password)
187 try:
187 try:
188 return bcrypt.hashpw(password, hashed) == hashed
188 return bcrypt.hashpw(password, hashed) == hashed
189 except ValueError as e:
189 except ValueError as e:
190 # we're having a invalid salt here probably, we should not crash
190 # we're having a invalid salt here probably, we should not crash
191 # just return with False as it would be a wrong password.
191 # just return with False as it would be a wrong password.
192 log.debug('Failed to check password hash using bcrypt %s',
192 log.debug('Failed to check password hash using bcrypt %s',
193 safe_str(e))
193 safe_str(e))
194
194
195 return False
195 return False
196
196
197
197
198 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
198 class _RhodeCodeCryptoSha256(_RhodeCodeCryptoBase):
199 ENC_PREF = '_'
199 ENC_PREF = '_'
200
200
201 def hash_create(self, str_):
201 def hash_create(self, str_):
202 self._assert_bytes(str_)
202 self._assert_bytes(str_)
203 return hashlib.sha256(str_).hexdigest()
203 return hashlib.sha256(str_).hexdigest()
204
204
205 def hash_check(self, password, hashed):
205 def hash_check(self, password, hashed):
206 """
206 """
207 Checks matching password with it's hashed value.
207 Checks matching password with it's hashed value.
208
208
209 :param password: password
209 :param password: password
210 :param hashed: password in hashed form
210 :param hashed: password in hashed form
211 """
211 """
212 self._assert_bytes(password)
212 self._assert_bytes(password)
213 return hashlib.sha256(password).hexdigest() == hashed
213 return hashlib.sha256(password).hexdigest() == hashed
214
214
215
215
216 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
216 class _RhodeCodeCryptoMd5(_RhodeCodeCryptoBase):
217 ENC_PREF = '_'
217 ENC_PREF = '_'
218
218
219 def hash_create(self, str_):
219 def hash_create(self, str_):
220 self._assert_bytes(str_)
220 self._assert_bytes(str_)
221 return hashlib.md5(str_).hexdigest()
221 return hashlib.md5(str_).hexdigest()
222
222
223 def hash_check(self, password, hashed):
223 def hash_check(self, password, hashed):
224 """
224 """
225 Checks matching password with it's hashed value.
225 Checks matching password with it's hashed value.
226
226
227 :param password: password
227 :param password: password
228 :param hashed: password in hashed form
228 :param hashed: password in hashed form
229 """
229 """
230 self._assert_bytes(password)
230 self._assert_bytes(password)
231 return hashlib.md5(password).hexdigest() == hashed
231 return hashlib.md5(password).hexdigest() == hashed
232
232
233
233
234 def crypto_backend():
234 def crypto_backend():
235 """
235 """
236 Return the matching crypto backend.
236 Return the matching crypto backend.
237
237
238 Selection is based on if we run tests or not, we pick md5 backend to run
238 Selection is based on if we run tests or not, we pick md5 backend to run
239 tests faster since BCRYPT is expensive to calculate
239 tests faster since BCRYPT is expensive to calculate
240 """
240 """
241 if rhodecode.is_test:
241 if rhodecode.is_test:
242 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
242 RhodeCodeCrypto = _RhodeCodeCryptoMd5()
243 else:
243 else:
244 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
244 RhodeCodeCrypto = _RhodeCodeCryptoBCrypt()
245
245
246 return RhodeCodeCrypto
246 return RhodeCodeCrypto
247
247
248
248
249 def get_crypt_password(password):
249 def get_crypt_password(password):
250 """
250 """
251 Create the hash of `password` with the active crypto backend.
251 Create the hash of `password` with the active crypto backend.
252
252
253 :param password: The cleartext password.
253 :param password: The cleartext password.
254 :type password: unicode
254 :type password: unicode
255 """
255 """
256 password = safe_str(password)
256 password = safe_str(password)
257 return crypto_backend().hash_create(password)
257 return crypto_backend().hash_create(password)
258
258
259
259
260 def check_password(password, hashed):
260 def check_password(password, hashed):
261 """
261 """
262 Check if the value in `password` matches the hash in `hashed`.
262 Check if the value in `password` matches the hash in `hashed`.
263
263
264 :param password: The cleartext password.
264 :param password: The cleartext password.
265 :type password: unicode
265 :type password: unicode
266
266
267 :param hashed: The expected hashed version of the password.
267 :param hashed: The expected hashed version of the password.
268 :type hashed: The hash has to be passed in in text representation.
268 :type hashed: The hash has to be passed in in text representation.
269 """
269 """
270 password = safe_str(password)
270 password = safe_str(password)
271 return crypto_backend().hash_check(password, hashed)
271 return crypto_backend().hash_check(password, hashed)
272
272
273
273
274 def generate_auth_token(data, salt=None):
274 def generate_auth_token(data, salt=None):
275 """
275 """
276 Generates API KEY from given string
276 Generates API KEY from given string
277 """
277 """
278
278
279 if salt is None:
279 if salt is None:
280 salt = os.urandom(16)
280 salt = os.urandom(16)
281 return hashlib.sha1(safe_str(data) + salt).hexdigest()
281 return hashlib.sha1(safe_str(data) + salt).hexdigest()
282
282
283
283
284 class CookieStoreWrapper(object):
284 class CookieStoreWrapper(object):
285
285
286 def __init__(self, cookie_store):
286 def __init__(self, cookie_store):
287 self.cookie_store = cookie_store
287 self.cookie_store = cookie_store
288
288
289 def __repr__(self):
289 def __repr__(self):
290 return 'CookieStore<%s>' % (self.cookie_store)
290 return 'CookieStore<%s>' % (self.cookie_store)
291
291
292 def get(self, key, other=None):
292 def get(self, key, other=None):
293 if isinstance(self.cookie_store, dict):
293 if isinstance(self.cookie_store, dict):
294 return self.cookie_store.get(key, other)
294 return self.cookie_store.get(key, other)
295 elif isinstance(self.cookie_store, AuthUser):
295 elif isinstance(self.cookie_store, AuthUser):
296 return self.cookie_store.__dict__.get(key, other)
296 return self.cookie_store.__dict__.get(key, other)
297
297
298
298
299 def _cached_perms_data(user_id, scope, user_is_admin,
299 def _cached_perms_data(user_id, scope, user_is_admin,
300 user_inherit_default_permissions, explicit, algo):
300 user_inherit_default_permissions, explicit, algo):
301
301
302 permissions = PermissionCalculator(
302 permissions = PermissionCalculator(
303 user_id, scope, user_is_admin, user_inherit_default_permissions,
303 user_id, scope, user_is_admin, user_inherit_default_permissions,
304 explicit, algo)
304 explicit, algo)
305 return permissions.calculate()
305 return permissions.calculate()
306
306
307 class PermOrigin:
307 class PermOrigin:
308 ADMIN = 'superadmin'
308 ADMIN = 'superadmin'
309
309
310 REPO_USER = 'user:%s'
310 REPO_USER = 'user:%s'
311 REPO_USERGROUP = 'usergroup:%s'
311 REPO_USERGROUP = 'usergroup:%s'
312 REPO_OWNER = 'repo.owner'
312 REPO_OWNER = 'repo.owner'
313 REPO_DEFAULT = 'repo.default'
313 REPO_DEFAULT = 'repo.default'
314 REPO_PRIVATE = 'repo.private'
314 REPO_PRIVATE = 'repo.private'
315
315
316 REPOGROUP_USER = 'user:%s'
316 REPOGROUP_USER = 'user:%s'
317 REPOGROUP_USERGROUP = 'usergroup:%s'
317 REPOGROUP_USERGROUP = 'usergroup:%s'
318 REPOGROUP_OWNER = 'group.owner'
318 REPOGROUP_OWNER = 'group.owner'
319 REPOGROUP_DEFAULT = 'group.default'
319 REPOGROUP_DEFAULT = 'group.default'
320
320
321 USERGROUP_USER = 'user:%s'
321 USERGROUP_USER = 'user:%s'
322 USERGROUP_USERGROUP = 'usergroup:%s'
322 USERGROUP_USERGROUP = 'usergroup:%s'
323 USERGROUP_OWNER = 'usergroup.owner'
323 USERGROUP_OWNER = 'usergroup.owner'
324 USERGROUP_DEFAULT = 'usergroup.default'
324 USERGROUP_DEFAULT = 'usergroup.default'
325
325
326
326
327 class PermOriginDict(dict):
327 class PermOriginDict(dict):
328 """
328 """
329 A special dict used for tracking permissions along with their origins.
329 A special dict used for tracking permissions along with their origins.
330
330
331 `__setitem__` has been overridden to expect a tuple(perm, origin)
331 `__setitem__` has been overridden to expect a tuple(perm, origin)
332 `__getitem__` will return only the perm
332 `__getitem__` will return only the perm
333 `.perm_origin_stack` will return the stack of (perm, origin) set per key
333 `.perm_origin_stack` will return the stack of (perm, origin) set per key
334
334
335 >>> perms = PermOriginDict()
335 >>> perms = PermOriginDict()
336 >>> perms['resource'] = 'read', 'default'
336 >>> perms['resource'] = 'read', 'default'
337 >>> perms['resource']
337 >>> perms['resource']
338 'read'
338 'read'
339 >>> perms['resource'] = 'write', 'admin'
339 >>> perms['resource'] = 'write', 'admin'
340 >>> perms['resource']
340 >>> perms['resource']
341 'write'
341 'write'
342 >>> perms.perm_origin_stack
342 >>> perms.perm_origin_stack
343 {'resource': [('read', 'default'), ('write', 'admin')]}
343 {'resource': [('read', 'default'), ('write', 'admin')]}
344 """
344 """
345
345
346
346
347 def __init__(self, *args, **kw):
347 def __init__(self, *args, **kw):
348 dict.__init__(self, *args, **kw)
348 dict.__init__(self, *args, **kw)
349 self.perm_origin_stack = {}
349 self.perm_origin_stack = {}
350
350
351 def __setitem__(self, key, (perm, origin)):
351 def __setitem__(self, key, (perm, origin)):
352 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
352 self.perm_origin_stack.setdefault(key, []).append((perm, origin))
353 dict.__setitem__(self, key, perm)
353 dict.__setitem__(self, key, perm)
354
354
355
355
356 class PermissionCalculator(object):
356 class PermissionCalculator(object):
357
357
358 def __init__(
358 def __init__(
359 self, user_id, scope, user_is_admin,
359 self, user_id, scope, user_is_admin,
360 user_inherit_default_permissions, explicit, algo):
360 user_inherit_default_permissions, explicit, algo):
361 self.user_id = user_id
361 self.user_id = user_id
362 self.user_is_admin = user_is_admin
362 self.user_is_admin = user_is_admin
363 self.inherit_default_permissions = user_inherit_default_permissions
363 self.inherit_default_permissions = user_inherit_default_permissions
364 self.explicit = explicit
364 self.explicit = explicit
365 self.algo = algo
365 self.algo = algo
366
366
367 scope = scope or {}
367 scope = scope or {}
368 self.scope_repo_id = scope.get('repo_id')
368 self.scope_repo_id = scope.get('repo_id')
369 self.scope_repo_group_id = scope.get('repo_group_id')
369 self.scope_repo_group_id = scope.get('repo_group_id')
370 self.scope_user_group_id = scope.get('user_group_id')
370 self.scope_user_group_id = scope.get('user_group_id')
371
371
372 self.default_user_id = User.get_default_user(cache=True).user_id
372 self.default_user_id = User.get_default_user(cache=True).user_id
373
373
374 self.permissions_repositories = PermOriginDict()
374 self.permissions_repositories = PermOriginDict()
375 self.permissions_repository_groups = PermOriginDict()
375 self.permissions_repository_groups = PermOriginDict()
376 self.permissions_user_groups = PermOriginDict()
376 self.permissions_user_groups = PermOriginDict()
377 self.permissions_global = set()
377 self.permissions_global = set()
378
378
379 self.default_repo_perms = Permission.get_default_repo_perms(
379 self.default_repo_perms = Permission.get_default_repo_perms(
380 self.default_user_id, self.scope_repo_id)
380 self.default_user_id, self.scope_repo_id)
381 self.default_repo_groups_perms = Permission.get_default_group_perms(
381 self.default_repo_groups_perms = Permission.get_default_group_perms(
382 self.default_user_id, self.scope_repo_group_id)
382 self.default_user_id, self.scope_repo_group_id)
383 self.default_user_group_perms = \
383 self.default_user_group_perms = \
384 Permission.get_default_user_group_perms(
384 Permission.get_default_user_group_perms(
385 self.default_user_id, self.scope_user_group_id)
385 self.default_user_id, self.scope_user_group_id)
386
386
387 def calculate(self):
387 def calculate(self):
388 if self.user_is_admin:
388 if self.user_is_admin:
389 return self._admin_permissions()
389 return self._admin_permissions()
390
390
391 self._calculate_global_default_permissions()
391 self._calculate_global_default_permissions()
392 self._calculate_global_permissions()
392 self._calculate_global_permissions()
393 self._calculate_default_permissions()
393 self._calculate_default_permissions()
394 self._calculate_repository_permissions()
394 self._calculate_repository_permissions()
395 self._calculate_repository_group_permissions()
395 self._calculate_repository_group_permissions()
396 self._calculate_user_group_permissions()
396 self._calculate_user_group_permissions()
397 return self._permission_structure()
397 return self._permission_structure()
398
398
399 def _admin_permissions(self):
399 def _admin_permissions(self):
400 """
400 """
401 admin user have all default rights for repositories
401 admin user have all default rights for repositories
402 and groups set to admin
402 and groups set to admin
403 """
403 """
404 self.permissions_global.add('hg.admin')
404 self.permissions_global.add('hg.admin')
405 self.permissions_global.add('hg.create.write_on_repogroup.true')
405 self.permissions_global.add('hg.create.write_on_repogroup.true')
406
406
407 # repositories
407 # repositories
408 for perm in self.default_repo_perms:
408 for perm in self.default_repo_perms:
409 r_k = perm.UserRepoToPerm.repository.repo_name
409 r_k = perm.UserRepoToPerm.repository.repo_name
410 p = 'repository.admin'
410 p = 'repository.admin'
411 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
411 self.permissions_repositories[r_k] = p, PermOrigin.ADMIN
412
412
413 # repository groups
413 # repository groups
414 for perm in self.default_repo_groups_perms:
414 for perm in self.default_repo_groups_perms:
415 rg_k = perm.UserRepoGroupToPerm.group.group_name
415 rg_k = perm.UserRepoGroupToPerm.group.group_name
416 p = 'group.admin'
416 p = 'group.admin'
417 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
417 self.permissions_repository_groups[rg_k] = p, PermOrigin.ADMIN
418
418
419 # user groups
419 # user groups
420 for perm in self.default_user_group_perms:
420 for perm in self.default_user_group_perms:
421 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
421 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
422 p = 'usergroup.admin'
422 p = 'usergroup.admin'
423 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
423 self.permissions_user_groups[u_k] = p, PermOrigin.ADMIN
424
424
425 return self._permission_structure()
425 return self._permission_structure()
426
426
427 def _calculate_global_default_permissions(self):
427 def _calculate_global_default_permissions(self):
428 """
428 """
429 global permissions taken from the default user
429 global permissions taken from the default user
430 """
430 """
431 default_global_perms = UserToPerm.query()\
431 default_global_perms = UserToPerm.query()\
432 .filter(UserToPerm.user_id == self.default_user_id)\
432 .filter(UserToPerm.user_id == self.default_user_id)\
433 .options(joinedload(UserToPerm.permission))
433 .options(joinedload(UserToPerm.permission))
434
434
435 for perm in default_global_perms:
435 for perm in default_global_perms:
436 self.permissions_global.add(perm.permission.permission_name)
436 self.permissions_global.add(perm.permission.permission_name)
437
437
438 def _calculate_global_permissions(self):
438 def _calculate_global_permissions(self):
439 """
439 """
440 Set global system permissions with user permissions or permissions
440 Set global system permissions with user permissions or permissions
441 taken from the user groups of the current user.
441 taken from the user groups of the current user.
442
442
443 The permissions include repo creating, repo group creating, forking
443 The permissions include repo creating, repo group creating, forking
444 etc.
444 etc.
445 """
445 """
446
446
447 # now we read the defined permissions and overwrite what we have set
447 # now we read the defined permissions and overwrite what we have set
448 # before those can be configured from groups or users explicitly.
448 # before those can be configured from groups or users explicitly.
449
449
450 # TODO: johbo: This seems to be out of sync, find out the reason
450 # TODO: johbo: This seems to be out of sync, find out the reason
451 # for the comment below and update it.
451 # for the comment below and update it.
452
452
453 # In case we want to extend this list we should be always in sync with
453 # In case we want to extend this list we should be always in sync with
454 # User.DEFAULT_USER_PERMISSIONS definitions
454 # User.DEFAULT_USER_PERMISSIONS definitions
455 _configurable = frozenset([
455 _configurable = frozenset([
456 'hg.fork.none', 'hg.fork.repository',
456 'hg.fork.none', 'hg.fork.repository',
457 'hg.create.none', 'hg.create.repository',
457 'hg.create.none', 'hg.create.repository',
458 'hg.usergroup.create.false', 'hg.usergroup.create.true',
458 'hg.usergroup.create.false', 'hg.usergroup.create.true',
459 'hg.repogroup.create.false', 'hg.repogroup.create.true',
459 'hg.repogroup.create.false', 'hg.repogroup.create.true',
460 'hg.create.write_on_repogroup.false',
460 'hg.create.write_on_repogroup.false',
461 'hg.create.write_on_repogroup.true',
461 'hg.create.write_on_repogroup.true',
462 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
462 'hg.inherit_default_perms.false', 'hg.inherit_default_perms.true'
463 ])
463 ])
464
464
465 # USER GROUPS comes first user group global permissions
465 # USER GROUPS comes first user group global permissions
466 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
466 user_perms_from_users_groups = Session().query(UserGroupToPerm)\
467 .options(joinedload(UserGroupToPerm.permission))\
467 .options(joinedload(UserGroupToPerm.permission))\
468 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
468 .join((UserGroupMember, UserGroupToPerm.users_group_id ==
469 UserGroupMember.users_group_id))\
469 UserGroupMember.users_group_id))\
470 .filter(UserGroupMember.user_id == self.user_id)\
470 .filter(UserGroupMember.user_id == self.user_id)\
471 .order_by(UserGroupToPerm.users_group_id)\
471 .order_by(UserGroupToPerm.users_group_id)\
472 .all()
472 .all()
473
473
474 # need to group here by groups since user can be in more than
474 # need to group here by groups since user can be in more than
475 # one group, so we get all groups
475 # one group, so we get all groups
476 _explicit_grouped_perms = [
476 _explicit_grouped_perms = [
477 [x, list(y)] for x, y in
477 [x, list(y)] for x, y in
478 itertools.groupby(user_perms_from_users_groups,
478 itertools.groupby(user_perms_from_users_groups,
479 lambda _x: _x.users_group)]
479 lambda _x: _x.users_group)]
480
480
481 for gr, perms in _explicit_grouped_perms:
481 for gr, perms in _explicit_grouped_perms:
482 # since user can be in multiple groups iterate over them and
482 # since user can be in multiple groups iterate over them and
483 # select the lowest permissions first (more explicit)
483 # select the lowest permissions first (more explicit)
484 # TODO: marcink: do this^^
484 # TODO: marcink: do this^^
485
485
486 # group doesn't inherit default permissions so we actually set them
486 # group doesn't inherit default permissions so we actually set them
487 if not gr.inherit_default_permissions:
487 if not gr.inherit_default_permissions:
488 # NEED TO IGNORE all previously set configurable permissions
488 # NEED TO IGNORE all previously set configurable permissions
489 # and replace them with explicitly set from this user
489 # and replace them with explicitly set from this user
490 # group permissions
490 # group permissions
491 self.permissions_global = self.permissions_global.difference(
491 self.permissions_global = self.permissions_global.difference(
492 _configurable)
492 _configurable)
493 for perm in perms:
493 for perm in perms:
494 self.permissions_global.add(perm.permission.permission_name)
494 self.permissions_global.add(perm.permission.permission_name)
495
495
496 # user explicit global permissions
496 # user explicit global permissions
497 user_perms = Session().query(UserToPerm)\
497 user_perms = Session().query(UserToPerm)\
498 .options(joinedload(UserToPerm.permission))\
498 .options(joinedload(UserToPerm.permission))\
499 .filter(UserToPerm.user_id == self.user_id).all()
499 .filter(UserToPerm.user_id == self.user_id).all()
500
500
501 if not self.inherit_default_permissions:
501 if not self.inherit_default_permissions:
502 # NEED TO IGNORE all configurable permissions and
502 # NEED TO IGNORE all configurable permissions and
503 # replace them with explicitly set from this user permissions
503 # replace them with explicitly set from this user permissions
504 self.permissions_global = self.permissions_global.difference(
504 self.permissions_global = self.permissions_global.difference(
505 _configurable)
505 _configurable)
506 for perm in user_perms:
506 for perm in user_perms:
507 self.permissions_global.add(perm.permission.permission_name)
507 self.permissions_global.add(perm.permission.permission_name)
508
508
509 def _calculate_default_permissions(self):
509 def _calculate_default_permissions(self):
510 """
510 """
511 Set default user permissions for repositories, repository groups
511 Set default user permissions for repositories, repository groups
512 taken from the default user.
512 taken from the default user.
513
513
514 Calculate inheritance of object permissions based on what we have now
514 Calculate inheritance of object permissions based on what we have now
515 in GLOBAL permissions. We check if .false is in GLOBAL since this is
515 in GLOBAL permissions. We check if .false is in GLOBAL since this is
516 explicitly set. Inherit is the opposite of .false being there.
516 explicitly set. Inherit is the opposite of .false being there.
517
517
518 .. note::
518 .. note::
519
519
520 the syntax is little bit odd but what we need to check here is
520 the syntax is little bit odd but what we need to check here is
521 the opposite of .false permission being in the list so even for
521 the opposite of .false permission being in the list so even for
522 inconsistent state when both .true/.false is there
522 inconsistent state when both .true/.false is there
523 .false is more important
523 .false is more important
524
524
525 """
525 """
526 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
526 user_inherit_object_permissions = not ('hg.inherit_default_perms.false'
527 in self.permissions_global)
527 in self.permissions_global)
528
528
529 # defaults for repositories, taken from `default` user permissions
529 # defaults for repositories, taken from `default` user permissions
530 # on given repo
530 # on given repo
531 for perm in self.default_repo_perms:
531 for perm in self.default_repo_perms:
532 r_k = perm.UserRepoToPerm.repository.repo_name
532 r_k = perm.UserRepoToPerm.repository.repo_name
533 o = PermOrigin.REPO_DEFAULT
533 o = PermOrigin.REPO_DEFAULT
534 if perm.Repository.private and not (
534 if perm.Repository.private and not (
535 perm.Repository.user_id == self.user_id):
535 perm.Repository.user_id == self.user_id):
536 # disable defaults for private repos,
536 # disable defaults for private repos,
537 p = 'repository.none'
537 p = 'repository.none'
538 o = PermOrigin.REPO_PRIVATE
538 o = PermOrigin.REPO_PRIVATE
539 elif perm.Repository.user_id == self.user_id:
539 elif perm.Repository.user_id == self.user_id:
540 # set admin if owner
540 # set admin if owner
541 p = 'repository.admin'
541 p = 'repository.admin'
542 o = PermOrigin.REPO_OWNER
542 o = PermOrigin.REPO_OWNER
543 else:
543 else:
544 p = perm.Permission.permission_name
544 p = perm.Permission.permission_name
545 # if we decide this user isn't inheriting permissions from
545 # if we decide this user isn't inheriting permissions from
546 # default user we set him to .none so only explicit
546 # default user we set him to .none so only explicit
547 # permissions work
547 # permissions work
548 if not user_inherit_object_permissions:
548 if not user_inherit_object_permissions:
549 p = 'repository.none'
549 p = 'repository.none'
550 self.permissions_repositories[r_k] = p, o
550 self.permissions_repositories[r_k] = p, o
551
551
552 # defaults for repository groups taken from `default` user permission
552 # defaults for repository groups taken from `default` user permission
553 # on given group
553 # on given group
554 for perm in self.default_repo_groups_perms:
554 for perm in self.default_repo_groups_perms:
555 rg_k = perm.UserRepoGroupToPerm.group.group_name
555 rg_k = perm.UserRepoGroupToPerm.group.group_name
556 o = PermOrigin.REPOGROUP_DEFAULT
556 o = PermOrigin.REPOGROUP_DEFAULT
557 if perm.RepoGroup.user_id == self.user_id:
557 if perm.RepoGroup.user_id == self.user_id:
558 # set admin if owner
558 # set admin if owner
559 p = 'group.admin'
559 p = 'group.admin'
560 o = PermOrigin.REPOGROUP_OWNER
560 o = PermOrigin.REPOGROUP_OWNER
561 else:
561 else:
562 p = perm.Permission.permission_name
562 p = perm.Permission.permission_name
563
563
564 # if we decide this user isn't inheriting permissions from default
564 # if we decide this user isn't inheriting permissions from default
565 # user we set him to .none so only explicit permissions work
565 # user we set him to .none so only explicit permissions work
566 if not user_inherit_object_permissions:
566 if not user_inherit_object_permissions:
567 p = 'group.none'
567 p = 'group.none'
568 self.permissions_repository_groups[rg_k] = p, o
568 self.permissions_repository_groups[rg_k] = p, o
569
569
570 # defaults for user groups taken from `default` user permission
570 # defaults for user groups taken from `default` user permission
571 # on given user group
571 # on given user group
572 for perm in self.default_user_group_perms:
572 for perm in self.default_user_group_perms:
573 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
573 u_k = perm.UserUserGroupToPerm.user_group.users_group_name
574 o = PermOrigin.USERGROUP_DEFAULT
574 o = PermOrigin.USERGROUP_DEFAULT
575 if perm.UserGroup.user_id == self.user_id:
575 if perm.UserGroup.user_id == self.user_id:
576 # set admin if owner
576 # set admin if owner
577 p = 'usergroup.admin'
577 p = 'usergroup.admin'
578 o = PermOrigin.USERGROUP_OWNER
578 o = PermOrigin.USERGROUP_OWNER
579 else:
579 else:
580 p = perm.Permission.permission_name
580 p = perm.Permission.permission_name
581
581
582 # if we decide this user isn't inheriting permissions from default
582 # if we decide this user isn't inheriting permissions from default
583 # user we set him to .none so only explicit permissions work
583 # user we set him to .none so only explicit permissions work
584 if not user_inherit_object_permissions:
584 if not user_inherit_object_permissions:
585 p = 'usergroup.none'
585 p = 'usergroup.none'
586 self.permissions_user_groups[u_k] = p, o
586 self.permissions_user_groups[u_k] = p, o
587
587
588 def _calculate_repository_permissions(self):
588 def _calculate_repository_permissions(self):
589 """
589 """
590 Repository permissions for the current user.
590 Repository permissions for the current user.
591
591
592 Check if the user is part of user groups for this repository and
592 Check if the user is part of user groups for this repository and
593 fill in the permission from it. `_choose_permission` decides of which
593 fill in the permission from it. `_choose_permission` decides of which
594 permission should be selected based on selected method.
594 permission should be selected based on selected method.
595 """
595 """
596
596
597 # user group for repositories permissions
597 # user group for repositories permissions
598 user_repo_perms_from_user_group = Permission\
598 user_repo_perms_from_user_group = Permission\
599 .get_default_repo_perms_from_user_group(
599 .get_default_repo_perms_from_user_group(
600 self.user_id, self.scope_repo_id)
600 self.user_id, self.scope_repo_id)
601
601
602 multiple_counter = collections.defaultdict(int)
602 multiple_counter = collections.defaultdict(int)
603 for perm in user_repo_perms_from_user_group:
603 for perm in user_repo_perms_from_user_group:
604 r_k = perm.UserGroupRepoToPerm.repository.repo_name
604 r_k = perm.UserGroupRepoToPerm.repository.repo_name
605 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
605 ug_k = perm.UserGroupRepoToPerm.users_group.users_group_name
606 multiple_counter[r_k] += 1
606 multiple_counter[r_k] += 1
607 p = perm.Permission.permission_name
607 p = perm.Permission.permission_name
608 o = PermOrigin.REPO_USERGROUP % ug_k
608 o = PermOrigin.REPO_USERGROUP % ug_k
609
609
610 if perm.Repository.user_id == self.user_id:
610 if perm.Repository.user_id == self.user_id:
611 # set admin if owner
611 # set admin if owner
612 p = 'repository.admin'
612 p = 'repository.admin'
613 o = PermOrigin.REPO_OWNER
613 o = PermOrigin.REPO_OWNER
614 else:
614 else:
615 if multiple_counter[r_k] > 1:
615 if multiple_counter[r_k] > 1:
616 cur_perm = self.permissions_repositories[r_k]
616 cur_perm = self.permissions_repositories[r_k]
617 p = self._choose_permission(p, cur_perm)
617 p = self._choose_permission(p, cur_perm)
618 self.permissions_repositories[r_k] = p, o
618 self.permissions_repositories[r_k] = p, o
619
619
620 # user explicit permissions for repositories, overrides any specified
620 # user explicit permissions for repositories, overrides any specified
621 # by the group permission
621 # by the group permission
622 user_repo_perms = Permission.get_default_repo_perms(
622 user_repo_perms = Permission.get_default_repo_perms(
623 self.user_id, self.scope_repo_id)
623 self.user_id, self.scope_repo_id)
624 for perm in user_repo_perms:
624 for perm in user_repo_perms:
625 r_k = perm.UserRepoToPerm.repository.repo_name
625 r_k = perm.UserRepoToPerm.repository.repo_name
626 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
626 o = PermOrigin.REPO_USER % perm.UserRepoToPerm.user.username
627 # set admin if owner
627 # set admin if owner
628 if perm.Repository.user_id == self.user_id:
628 if perm.Repository.user_id == self.user_id:
629 p = 'repository.admin'
629 p = 'repository.admin'
630 o = PermOrigin.REPO_OWNER
630 o = PermOrigin.REPO_OWNER
631 else:
631 else:
632 p = perm.Permission.permission_name
632 p = perm.Permission.permission_name
633 if not self.explicit:
633 if not self.explicit:
634 cur_perm = self.permissions_repositories.get(
634 cur_perm = self.permissions_repositories.get(
635 r_k, 'repository.none')
635 r_k, 'repository.none')
636 p = self._choose_permission(p, cur_perm)
636 p = self._choose_permission(p, cur_perm)
637 self.permissions_repositories[r_k] = p, o
637 self.permissions_repositories[r_k] = p, o
638
638
639 def _calculate_repository_group_permissions(self):
639 def _calculate_repository_group_permissions(self):
640 """
640 """
641 Repository group permissions for the current user.
641 Repository group permissions for the current user.
642
642
643 Check if the user is part of user groups for repository groups and
643 Check if the user is part of user groups for repository groups and
644 fill in the permissions from it. `_choose_permmission` decides of which
644 fill in the permissions from it. `_choose_permmission` decides of which
645 permission should be selected based on selected method.
645 permission should be selected based on selected method.
646 """
646 """
647 # user group for repo groups permissions
647 # user group for repo groups permissions
648 user_repo_group_perms_from_user_group = Permission\
648 user_repo_group_perms_from_user_group = Permission\
649 .get_default_group_perms_from_user_group(
649 .get_default_group_perms_from_user_group(
650 self.user_id, self.scope_repo_group_id)
650 self.user_id, self.scope_repo_group_id)
651
651
652 multiple_counter = collections.defaultdict(int)
652 multiple_counter = collections.defaultdict(int)
653 for perm in user_repo_group_perms_from_user_group:
653 for perm in user_repo_group_perms_from_user_group:
654 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
654 g_k = perm.UserGroupRepoGroupToPerm.group.group_name
655 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
655 ug_k = perm.UserGroupRepoGroupToPerm.users_group.users_group_name
656 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
656 o = PermOrigin.REPOGROUP_USERGROUP % ug_k
657 multiple_counter[g_k] += 1
657 multiple_counter[g_k] += 1
658 p = perm.Permission.permission_name
658 p = perm.Permission.permission_name
659 if perm.RepoGroup.user_id == self.user_id:
659 if perm.RepoGroup.user_id == self.user_id:
660 # set admin if owner, even for member of other user group
660 # set admin if owner, even for member of other user group
661 p = 'group.admin'
661 p = 'group.admin'
662 o = PermOrigin.REPOGROUP_OWNER
662 o = PermOrigin.REPOGROUP_OWNER
663 else:
663 else:
664 if multiple_counter[g_k] > 1:
664 if multiple_counter[g_k] > 1:
665 cur_perm = self.permissions_repository_groups[g_k]
665 cur_perm = self.permissions_repository_groups[g_k]
666 p = self._choose_permission(p, cur_perm)
666 p = self._choose_permission(p, cur_perm)
667 self.permissions_repository_groups[g_k] = p, o
667 self.permissions_repository_groups[g_k] = p, o
668
668
669 # user explicit permissions for repository groups
669 # user explicit permissions for repository groups
670 user_repo_groups_perms = Permission.get_default_group_perms(
670 user_repo_groups_perms = Permission.get_default_group_perms(
671 self.user_id, self.scope_repo_group_id)
671 self.user_id, self.scope_repo_group_id)
672 for perm in user_repo_groups_perms:
672 for perm in user_repo_groups_perms:
673 rg_k = perm.UserRepoGroupToPerm.group.group_name
673 rg_k = perm.UserRepoGroupToPerm.group.group_name
674 u_k = perm.UserRepoGroupToPerm.user.username
674 u_k = perm.UserRepoGroupToPerm.user.username
675 o = PermOrigin.REPOGROUP_USER % u_k
675 o = PermOrigin.REPOGROUP_USER % u_k
676
676
677 if perm.RepoGroup.user_id == self.user_id:
677 if perm.RepoGroup.user_id == self.user_id:
678 # set admin if owner
678 # set admin if owner
679 p = 'group.admin'
679 p = 'group.admin'
680 o = PermOrigin.REPOGROUP_OWNER
680 o = PermOrigin.REPOGROUP_OWNER
681 else:
681 else:
682 p = perm.Permission.permission_name
682 p = perm.Permission.permission_name
683 if not self.explicit:
683 if not self.explicit:
684 cur_perm = self.permissions_repository_groups.get(
684 cur_perm = self.permissions_repository_groups.get(
685 rg_k, 'group.none')
685 rg_k, 'group.none')
686 p = self._choose_permission(p, cur_perm)
686 p = self._choose_permission(p, cur_perm)
687 self.permissions_repository_groups[rg_k] = p, o
687 self.permissions_repository_groups[rg_k] = p, o
688
688
689 def _calculate_user_group_permissions(self):
689 def _calculate_user_group_permissions(self):
690 """
690 """
691 User group permissions for the current user.
691 User group permissions for the current user.
692 """
692 """
693 # user group for user group permissions
693 # user group for user group permissions
694 user_group_from_user_group = Permission\
694 user_group_from_user_group = Permission\
695 .get_default_user_group_perms_from_user_group(
695 .get_default_user_group_perms_from_user_group(
696 self.user_id, self.scope_user_group_id)
696 self.user_id, self.scope_user_group_id)
697
697
698 multiple_counter = collections.defaultdict(int)
698 multiple_counter = collections.defaultdict(int)
699 for perm in user_group_from_user_group:
699 for perm in user_group_from_user_group:
700 g_k = perm.UserGroupUserGroupToPerm\
700 g_k = perm.UserGroupUserGroupToPerm\
701 .target_user_group.users_group_name
701 .target_user_group.users_group_name
702 u_k = perm.UserGroupUserGroupToPerm\
702 u_k = perm.UserGroupUserGroupToPerm\
703 .user_group.users_group_name
703 .user_group.users_group_name
704 o = PermOrigin.USERGROUP_USERGROUP % u_k
704 o = PermOrigin.USERGROUP_USERGROUP % u_k
705 multiple_counter[g_k] += 1
705 multiple_counter[g_k] += 1
706 p = perm.Permission.permission_name
706 p = perm.Permission.permission_name
707
707
708 if perm.UserGroup.user_id == self.user_id:
708 if perm.UserGroup.user_id == self.user_id:
709 # set admin if owner, even for member of other user group
709 # set admin if owner, even for member of other user group
710 p = 'usergroup.admin'
710 p = 'usergroup.admin'
711 o = PermOrigin.USERGROUP_OWNER
711 o = PermOrigin.USERGROUP_OWNER
712 else:
712 else:
713 if multiple_counter[g_k] > 1:
713 if multiple_counter[g_k] > 1:
714 cur_perm = self.permissions_user_groups[g_k]
714 cur_perm = self.permissions_user_groups[g_k]
715 p = self._choose_permission(p, cur_perm)
715 p = self._choose_permission(p, cur_perm)
716 self.permissions_user_groups[g_k] = p, o
716 self.permissions_user_groups[g_k] = p, o
717
717
718 # user explicit permission for user groups
718 # user explicit permission for user groups
719 user_user_groups_perms = Permission.get_default_user_group_perms(
719 user_user_groups_perms = Permission.get_default_user_group_perms(
720 self.user_id, self.scope_user_group_id)
720 self.user_id, self.scope_user_group_id)
721 for perm in user_user_groups_perms:
721 for perm in user_user_groups_perms:
722 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
722 ug_k = perm.UserUserGroupToPerm.user_group.users_group_name
723 u_k = perm.UserUserGroupToPerm.user.username
723 u_k = perm.UserUserGroupToPerm.user.username
724 o = PermOrigin.USERGROUP_USER % u_k
724 o = PermOrigin.USERGROUP_USER % u_k
725
725
726 if perm.UserGroup.user_id == self.user_id:
726 if perm.UserGroup.user_id == self.user_id:
727 # set admin if owner
727 # set admin if owner
728 p = 'usergroup.admin'
728 p = 'usergroup.admin'
729 o = PermOrigin.USERGROUP_OWNER
729 o = PermOrigin.USERGROUP_OWNER
730 else:
730 else:
731 p = perm.Permission.permission_name
731 p = perm.Permission.permission_name
732 if not self.explicit:
732 if not self.explicit:
733 cur_perm = self.permissions_user_groups.get(
733 cur_perm = self.permissions_user_groups.get(
734 ug_k, 'usergroup.none')
734 ug_k, 'usergroup.none')
735 p = self._choose_permission(p, cur_perm)
735 p = self._choose_permission(p, cur_perm)
736 self.permissions_user_groups[ug_k] = p, o
736 self.permissions_user_groups[ug_k] = p, o
737
737
738 def _choose_permission(self, new_perm, cur_perm):
738 def _choose_permission(self, new_perm, cur_perm):
739 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
739 new_perm_val = Permission.PERM_WEIGHTS[new_perm]
740 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
740 cur_perm_val = Permission.PERM_WEIGHTS[cur_perm]
741 if self.algo == 'higherwin':
741 if self.algo == 'higherwin':
742 if new_perm_val > cur_perm_val:
742 if new_perm_val > cur_perm_val:
743 return new_perm
743 return new_perm
744 return cur_perm
744 return cur_perm
745 elif self.algo == 'lowerwin':
745 elif self.algo == 'lowerwin':
746 if new_perm_val < cur_perm_val:
746 if new_perm_val < cur_perm_val:
747 return new_perm
747 return new_perm
748 return cur_perm
748 return cur_perm
749
749
750 def _permission_structure(self):
750 def _permission_structure(self):
751 return {
751 return {
752 'global': self.permissions_global,
752 'global': self.permissions_global,
753 'repositories': self.permissions_repositories,
753 'repositories': self.permissions_repositories,
754 'repositories_groups': self.permissions_repository_groups,
754 'repositories_groups': self.permissions_repository_groups,
755 'user_groups': self.permissions_user_groups,
755 'user_groups': self.permissions_user_groups,
756 }
756 }
757
757
758
758
759 def allowed_auth_token_access(controller_name, whitelist=None, auth_token=None):
759 def allowed_auth_token_access(controller_name, whitelist=None, auth_token=None):
760 """
760 """
761 Check if given controller_name is in whitelist of auth token access
761 Check if given controller_name is in whitelist of auth token access
762 """
762 """
763 if not whitelist:
763 if not whitelist:
764 from rhodecode import CONFIG
764 from rhodecode import CONFIG
765 whitelist = aslist(
765 whitelist = aslist(
766 CONFIG.get('api_access_controllers_whitelist'), sep=',')
766 CONFIG.get('api_access_controllers_whitelist'), sep=',')
767 log.debug(
767 log.debug(
768 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,))
768 'Allowed controllers for AUTH TOKEN access: %s' % (whitelist,))
769
769
770 auth_token_access_valid = False
770 auth_token_access_valid = False
771 for entry in whitelist:
771 for entry in whitelist:
772 if fnmatch.fnmatch(controller_name, entry):
772 if fnmatch.fnmatch(controller_name, entry):
773 auth_token_access_valid = True
773 auth_token_access_valid = True
774 break
774 break
775
775
776 if auth_token_access_valid:
776 if auth_token_access_valid:
777 log.debug('controller:%s matches entry in whitelist'
777 log.debug('controller:%s matches entry in whitelist'
778 % (controller_name,))
778 % (controller_name,))
779 else:
779 else:
780 msg = ('controller: %s does *NOT* match any entry in whitelist'
780 msg = ('controller: %s does *NOT* match any entry in whitelist'
781 % (controller_name,))
781 % (controller_name,))
782 if auth_token:
782 if auth_token:
783 # if we use auth token key and don't have access it's a warning
783 # if we use auth token key and don't have access it's a warning
784 log.warning(msg)
784 log.warning(msg)
785 else:
785 else:
786 log.debug(msg)
786 log.debug(msg)
787
787
788 return auth_token_access_valid
788 return auth_token_access_valid
789
789
790
790
791 class AuthUser(object):
791 class AuthUser(object):
792 """
792 """
793 A simple object that handles all attributes of user in RhodeCode
793 A simple object that handles all attributes of user in RhodeCode
794
794
795 It does lookup based on API key,given user, or user present in session
795 It does lookup based on API key,given user, or user present in session
796 Then it fills all required information for such user. It also checks if
796 Then it fills all required information for such user. It also checks if
797 anonymous access is enabled and if so, it returns default user as logged in
797 anonymous access is enabled and if so, it returns default user as logged in
798 """
798 """
799 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
799 GLOBAL_PERMS = [x[0] for x in Permission.PERMS]
800
800
801 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
801 def __init__(self, user_id=None, api_key=None, username=None, ip_addr=None):
802
802
803 self.user_id = user_id
803 self.user_id = user_id
804 self._api_key = api_key
804 self._api_key = api_key
805
805
806 self.api_key = None
806 self.api_key = None
807 self.feed_token = ''
807 self.feed_token = ''
808 self.username = username
808 self.username = username
809 self.ip_addr = ip_addr
809 self.ip_addr = ip_addr
810 self.name = ''
810 self.name = ''
811 self.lastname = ''
811 self.lastname = ''
812 self.email = ''
812 self.email = ''
813 self.is_authenticated = False
813 self.is_authenticated = False
814 self.admin = False
814 self.admin = False
815 self.inherit_default_permissions = False
815 self.inherit_default_permissions = False
816 self.password = ''
816 self.password = ''
817
817
818 self.anonymous_user = None # propagated on propagate_data
818 self.anonymous_user = None # propagated on propagate_data
819 self.propagate_data()
819 self.propagate_data()
820 self._instance = None
820 self._instance = None
821 self._permissions_scoped_cache = {} # used to bind scoped calculation
821 self._permissions_scoped_cache = {} # used to bind scoped calculation
822
822
823 @LazyProperty
823 @LazyProperty
824 def permissions(self):
824 def permissions(self):
825 return self.get_perms(user=self, cache=False)
825 return self.get_perms(user=self, cache=False)
826
826
827 def permissions_with_scope(self, scope):
827 def permissions_with_scope(self, scope):
828 """
828 """
829 Call the get_perms function with scoped data. The scope in that function
829 Call the get_perms function with scoped data. The scope in that function
830 narrows the SQL calls to the given ID of objects resulting in fetching
830 narrows the SQL calls to the given ID of objects resulting in fetching
831 Just particular permission we want to obtain. If scope is an empty dict
831 Just particular permission we want to obtain. If scope is an empty dict
832 then it basically narrows the scope to GLOBAL permissions only.
832 then it basically narrows the scope to GLOBAL permissions only.
833
833
834 :param scope: dict
834 :param scope: dict
835 """
835 """
836 if 'repo_name' in scope:
836 if 'repo_name' in scope:
837 obj = Repository.get_by_repo_name(scope['repo_name'])
837 obj = Repository.get_by_repo_name(scope['repo_name'])
838 if obj:
838 if obj:
839 scope['repo_id'] = obj.repo_id
839 scope['repo_id'] = obj.repo_id
840 _scope = {
840 _scope = {
841 'repo_id': -1,
841 'repo_id': -1,
842 'user_group_id': -1,
842 'user_group_id': -1,
843 'repo_group_id': -1,
843 'repo_group_id': -1,
844 }
844 }
845 _scope.update(scope)
845 _scope.update(scope)
846 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
846 cache_key = "_".join(map(safe_str, reduce(lambda a, b: a+b,
847 _scope.items())))
847 _scope.items())))
848 if cache_key not in self._permissions_scoped_cache:
848 if cache_key not in self._permissions_scoped_cache:
849 # store in cache to mimic how the @LazyProperty works,
849 # store in cache to mimic how the @LazyProperty works,
850 # the difference here is that we use the unique key calculated
850 # the difference here is that we use the unique key calculated
851 # from params and values
851 # from params and values
852 res = self.get_perms(user=self, cache=False, scope=_scope)
852 res = self.get_perms(user=self, cache=False, scope=_scope)
853 self._permissions_scoped_cache[cache_key] = res
853 self._permissions_scoped_cache[cache_key] = res
854 return self._permissions_scoped_cache[cache_key]
854 return self._permissions_scoped_cache[cache_key]
855
855
856 def get_instance(self):
856 def get_instance(self):
857 return User.get(self.user_id)
857 return User.get(self.user_id)
858
858
859 def update_lastactivity(self):
859 def update_lastactivity(self):
860 if self.user_id:
860 if self.user_id:
861 User.get(self.user_id).update_lastactivity()
861 User.get(self.user_id).update_lastactivity()
862
862
863 def propagate_data(self):
863 def propagate_data(self):
864 """
864 """
865 Fills in user data and propagates values to this instance. Maps fetched
865 Fills in user data and propagates values to this instance. Maps fetched
866 user attributes to this class instance attributes
866 user attributes to this class instance attributes
867 """
867 """
868 log.debug('starting data propagation for new potential AuthUser')
868 log.debug('starting data propagation for new potential AuthUser')
869 user_model = UserModel()
869 user_model = UserModel()
870 anon_user = self.anonymous_user = User.get_default_user(cache=True)
870 anon_user = self.anonymous_user = User.get_default_user(cache=True)
871 is_user_loaded = False
871 is_user_loaded = False
872
872
873 # lookup by userid
873 # lookup by userid
874 if self.user_id is not None and self.user_id != anon_user.user_id:
874 if self.user_id is not None and self.user_id != anon_user.user_id:
875 log.debug('Trying Auth User lookup by USER ID: `%s`' % self.user_id)
875 log.debug('Trying Auth User lookup by USER ID: `%s`' % self.user_id)
876 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
876 is_user_loaded = user_model.fill_data(self, user_id=self.user_id)
877
877
878 # try go get user by api key
878 # try go get user by api key
879 elif self._api_key and self._api_key != anon_user.api_key:
879 elif self._api_key and self._api_key != anon_user.api_key:
880 log.debug('Trying Auth User lookup by API KEY: `%s`' % self._api_key)
880 log.debug('Trying Auth User lookup by API KEY: `%s`' % self._api_key)
881 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
881 is_user_loaded = user_model.fill_data(self, api_key=self._api_key)
882
882
883 # lookup by username
883 # lookup by username
884 elif self.username:
884 elif self.username:
885 log.debug('Trying Auth User lookup by USER NAME: `%s`' % self.username)
885 log.debug('Trying Auth User lookup by USER NAME: `%s`' % self.username)
886 is_user_loaded = user_model.fill_data(self, username=self.username)
886 is_user_loaded = user_model.fill_data(self, username=self.username)
887 else:
887 else:
888 log.debug('No data in %s that could been used to log in' % self)
888 log.debug('No data in %s that could been used to log in' % self)
889
889
890 if not is_user_loaded:
890 if not is_user_loaded:
891 log.debug('Failed to load user. Fallback to default user')
891 log.debug('Failed to load user. Fallback to default user')
892 # if we cannot authenticate user try anonymous
892 # if we cannot authenticate user try anonymous
893 if anon_user.active:
893 if anon_user.active:
894 user_model.fill_data(self, user_id=anon_user.user_id)
894 user_model.fill_data(self, user_id=anon_user.user_id)
895 # then we set this user is logged in
895 # then we set this user is logged in
896 self.is_authenticated = True
896 self.is_authenticated = True
897 else:
897 else:
898 # in case of disabled anonymous user we reset some of the
898 # in case of disabled anonymous user we reset some of the
899 # parameters so such user is "corrupted", skipping the fill_data
899 # parameters so such user is "corrupted", skipping the fill_data
900 for attr in ['user_id', 'username', 'admin', 'active']:
900 for attr in ['user_id', 'username', 'admin', 'active']:
901 setattr(self, attr, None)
901 setattr(self, attr, None)
902 self.is_authenticated = False
902 self.is_authenticated = False
903
903
904 if not self.username:
904 if not self.username:
905 self.username = 'None'
905 self.username = 'None'
906
906
907 log.debug('Auth User is now %s' % self)
907 log.debug('Auth User is now %s' % self)
908
908
909 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
909 def get_perms(self, user, scope=None, explicit=True, algo='higherwin',
910 cache=False):
910 cache=False):
911 """
911 """
912 Fills user permission attribute with permissions taken from database
912 Fills user permission attribute with permissions taken from database
913 works for permissions given for repositories, and for permissions that
913 works for permissions given for repositories, and for permissions that
914 are granted to groups
914 are granted to groups
915
915
916 :param user: instance of User object from database
916 :param user: instance of User object from database
917 :param explicit: In case there are permissions both for user and a group
917 :param explicit: In case there are permissions both for user and a group
918 that user is part of, explicit flag will defiine if user will
918 that user is part of, explicit flag will defiine if user will
919 explicitly override permissions from group, if it's False it will
919 explicitly override permissions from group, if it's False it will
920 make decision based on the algo
920 make decision based on the algo
921 :param algo: algorithm to decide what permission should be choose if
921 :param algo: algorithm to decide what permission should be choose if
922 it's multiple defined, eg user in two different groups. It also
922 it's multiple defined, eg user in two different groups. It also
923 decides if explicit flag is turned off how to specify the permission
923 decides if explicit flag is turned off how to specify the permission
924 for case when user is in a group + have defined separate permission
924 for case when user is in a group + have defined separate permission
925 """
925 """
926 user_id = user.user_id
926 user_id = user.user_id
927 user_is_admin = user.is_admin
927 user_is_admin = user.is_admin
928
928
929 # inheritance of global permissions like create repo/fork repo etc
929 # inheritance of global permissions like create repo/fork repo etc
930 user_inherit_default_permissions = user.inherit_default_permissions
930 user_inherit_default_permissions = user.inherit_default_permissions
931
931
932 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
932 log.debug('Computing PERMISSION tree for scope %s' % (scope, ))
933 compute = caches.conditional_cache(
933 compute = caches.conditional_cache(
934 'short_term', 'cache_desc',
934 'short_term', 'cache_desc',
935 condition=cache, func=_cached_perms_data)
935 condition=cache, func=_cached_perms_data)
936 result = compute(user_id, scope, user_is_admin,
936 result = compute(user_id, scope, user_is_admin,
937 user_inherit_default_permissions, explicit, algo)
937 user_inherit_default_permissions, explicit, algo)
938
938
939 result_repr = []
939 result_repr = []
940 for k in result:
940 for k in result:
941 result_repr.append((k, len(result[k])))
941 result_repr.append((k, len(result[k])))
942
942
943 log.debug('PERMISSION tree computed %s' % (result_repr,))
943 log.debug('PERMISSION tree computed %s' % (result_repr,))
944 return result
944 return result
945
945
946 @property
946 @property
947 def is_default(self):
947 def is_default(self):
948 return self.username == User.DEFAULT_USER
948 return self.username == User.DEFAULT_USER
949
949
950 @property
950 @property
951 def is_admin(self):
951 def is_admin(self):
952 return self.admin
952 return self.admin
953
953
954 @property
954 @property
955 def is_user_object(self):
955 def is_user_object(self):
956 return self.user_id is not None
956 return self.user_id is not None
957
957
958 @property
958 @property
959 def repositories_admin(self):
959 def repositories_admin(self):
960 """
960 """
961 Returns list of repositories you're an admin of
961 Returns list of repositories you're an admin of
962 """
962 """
963 return [
963 return [
964 x[0] for x in self.permissions['repositories'].iteritems()
964 x[0] for x in self.permissions['repositories'].iteritems()
965 if x[1] == 'repository.admin']
965 if x[1] == 'repository.admin']
966
966
967 @property
967 @property
968 def repository_groups_admin(self):
968 def repository_groups_admin(self):
969 """
969 """
970 Returns list of repository groups you're an admin of
970 Returns list of repository groups you're an admin of
971 """
971 """
972 return [
972 return [
973 x[0] for x in self.permissions['repositories_groups'].iteritems()
973 x[0] for x in self.permissions['repositories_groups'].iteritems()
974 if x[1] == 'group.admin']
974 if x[1] == 'group.admin']
975
975
976 @property
976 @property
977 def user_groups_admin(self):
977 def user_groups_admin(self):
978 """
978 """
979 Returns list of user groups you're an admin of
979 Returns list of user groups you're an admin of
980 """
980 """
981 return [
981 return [
982 x[0] for x in self.permissions['user_groups'].iteritems()
982 x[0] for x in self.permissions['user_groups'].iteritems()
983 if x[1] == 'usergroup.admin']
983 if x[1] == 'usergroup.admin']
984
984
985 @property
985 @property
986 def ip_allowed(self):
986 def ip_allowed(self):
987 """
987 """
988 Checks if ip_addr used in constructor is allowed from defined list of
988 Checks if ip_addr used in constructor is allowed from defined list of
989 allowed ip_addresses for user
989 allowed ip_addresses for user
990
990
991 :returns: boolean, True if ip is in allowed ip range
991 :returns: boolean, True if ip is in allowed ip range
992 """
992 """
993 # check IP
993 # check IP
994 inherit = self.inherit_default_permissions
994 inherit = self.inherit_default_permissions
995 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
995 return AuthUser.check_ip_allowed(self.user_id, self.ip_addr,
996 inherit_from_default=inherit)
996 inherit_from_default=inherit)
997 @property
997 @property
998 def personal_repo_group(self):
998 def personal_repo_group(self):
999 return RepoGroup.get_user_personal_repo_group(self.user_id)
999 return RepoGroup.get_user_personal_repo_group(self.user_id)
1000
1000
1001 @classmethod
1001 @classmethod
1002 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1002 def check_ip_allowed(cls, user_id, ip_addr, inherit_from_default):
1003 allowed_ips = AuthUser.get_allowed_ips(
1003 allowed_ips = AuthUser.get_allowed_ips(
1004 user_id, cache=True, inherit_from_default=inherit_from_default)
1004 user_id, cache=True, inherit_from_default=inherit_from_default)
1005 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1005 if check_ip_access(source_ip=ip_addr, allowed_ips=allowed_ips):
1006 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1006 log.debug('IP:%s is in range of %s' % (ip_addr, allowed_ips))
1007 return True
1007 return True
1008 else:
1008 else:
1009 log.info('Access for IP:%s forbidden, '
1009 log.info('Access for IP:%s forbidden, '
1010 'not in %s' % (ip_addr, allowed_ips))
1010 'not in %s' % (ip_addr, allowed_ips))
1011 return False
1011 return False
1012
1012
1013 def __repr__(self):
1013 def __repr__(self):
1014 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1014 return "<AuthUser('id:%s[%s] ip:%s auth:%s')>"\
1015 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1015 % (self.user_id, self.username, self.ip_addr, self.is_authenticated)
1016
1016
1017 def set_authenticated(self, authenticated=True):
1017 def set_authenticated(self, authenticated=True):
1018 if self.user_id != self.anonymous_user.user_id:
1018 if self.user_id != self.anonymous_user.user_id:
1019 self.is_authenticated = authenticated
1019 self.is_authenticated = authenticated
1020
1020
1021 def get_cookie_store(self):
1021 def get_cookie_store(self):
1022 return {
1022 return {
1023 'username': self.username,
1023 'username': self.username,
1024 'password': md5(self.password),
1024 'password': md5(self.password),
1025 'user_id': self.user_id,
1025 'user_id': self.user_id,
1026 'is_authenticated': self.is_authenticated
1026 'is_authenticated': self.is_authenticated
1027 }
1027 }
1028
1028
1029 @classmethod
1029 @classmethod
1030 def from_cookie_store(cls, cookie_store):
1030 def from_cookie_store(cls, cookie_store):
1031 """
1031 """
1032 Creates AuthUser from a cookie store
1032 Creates AuthUser from a cookie store
1033
1033
1034 :param cls:
1034 :param cls:
1035 :param cookie_store:
1035 :param cookie_store:
1036 """
1036 """
1037 user_id = cookie_store.get('user_id')
1037 user_id = cookie_store.get('user_id')
1038 username = cookie_store.get('username')
1038 username = cookie_store.get('username')
1039 api_key = cookie_store.get('api_key')
1039 api_key = cookie_store.get('api_key')
1040 return AuthUser(user_id, api_key, username)
1040 return AuthUser(user_id, api_key, username)
1041
1041
1042 @classmethod
1042 @classmethod
1043 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1043 def get_allowed_ips(cls, user_id, cache=False, inherit_from_default=False):
1044 _set = set()
1044 _set = set()
1045
1045
1046 if inherit_from_default:
1046 if inherit_from_default:
1047 default_ips = UserIpMap.query().filter(
1047 default_ips = UserIpMap.query().filter(
1048 UserIpMap.user == User.get_default_user(cache=True))
1048 UserIpMap.user == User.get_default_user(cache=True))
1049 if cache:
1049 if cache:
1050 default_ips = default_ips.options(FromCache("sql_cache_short",
1050 default_ips = default_ips.options(FromCache("sql_cache_short",
1051 "get_user_ips_default"))
1051 "get_user_ips_default"))
1052
1052
1053 # populate from default user
1053 # populate from default user
1054 for ip in default_ips:
1054 for ip in default_ips:
1055 try:
1055 try:
1056 _set.add(ip.ip_addr)
1056 _set.add(ip.ip_addr)
1057 except ObjectDeletedError:
1057 except ObjectDeletedError:
1058 # since we use heavy caching sometimes it happens that
1058 # since we use heavy caching sometimes it happens that
1059 # we get deleted objects here, we just skip them
1059 # we get deleted objects here, we just skip them
1060 pass
1060 pass
1061
1061
1062 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1062 user_ips = UserIpMap.query().filter(UserIpMap.user_id == user_id)
1063 if cache:
1063 if cache:
1064 user_ips = user_ips.options(FromCache("sql_cache_short",
1064 user_ips = user_ips.options(FromCache("sql_cache_short",
1065 "get_user_ips_%s" % user_id))
1065 "get_user_ips_%s" % user_id))
1066
1066
1067 for ip in user_ips:
1067 for ip in user_ips:
1068 try:
1068 try:
1069 _set.add(ip.ip_addr)
1069 _set.add(ip.ip_addr)
1070 except ObjectDeletedError:
1070 except ObjectDeletedError:
1071 # since we use heavy caching sometimes it happens that we get
1071 # since we use heavy caching sometimes it happens that we get
1072 # deleted objects here, we just skip them
1072 # deleted objects here, we just skip them
1073 pass
1073 pass
1074 return _set or set(['0.0.0.0/0', '::/0'])
1074 return _set or set(['0.0.0.0/0', '::/0'])
1075
1075
1076
1076
1077 def set_available_permissions(config):
1077 def set_available_permissions(config):
1078 """
1078 """
1079 This function will propagate pylons globals with all available defined
1079 This function will propagate pylons globals with all available defined
1080 permission given in db. We don't want to check each time from db for new
1080 permission given in db. We don't want to check each time from db for new
1081 permissions since adding a new permission also requires application restart
1081 permissions since adding a new permission also requires application restart
1082 ie. to decorate new views with the newly created permission
1082 ie. to decorate new views with the newly created permission
1083
1083
1084 :param config: current pylons config instance
1084 :param config: current pylons config instance
1085
1085
1086 """
1086 """
1087 log.info('getting information about all available permissions')
1087 log.info('getting information about all available permissions')
1088 try:
1088 try:
1089 sa = meta.Session
1089 sa = meta.Session
1090 all_perms = sa.query(Permission).all()
1090 all_perms = sa.query(Permission).all()
1091 config['available_permissions'] = [x.permission_name for x in all_perms]
1091 config['available_permissions'] = [x.permission_name for x in all_perms]
1092 except Exception:
1092 except Exception:
1093 log.error(traceback.format_exc())
1093 log.error(traceback.format_exc())
1094 finally:
1094 finally:
1095 meta.Session.remove()
1095 meta.Session.remove()
1096
1096
1097
1097
1098 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1098 def get_csrf_token(session=None, force_new=False, save_if_missing=True):
1099 """
1099 """
1100 Return the current authentication token, creating one if one doesn't
1100 Return the current authentication token, creating one if one doesn't
1101 already exist and the save_if_missing flag is present.
1101 already exist and the save_if_missing flag is present.
1102
1102
1103 :param session: pass in the pylons session, else we use the global ones
1103 :param session: pass in the pylons session, else we use the global ones
1104 :param force_new: force to re-generate the token and store it in session
1104 :param force_new: force to re-generate the token and store it in session
1105 :param save_if_missing: save the newly generated token if it's missing in
1105 :param save_if_missing: save the newly generated token if it's missing in
1106 session
1106 session
1107 """
1107 """
1108 if not session:
1108 if not session:
1109 from pylons import session
1109 from pylons import session
1110
1110
1111 if (csrf_token_key not in session and save_if_missing) or force_new:
1111 if (csrf_token_key not in session and save_if_missing) or force_new:
1112 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1112 token = hashlib.sha1(str(random.getrandbits(128))).hexdigest()
1113 session[csrf_token_key] = token
1113 session[csrf_token_key] = token
1114 if hasattr(session, 'save'):
1114 if hasattr(session, 'save'):
1115 session.save()
1115 session.save()
1116 return session.get(csrf_token_key)
1116 return session.get(csrf_token_key)
1117
1117
1118
1118
1119 # CHECK DECORATORS
1119 # CHECK DECORATORS
1120 class CSRFRequired(object):
1120 class CSRFRequired(object):
1121 """
1121 """
1122 Decorator for authenticating a form
1122 Decorator for authenticating a form
1123
1123
1124 This decorator uses an authorization token stored in the client's
1124 This decorator uses an authorization token stored in the client's
1125 session for prevention of certain Cross-site request forgery (CSRF)
1125 session for prevention of certain Cross-site request forgery (CSRF)
1126 attacks (See
1126 attacks (See
1127 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1127 http://en.wikipedia.org/wiki/Cross-site_request_forgery for more
1128 information).
1128 information).
1129
1129
1130 For use with the ``webhelpers.secure_form`` helper functions.
1130 For use with the ``webhelpers.secure_form`` helper functions.
1131
1131
1132 """
1132 """
1133 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1133 def __init__(self, token=csrf_token_key, header='X-CSRF-Token',
1134 except_methods=None):
1134 except_methods=None):
1135 self.token = token
1135 self.token = token
1136 self.header = header
1136 self.header = header
1137 self.except_methods = except_methods or []
1137 self.except_methods = except_methods or []
1138
1138
1139 def __call__(self, func):
1139 def __call__(self, func):
1140 return get_cython_compat_decorator(self.__wrapper, func)
1140 return get_cython_compat_decorator(self.__wrapper, func)
1141
1141
1142 def _get_csrf(self, _request):
1142 def _get_csrf(self, _request):
1143 return _request.POST.get(self.token, _request.headers.get(self.header))
1143 return _request.POST.get(self.token, _request.headers.get(self.header))
1144
1144
1145 def check_csrf(self, _request, cur_token):
1145 def check_csrf(self, _request, cur_token):
1146 supplied_token = self._get_csrf(_request)
1146 supplied_token = self._get_csrf(_request)
1147 return supplied_token and supplied_token == cur_token
1147 return supplied_token and supplied_token == cur_token
1148
1148
1149 def __wrapper(self, func, *fargs, **fkwargs):
1149 def __wrapper(self, func, *fargs, **fkwargs):
1150 if request.method in self.except_methods:
1150 if request.method in self.except_methods:
1151 return func(*fargs, **fkwargs)
1151 return func(*fargs, **fkwargs)
1152
1152
1153 cur_token = get_csrf_token(save_if_missing=False)
1153 cur_token = get_csrf_token(save_if_missing=False)
1154 if self.check_csrf(request, cur_token):
1154 if self.check_csrf(request, cur_token):
1155 if request.POST.get(self.token):
1155 if request.POST.get(self.token):
1156 del request.POST[self.token]
1156 del request.POST[self.token]
1157 return func(*fargs, **fkwargs)
1157 return func(*fargs, **fkwargs)
1158 else:
1158 else:
1159 reason = 'token-missing'
1159 reason = 'token-missing'
1160 supplied_token = self._get_csrf(request)
1160 supplied_token = self._get_csrf(request)
1161 if supplied_token and cur_token != supplied_token:
1161 if supplied_token and cur_token != supplied_token:
1162 reason = 'token-mismatch [%s:%s]' % (cur_token or ''[:6],
1162 reason = 'token-mismatch [%s:%s]' % (cur_token or ''[:6],
1163 supplied_token or ''[:6])
1163 supplied_token or ''[:6])
1164
1164
1165 csrf_message = \
1165 csrf_message = \
1166 ("Cross-site request forgery detected, request denied. See "
1166 ("Cross-site request forgery detected, request denied. See "
1167 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1167 "http://en.wikipedia.org/wiki/Cross-site_request_forgery for "
1168 "more information.")
1168 "more information.")
1169 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1169 log.warn('Cross-site request forgery detected, request %r DENIED: %s '
1170 'REMOTE_ADDR:%s, HEADERS:%s' % (
1170 'REMOTE_ADDR:%s, HEADERS:%s' % (
1171 request, reason, request.remote_addr, request.headers))
1171 request, reason, request.remote_addr, request.headers))
1172
1172
1173 raise HTTPForbidden(explanation=csrf_message)
1173 raise HTTPForbidden(explanation=csrf_message)
1174
1174
1175
1175
1176 class LoginRequired(object):
1176 class LoginRequired(object):
1177 """
1177 """
1178 Must be logged in to execute this function else
1178 Must be logged in to execute this function else
1179 redirect to login page
1179 redirect to login page
1180
1180
1181 :param api_access: if enabled this checks only for valid auth token
1181 :param api_access: if enabled this checks only for valid auth token
1182 and grants access based on valid token
1182 and grants access based on valid token
1183 """
1183 """
1184 def __init__(self, auth_token_access=None):
1184 def __init__(self, auth_token_access=None):
1185 self.auth_token_access = auth_token_access
1185 self.auth_token_access = auth_token_access
1186
1186
1187 def __call__(self, func):
1187 def __call__(self, func):
1188 return get_cython_compat_decorator(self.__wrapper, func)
1188 return get_cython_compat_decorator(self.__wrapper, func)
1189
1189
1190 def __wrapper(self, func, *fargs, **fkwargs):
1190 def __wrapper(self, func, *fargs, **fkwargs):
1191 from rhodecode.lib import helpers as h
1191 from rhodecode.lib import helpers as h
1192 cls = fargs[0]
1192 cls = fargs[0]
1193 user = cls._rhodecode_user
1193 user = cls._rhodecode_user
1194 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1194 loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
1195 log.debug('Starting login restriction checks for user: %s' % (user,))
1195 log.debug('Starting login restriction checks for user: %s' % (user,))
1196 # check if our IP is allowed
1196 # check if our IP is allowed
1197 ip_access_valid = True
1197 ip_access_valid = True
1198 if not user.ip_allowed:
1198 if not user.ip_allowed:
1199 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1199 h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr,))),
1200 category='warning')
1200 category='warning')
1201 ip_access_valid = False
1201 ip_access_valid = False
1202
1202
1203 # check if we used an APIKEY and it's a valid one
1203 # check if we used an APIKEY and it's a valid one
1204 # defined white-list of controllers which API access will be enabled
1204 # defined white-list of controllers which API access will be enabled
1205 _auth_token = request.GET.get(
1205 _auth_token = request.GET.get(
1206 'auth_token', '') or request.GET.get('api_key', '')
1206 'auth_token', '') or request.GET.get('api_key', '')
1207 auth_token_access_valid = allowed_auth_token_access(
1207 auth_token_access_valid = allowed_auth_token_access(
1208 loc, auth_token=_auth_token)
1208 loc, auth_token=_auth_token)
1209
1209
1210 # explicit controller is enabled or API is in our whitelist
1210 # explicit controller is enabled or API is in our whitelist
1211 if self.auth_token_access or auth_token_access_valid:
1211 if self.auth_token_access or auth_token_access_valid:
1212 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1212 log.debug('Checking AUTH TOKEN access for %s' % (cls,))
1213 db_user = user.get_instance()
1213 db_user = user.get_instance()
1214
1214
1215 if db_user:
1215 if db_user:
1216 if self.auth_token_access:
1216 if self.auth_token_access:
1217 roles = self.auth_token_access
1217 roles = self.auth_token_access
1218 else:
1218 else:
1219 roles = [UserApiKeys.ROLE_HTTP]
1219 roles = [UserApiKeys.ROLE_HTTP]
1220 token_match = db_user.authenticate_by_token(
1220 token_match = db_user.authenticate_by_token(
1221 _auth_token, roles=roles, include_builtin_token=True)
1221 _auth_token, roles=roles)
1222 else:
1222 else:
1223 log.debug('Unable to fetch db instance for auth user: %s', user)
1223 log.debug('Unable to fetch db instance for auth user: %s', user)
1224 token_match = False
1224 token_match = False
1225
1225
1226 if _auth_token and token_match:
1226 if _auth_token and token_match:
1227 auth_token_access_valid = True
1227 auth_token_access_valid = True
1228 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1228 log.debug('AUTH TOKEN ****%s is VALID' % (_auth_token[-4:],))
1229 else:
1229 else:
1230 auth_token_access_valid = False
1230 auth_token_access_valid = False
1231 if not _auth_token:
1231 if not _auth_token:
1232 log.debug("AUTH TOKEN *NOT* present in request")
1232 log.debug("AUTH TOKEN *NOT* present in request")
1233 else:
1233 else:
1234 log.warning(
1234 log.warning(
1235 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1235 "AUTH TOKEN ****%s *NOT* valid" % _auth_token[-4:])
1236
1236
1237 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1237 log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
1238 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1238 reason = 'RHODECODE_AUTH' if user.is_authenticated \
1239 else 'AUTH_TOKEN_AUTH'
1239 else 'AUTH_TOKEN_AUTH'
1240
1240
1241 if ip_access_valid and (
1241 if ip_access_valid and (
1242 user.is_authenticated or auth_token_access_valid):
1242 user.is_authenticated or auth_token_access_valid):
1243 log.info(
1243 log.info(
1244 'user %s authenticating with:%s IS authenticated on func %s'
1244 'user %s authenticating with:%s IS authenticated on func %s'
1245 % (user, reason, loc))
1245 % (user, reason, loc))
1246
1246
1247 # update user data to check last activity
1247 # update user data to check last activity
1248 user.update_lastactivity()
1248 user.update_lastactivity()
1249 Session().commit()
1249 Session().commit()
1250 return func(*fargs, **fkwargs)
1250 return func(*fargs, **fkwargs)
1251 else:
1251 else:
1252 log.warning(
1252 log.warning(
1253 'user %s authenticating with:%s NOT authenticated on '
1253 'user %s authenticating with:%s NOT authenticated on '
1254 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1254 'func: %s: IP_ACCESS:%s AUTH_TOKEN_ACCESS:%s'
1255 % (user, reason, loc, ip_access_valid,
1255 % (user, reason, loc, ip_access_valid,
1256 auth_token_access_valid))
1256 auth_token_access_valid))
1257 # we preserve the get PARAM
1257 # we preserve the get PARAM
1258 came_from = request.path_qs
1258 came_from = request.path_qs
1259
1259
1260 log.debug('redirecting to login page with %s' % (came_from,))
1260 log.debug('redirecting to login page with %s' % (came_from,))
1261 return redirect(
1261 return redirect(
1262 h.route_path('login', _query={'came_from': came_from}))
1262 h.route_path('login', _query={'came_from': came_from}))
1263
1263
1264
1264
1265 class NotAnonymous(object):
1265 class NotAnonymous(object):
1266 """
1266 """
1267 Must be logged in to execute this function else
1267 Must be logged in to execute this function else
1268 redirect to login page"""
1268 redirect to login page"""
1269
1269
1270 def __call__(self, func):
1270 def __call__(self, func):
1271 return get_cython_compat_decorator(self.__wrapper, func)
1271 return get_cython_compat_decorator(self.__wrapper, func)
1272
1272
1273 def __wrapper(self, func, *fargs, **fkwargs):
1273 def __wrapper(self, func, *fargs, **fkwargs):
1274 cls = fargs[0]
1274 cls = fargs[0]
1275 self.user = cls._rhodecode_user
1275 self.user = cls._rhodecode_user
1276
1276
1277 log.debug('Checking if user is not anonymous @%s' % cls)
1277 log.debug('Checking if user is not anonymous @%s' % cls)
1278
1278
1279 anonymous = self.user.username == User.DEFAULT_USER
1279 anonymous = self.user.username == User.DEFAULT_USER
1280
1280
1281 if anonymous:
1281 if anonymous:
1282 came_from = request.path_qs
1282 came_from = request.path_qs
1283
1283
1284 import rhodecode.lib.helpers as h
1284 import rhodecode.lib.helpers as h
1285 h.flash(_('You need to be a registered user to '
1285 h.flash(_('You need to be a registered user to '
1286 'perform this action'),
1286 'perform this action'),
1287 category='warning')
1287 category='warning')
1288 return redirect(
1288 return redirect(
1289 h.route_path('login', _query={'came_from': came_from}))
1289 h.route_path('login', _query={'came_from': came_from}))
1290 else:
1290 else:
1291 return func(*fargs, **fkwargs)
1291 return func(*fargs, **fkwargs)
1292
1292
1293
1293
1294 class XHRRequired(object):
1294 class XHRRequired(object):
1295 def __call__(self, func):
1295 def __call__(self, func):
1296 return get_cython_compat_decorator(self.__wrapper, func)
1296 return get_cython_compat_decorator(self.__wrapper, func)
1297
1297
1298 def __wrapper(self, func, *fargs, **fkwargs):
1298 def __wrapper(self, func, *fargs, **fkwargs):
1299 log.debug('Checking if request is XMLHttpRequest (XHR)')
1299 log.debug('Checking if request is XMLHttpRequest (XHR)')
1300 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1300 xhr_message = 'This is not a valid XMLHttpRequest (XHR) request'
1301 if not request.is_xhr:
1301 if not request.is_xhr:
1302 abort(400, detail=xhr_message)
1302 abort(400, detail=xhr_message)
1303
1303
1304 return func(*fargs, **fkwargs)
1304 return func(*fargs, **fkwargs)
1305
1305
1306
1306
1307 class HasAcceptedRepoType(object):
1307 class HasAcceptedRepoType(object):
1308 """
1308 """
1309 Check if requested repo is within given repo type aliases
1309 Check if requested repo is within given repo type aliases
1310
1310
1311 TODO: anderson: not sure where to put this decorator
1311 TODO: anderson: not sure where to put this decorator
1312 """
1312 """
1313
1313
1314 def __init__(self, *repo_type_list):
1314 def __init__(self, *repo_type_list):
1315 self.repo_type_list = set(repo_type_list)
1315 self.repo_type_list = set(repo_type_list)
1316
1316
1317 def __call__(self, func):
1317 def __call__(self, func):
1318 return get_cython_compat_decorator(self.__wrapper, func)
1318 return get_cython_compat_decorator(self.__wrapper, func)
1319
1319
1320 def __wrapper(self, func, *fargs, **fkwargs):
1320 def __wrapper(self, func, *fargs, **fkwargs):
1321 cls = fargs[0]
1321 cls = fargs[0]
1322 rhodecode_repo = cls.rhodecode_repo
1322 rhodecode_repo = cls.rhodecode_repo
1323
1323
1324 log.debug('%s checking repo type for %s in %s',
1324 log.debug('%s checking repo type for %s in %s',
1325 self.__class__.__name__,
1325 self.__class__.__name__,
1326 rhodecode_repo.alias, self.repo_type_list)
1326 rhodecode_repo.alias, self.repo_type_list)
1327
1327
1328 if rhodecode_repo.alias in self.repo_type_list:
1328 if rhodecode_repo.alias in self.repo_type_list:
1329 return func(*fargs, **fkwargs)
1329 return func(*fargs, **fkwargs)
1330 else:
1330 else:
1331 import rhodecode.lib.helpers as h
1331 import rhodecode.lib.helpers as h
1332 h.flash(h.literal(
1332 h.flash(h.literal(
1333 _('Action not supported for %s.' % rhodecode_repo.alias)),
1333 _('Action not supported for %s.' % rhodecode_repo.alias)),
1334 category='warning')
1334 category='warning')
1335 return redirect(
1335 return redirect(
1336 url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name))
1336 url('summary_home', repo_name=cls.rhodecode_db_repo.repo_name))
1337
1337
1338
1338
1339 class PermsDecorator(object):
1339 class PermsDecorator(object):
1340 """
1340 """
1341 Base class for controller decorators, we extract the current user from
1341 Base class for controller decorators, we extract the current user from
1342 the class itself, which has it stored in base controllers
1342 the class itself, which has it stored in base controllers
1343 """
1343 """
1344
1344
1345 def __init__(self, *required_perms):
1345 def __init__(self, *required_perms):
1346 self.required_perms = set(required_perms)
1346 self.required_perms = set(required_perms)
1347
1347
1348 def __call__(self, func):
1348 def __call__(self, func):
1349 return get_cython_compat_decorator(self.__wrapper, func)
1349 return get_cython_compat_decorator(self.__wrapper, func)
1350
1350
1351 def __wrapper(self, func, *fargs, **fkwargs):
1351 def __wrapper(self, func, *fargs, **fkwargs):
1352 cls = fargs[0]
1352 cls = fargs[0]
1353 _user = cls._rhodecode_user
1353 _user = cls._rhodecode_user
1354
1354
1355 log.debug('checking %s permissions %s for %s %s',
1355 log.debug('checking %s permissions %s for %s %s',
1356 self.__class__.__name__, self.required_perms, cls, _user)
1356 self.__class__.__name__, self.required_perms, cls, _user)
1357
1357
1358 if self.check_permissions(_user):
1358 if self.check_permissions(_user):
1359 log.debug('Permission granted for %s %s', cls, _user)
1359 log.debug('Permission granted for %s %s', cls, _user)
1360 return func(*fargs, **fkwargs)
1360 return func(*fargs, **fkwargs)
1361
1361
1362 else:
1362 else:
1363 log.debug('Permission denied for %s %s', cls, _user)
1363 log.debug('Permission denied for %s %s', cls, _user)
1364 anonymous = _user.username == User.DEFAULT_USER
1364 anonymous = _user.username == User.DEFAULT_USER
1365
1365
1366 if anonymous:
1366 if anonymous:
1367 came_from = request.path_qs
1367 came_from = request.path_qs
1368
1368
1369 import rhodecode.lib.helpers as h
1369 import rhodecode.lib.helpers as h
1370 h.flash(_('You need to be signed in to view this page'),
1370 h.flash(_('You need to be signed in to view this page'),
1371 category='warning')
1371 category='warning')
1372 return redirect(
1372 return redirect(
1373 h.route_path('login', _query={'came_from': came_from}))
1373 h.route_path('login', _query={'came_from': came_from}))
1374
1374
1375 else:
1375 else:
1376 # redirect with forbidden ret code
1376 # redirect with forbidden ret code
1377 return abort(403)
1377 return abort(403)
1378
1378
1379 def check_permissions(self, user):
1379 def check_permissions(self, user):
1380 """Dummy function for overriding"""
1380 """Dummy function for overriding"""
1381 raise NotImplementedError(
1381 raise NotImplementedError(
1382 'You have to write this function in child class')
1382 'You have to write this function in child class')
1383
1383
1384
1384
1385 class HasPermissionAllDecorator(PermsDecorator):
1385 class HasPermissionAllDecorator(PermsDecorator):
1386 """
1386 """
1387 Checks for access permission for all given predicates. All of them
1387 Checks for access permission for all given predicates. All of them
1388 have to be meet in order to fulfill the request
1388 have to be meet in order to fulfill the request
1389 """
1389 """
1390
1390
1391 def check_permissions(self, user):
1391 def check_permissions(self, user):
1392 perms = user.permissions_with_scope({})
1392 perms = user.permissions_with_scope({})
1393 if self.required_perms.issubset(perms['global']):
1393 if self.required_perms.issubset(perms['global']):
1394 return True
1394 return True
1395 return False
1395 return False
1396
1396
1397
1397
1398 class HasPermissionAnyDecorator(PermsDecorator):
1398 class HasPermissionAnyDecorator(PermsDecorator):
1399 """
1399 """
1400 Checks for access permission for any of given predicates. In order to
1400 Checks for access permission for any of given predicates. In order to
1401 fulfill the request any of predicates must be meet
1401 fulfill the request any of predicates must be meet
1402 """
1402 """
1403
1403
1404 def check_permissions(self, user):
1404 def check_permissions(self, user):
1405 perms = user.permissions_with_scope({})
1405 perms = user.permissions_with_scope({})
1406 if self.required_perms.intersection(perms['global']):
1406 if self.required_perms.intersection(perms['global']):
1407 return True
1407 return True
1408 return False
1408 return False
1409
1409
1410
1410
1411 class HasRepoPermissionAllDecorator(PermsDecorator):
1411 class HasRepoPermissionAllDecorator(PermsDecorator):
1412 """
1412 """
1413 Checks for access permission for all given predicates for specific
1413 Checks for access permission for all given predicates for specific
1414 repository. All of them have to be meet in order to fulfill the request
1414 repository. All of them have to be meet in order to fulfill the request
1415 """
1415 """
1416
1416
1417 def check_permissions(self, user):
1417 def check_permissions(self, user):
1418 perms = user.permissions
1418 perms = user.permissions
1419 repo_name = get_repo_slug(request)
1419 repo_name = get_repo_slug(request)
1420 try:
1420 try:
1421 user_perms = set([perms['repositories'][repo_name]])
1421 user_perms = set([perms['repositories'][repo_name]])
1422 except KeyError:
1422 except KeyError:
1423 return False
1423 return False
1424 if self.required_perms.issubset(user_perms):
1424 if self.required_perms.issubset(user_perms):
1425 return True
1425 return True
1426 return False
1426 return False
1427
1427
1428
1428
1429 class HasRepoPermissionAnyDecorator(PermsDecorator):
1429 class HasRepoPermissionAnyDecorator(PermsDecorator):
1430 """
1430 """
1431 Checks for access permission for any of given predicates for specific
1431 Checks for access permission for any of given predicates for specific
1432 repository. In order to fulfill the request any of predicates must be meet
1432 repository. In order to fulfill the request any of predicates must be meet
1433 """
1433 """
1434
1434
1435 def check_permissions(self, user):
1435 def check_permissions(self, user):
1436 perms = user.permissions
1436 perms = user.permissions
1437 repo_name = get_repo_slug(request)
1437 repo_name = get_repo_slug(request)
1438 try:
1438 try:
1439 user_perms = set([perms['repositories'][repo_name]])
1439 user_perms = set([perms['repositories'][repo_name]])
1440 except KeyError:
1440 except KeyError:
1441 return False
1441 return False
1442
1442
1443 if self.required_perms.intersection(user_perms):
1443 if self.required_perms.intersection(user_perms):
1444 return True
1444 return True
1445 return False
1445 return False
1446
1446
1447
1447
1448 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1448 class HasRepoGroupPermissionAllDecorator(PermsDecorator):
1449 """
1449 """
1450 Checks for access permission for all given predicates for specific
1450 Checks for access permission for all given predicates for specific
1451 repository group. All of them have to be meet in order to
1451 repository group. All of them have to be meet in order to
1452 fulfill the request
1452 fulfill the request
1453 """
1453 """
1454
1454
1455 def check_permissions(self, user):
1455 def check_permissions(self, user):
1456 perms = user.permissions
1456 perms = user.permissions
1457 group_name = get_repo_group_slug(request)
1457 group_name = get_repo_group_slug(request)
1458 try:
1458 try:
1459 user_perms = set([perms['repositories_groups'][group_name]])
1459 user_perms = set([perms['repositories_groups'][group_name]])
1460 except KeyError:
1460 except KeyError:
1461 return False
1461 return False
1462
1462
1463 if self.required_perms.issubset(user_perms):
1463 if self.required_perms.issubset(user_perms):
1464 return True
1464 return True
1465 return False
1465 return False
1466
1466
1467
1467
1468 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1468 class HasRepoGroupPermissionAnyDecorator(PermsDecorator):
1469 """
1469 """
1470 Checks for access permission for any of given predicates for specific
1470 Checks for access permission for any of given predicates for specific
1471 repository group. In order to fulfill the request any
1471 repository group. In order to fulfill the request any
1472 of predicates must be met
1472 of predicates must be met
1473 """
1473 """
1474
1474
1475 def check_permissions(self, user):
1475 def check_permissions(self, user):
1476 perms = user.permissions
1476 perms = user.permissions
1477 group_name = get_repo_group_slug(request)
1477 group_name = get_repo_group_slug(request)
1478 try:
1478 try:
1479 user_perms = set([perms['repositories_groups'][group_name]])
1479 user_perms = set([perms['repositories_groups'][group_name]])
1480 except KeyError:
1480 except KeyError:
1481 return False
1481 return False
1482
1482
1483 if self.required_perms.intersection(user_perms):
1483 if self.required_perms.intersection(user_perms):
1484 return True
1484 return True
1485 return False
1485 return False
1486
1486
1487
1487
1488 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1488 class HasUserGroupPermissionAllDecorator(PermsDecorator):
1489 """
1489 """
1490 Checks for access permission for all given predicates for specific
1490 Checks for access permission for all given predicates for specific
1491 user group. All of them have to be meet in order to fulfill the request
1491 user group. All of them have to be meet in order to fulfill the request
1492 """
1492 """
1493
1493
1494 def check_permissions(self, user):
1494 def check_permissions(self, user):
1495 perms = user.permissions
1495 perms = user.permissions
1496 group_name = get_user_group_slug(request)
1496 group_name = get_user_group_slug(request)
1497 try:
1497 try:
1498 user_perms = set([perms['user_groups'][group_name]])
1498 user_perms = set([perms['user_groups'][group_name]])
1499 except KeyError:
1499 except KeyError:
1500 return False
1500 return False
1501
1501
1502 if self.required_perms.issubset(user_perms):
1502 if self.required_perms.issubset(user_perms):
1503 return True
1503 return True
1504 return False
1504 return False
1505
1505
1506
1506
1507 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1507 class HasUserGroupPermissionAnyDecorator(PermsDecorator):
1508 """
1508 """
1509 Checks for access permission for any of given predicates for specific
1509 Checks for access permission for any of given predicates for specific
1510 user group. In order to fulfill the request any of predicates must be meet
1510 user group. In order to fulfill the request any of predicates must be meet
1511 """
1511 """
1512
1512
1513 def check_permissions(self, user):
1513 def check_permissions(self, user):
1514 perms = user.permissions
1514 perms = user.permissions
1515 group_name = get_user_group_slug(request)
1515 group_name = get_user_group_slug(request)
1516 try:
1516 try:
1517 user_perms = set([perms['user_groups'][group_name]])
1517 user_perms = set([perms['user_groups'][group_name]])
1518 except KeyError:
1518 except KeyError:
1519 return False
1519 return False
1520
1520
1521 if self.required_perms.intersection(user_perms):
1521 if self.required_perms.intersection(user_perms):
1522 return True
1522 return True
1523 return False
1523 return False
1524
1524
1525
1525
1526 # CHECK FUNCTIONS
1526 # CHECK FUNCTIONS
1527 class PermsFunction(object):
1527 class PermsFunction(object):
1528 """Base function for other check functions"""
1528 """Base function for other check functions"""
1529
1529
1530 def __init__(self, *perms):
1530 def __init__(self, *perms):
1531 self.required_perms = set(perms)
1531 self.required_perms = set(perms)
1532 self.repo_name = None
1532 self.repo_name = None
1533 self.repo_group_name = None
1533 self.repo_group_name = None
1534 self.user_group_name = None
1534 self.user_group_name = None
1535
1535
1536 def __bool__(self):
1536 def __bool__(self):
1537 frame = inspect.currentframe()
1537 frame = inspect.currentframe()
1538 stack_trace = traceback.format_stack(frame)
1538 stack_trace = traceback.format_stack(frame)
1539 log.error('Checking bool value on a class instance of perm '
1539 log.error('Checking bool value on a class instance of perm '
1540 'function is not allowed: %s' % ''.join(stack_trace))
1540 'function is not allowed: %s' % ''.join(stack_trace))
1541 # rather than throwing errors, here we always return False so if by
1541 # rather than throwing errors, here we always return False so if by
1542 # accident someone checks truth for just an instance it will always end
1542 # accident someone checks truth for just an instance it will always end
1543 # up in returning False
1543 # up in returning False
1544 return False
1544 return False
1545 __nonzero__ = __bool__
1545 __nonzero__ = __bool__
1546
1546
1547 def __call__(self, check_location='', user=None):
1547 def __call__(self, check_location='', user=None):
1548 if not user:
1548 if not user:
1549 log.debug('Using user attribute from global request')
1549 log.debug('Using user attribute from global request')
1550 # TODO: remove this someday,put as user as attribute here
1550 # TODO: remove this someday,put as user as attribute here
1551 user = request.user
1551 user = request.user
1552
1552
1553 # init auth user if not already given
1553 # init auth user if not already given
1554 if not isinstance(user, AuthUser):
1554 if not isinstance(user, AuthUser):
1555 log.debug('Wrapping user %s into AuthUser', user)
1555 log.debug('Wrapping user %s into AuthUser', user)
1556 user = AuthUser(user.user_id)
1556 user = AuthUser(user.user_id)
1557
1557
1558 cls_name = self.__class__.__name__
1558 cls_name = self.__class__.__name__
1559 check_scope = self._get_check_scope(cls_name)
1559 check_scope = self._get_check_scope(cls_name)
1560 check_location = check_location or 'unspecified location'
1560 check_location = check_location or 'unspecified location'
1561
1561
1562 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1562 log.debug('checking cls:%s %s usr:%s %s @ %s', cls_name,
1563 self.required_perms, user, check_scope, check_location)
1563 self.required_perms, user, check_scope, check_location)
1564 if not user:
1564 if not user:
1565 log.warning('Empty user given for permission check')
1565 log.warning('Empty user given for permission check')
1566 return False
1566 return False
1567
1567
1568 if self.check_permissions(user):
1568 if self.check_permissions(user):
1569 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1569 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1570 check_scope, user, check_location)
1570 check_scope, user, check_location)
1571 return True
1571 return True
1572
1572
1573 else:
1573 else:
1574 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1574 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1575 check_scope, user, check_location)
1575 check_scope, user, check_location)
1576 return False
1576 return False
1577
1577
1578 def _get_check_scope(self, cls_name):
1578 def _get_check_scope(self, cls_name):
1579 return {
1579 return {
1580 'HasPermissionAll': 'GLOBAL',
1580 'HasPermissionAll': 'GLOBAL',
1581 'HasPermissionAny': 'GLOBAL',
1581 'HasPermissionAny': 'GLOBAL',
1582 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1582 'HasRepoPermissionAll': 'repo:%s' % self.repo_name,
1583 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1583 'HasRepoPermissionAny': 'repo:%s' % self.repo_name,
1584 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1584 'HasRepoGroupPermissionAll': 'repo_group:%s' % self.repo_group_name,
1585 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1585 'HasRepoGroupPermissionAny': 'repo_group:%s' % self.repo_group_name,
1586 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1586 'HasUserGroupPermissionAll': 'user_group:%s' % self.user_group_name,
1587 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1587 'HasUserGroupPermissionAny': 'user_group:%s' % self.user_group_name,
1588 }.get(cls_name, '?:%s' % cls_name)
1588 }.get(cls_name, '?:%s' % cls_name)
1589
1589
1590 def check_permissions(self, user):
1590 def check_permissions(self, user):
1591 """Dummy function for overriding"""
1591 """Dummy function for overriding"""
1592 raise Exception('You have to write this function in child class')
1592 raise Exception('You have to write this function in child class')
1593
1593
1594
1594
1595 class HasPermissionAll(PermsFunction):
1595 class HasPermissionAll(PermsFunction):
1596 def check_permissions(self, user):
1596 def check_permissions(self, user):
1597 perms = user.permissions_with_scope({})
1597 perms = user.permissions_with_scope({})
1598 if self.required_perms.issubset(perms.get('global')):
1598 if self.required_perms.issubset(perms.get('global')):
1599 return True
1599 return True
1600 return False
1600 return False
1601
1601
1602
1602
1603 class HasPermissionAny(PermsFunction):
1603 class HasPermissionAny(PermsFunction):
1604 def check_permissions(self, user):
1604 def check_permissions(self, user):
1605 perms = user.permissions_with_scope({})
1605 perms = user.permissions_with_scope({})
1606 if self.required_perms.intersection(perms.get('global')):
1606 if self.required_perms.intersection(perms.get('global')):
1607 return True
1607 return True
1608 return False
1608 return False
1609
1609
1610
1610
1611 class HasRepoPermissionAll(PermsFunction):
1611 class HasRepoPermissionAll(PermsFunction):
1612 def __call__(self, repo_name=None, check_location='', user=None):
1612 def __call__(self, repo_name=None, check_location='', user=None):
1613 self.repo_name = repo_name
1613 self.repo_name = repo_name
1614 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1614 return super(HasRepoPermissionAll, self).__call__(check_location, user)
1615
1615
1616 def check_permissions(self, user):
1616 def check_permissions(self, user):
1617 if not self.repo_name:
1617 if not self.repo_name:
1618 self.repo_name = get_repo_slug(request)
1618 self.repo_name = get_repo_slug(request)
1619
1619
1620 perms = user.permissions
1620 perms = user.permissions
1621 try:
1621 try:
1622 user_perms = set([perms['repositories'][self.repo_name]])
1622 user_perms = set([perms['repositories'][self.repo_name]])
1623 except KeyError:
1623 except KeyError:
1624 return False
1624 return False
1625 if self.required_perms.issubset(user_perms):
1625 if self.required_perms.issubset(user_perms):
1626 return True
1626 return True
1627 return False
1627 return False
1628
1628
1629
1629
1630 class HasRepoPermissionAny(PermsFunction):
1630 class HasRepoPermissionAny(PermsFunction):
1631 def __call__(self, repo_name=None, check_location='', user=None):
1631 def __call__(self, repo_name=None, check_location='', user=None):
1632 self.repo_name = repo_name
1632 self.repo_name = repo_name
1633 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1633 return super(HasRepoPermissionAny, self).__call__(check_location, user)
1634
1634
1635 def check_permissions(self, user):
1635 def check_permissions(self, user):
1636 if not self.repo_name:
1636 if not self.repo_name:
1637 self.repo_name = get_repo_slug(request)
1637 self.repo_name = get_repo_slug(request)
1638
1638
1639 perms = user.permissions
1639 perms = user.permissions
1640 try:
1640 try:
1641 user_perms = set([perms['repositories'][self.repo_name]])
1641 user_perms = set([perms['repositories'][self.repo_name]])
1642 except KeyError:
1642 except KeyError:
1643 return False
1643 return False
1644 if self.required_perms.intersection(user_perms):
1644 if self.required_perms.intersection(user_perms):
1645 return True
1645 return True
1646 return False
1646 return False
1647
1647
1648
1648
1649 class HasRepoGroupPermissionAny(PermsFunction):
1649 class HasRepoGroupPermissionAny(PermsFunction):
1650 def __call__(self, group_name=None, check_location='', user=None):
1650 def __call__(self, group_name=None, check_location='', user=None):
1651 self.repo_group_name = group_name
1651 self.repo_group_name = group_name
1652 return super(HasRepoGroupPermissionAny, self).__call__(
1652 return super(HasRepoGroupPermissionAny, self).__call__(
1653 check_location, user)
1653 check_location, user)
1654
1654
1655 def check_permissions(self, user):
1655 def check_permissions(self, user):
1656 perms = user.permissions
1656 perms = user.permissions
1657 try:
1657 try:
1658 user_perms = set(
1658 user_perms = set(
1659 [perms['repositories_groups'][self.repo_group_name]])
1659 [perms['repositories_groups'][self.repo_group_name]])
1660 except KeyError:
1660 except KeyError:
1661 return False
1661 return False
1662 if self.required_perms.intersection(user_perms):
1662 if self.required_perms.intersection(user_perms):
1663 return True
1663 return True
1664 return False
1664 return False
1665
1665
1666
1666
1667 class HasRepoGroupPermissionAll(PermsFunction):
1667 class HasRepoGroupPermissionAll(PermsFunction):
1668 def __call__(self, group_name=None, check_location='', user=None):
1668 def __call__(self, group_name=None, check_location='', user=None):
1669 self.repo_group_name = group_name
1669 self.repo_group_name = group_name
1670 return super(HasRepoGroupPermissionAll, self).__call__(
1670 return super(HasRepoGroupPermissionAll, self).__call__(
1671 check_location, user)
1671 check_location, user)
1672
1672
1673 def check_permissions(self, user):
1673 def check_permissions(self, user):
1674 perms = user.permissions
1674 perms = user.permissions
1675 try:
1675 try:
1676 user_perms = set(
1676 user_perms = set(
1677 [perms['repositories_groups'][self.repo_group_name]])
1677 [perms['repositories_groups'][self.repo_group_name]])
1678 except KeyError:
1678 except KeyError:
1679 return False
1679 return False
1680 if self.required_perms.issubset(user_perms):
1680 if self.required_perms.issubset(user_perms):
1681 return True
1681 return True
1682 return False
1682 return False
1683
1683
1684
1684
1685 class HasUserGroupPermissionAny(PermsFunction):
1685 class HasUserGroupPermissionAny(PermsFunction):
1686 def __call__(self, user_group_name=None, check_location='', user=None):
1686 def __call__(self, user_group_name=None, check_location='', user=None):
1687 self.user_group_name = user_group_name
1687 self.user_group_name = user_group_name
1688 return super(HasUserGroupPermissionAny, self).__call__(
1688 return super(HasUserGroupPermissionAny, self).__call__(
1689 check_location, user)
1689 check_location, user)
1690
1690
1691 def check_permissions(self, user):
1691 def check_permissions(self, user):
1692 perms = user.permissions
1692 perms = user.permissions
1693 try:
1693 try:
1694 user_perms = set([perms['user_groups'][self.user_group_name]])
1694 user_perms = set([perms['user_groups'][self.user_group_name]])
1695 except KeyError:
1695 except KeyError:
1696 return False
1696 return False
1697 if self.required_perms.intersection(user_perms):
1697 if self.required_perms.intersection(user_perms):
1698 return True
1698 return True
1699 return False
1699 return False
1700
1700
1701
1701
1702 class HasUserGroupPermissionAll(PermsFunction):
1702 class HasUserGroupPermissionAll(PermsFunction):
1703 def __call__(self, user_group_name=None, check_location='', user=None):
1703 def __call__(self, user_group_name=None, check_location='', user=None):
1704 self.user_group_name = user_group_name
1704 self.user_group_name = user_group_name
1705 return super(HasUserGroupPermissionAll, self).__call__(
1705 return super(HasUserGroupPermissionAll, self).__call__(
1706 check_location, user)
1706 check_location, user)
1707
1707
1708 def check_permissions(self, user):
1708 def check_permissions(self, user):
1709 perms = user.permissions
1709 perms = user.permissions
1710 try:
1710 try:
1711 user_perms = set([perms['user_groups'][self.user_group_name]])
1711 user_perms = set([perms['user_groups'][self.user_group_name]])
1712 except KeyError:
1712 except KeyError:
1713 return False
1713 return False
1714 if self.required_perms.issubset(user_perms):
1714 if self.required_perms.issubset(user_perms):
1715 return True
1715 return True
1716 return False
1716 return False
1717
1717
1718
1718
1719 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1719 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
1720 class HasPermissionAnyMiddleware(object):
1720 class HasPermissionAnyMiddleware(object):
1721 def __init__(self, *perms):
1721 def __init__(self, *perms):
1722 self.required_perms = set(perms)
1722 self.required_perms = set(perms)
1723
1723
1724 def __call__(self, user, repo_name):
1724 def __call__(self, user, repo_name):
1725 # repo_name MUST be unicode, since we handle keys in permission
1725 # repo_name MUST be unicode, since we handle keys in permission
1726 # dict by unicode
1726 # dict by unicode
1727 repo_name = safe_unicode(repo_name)
1727 repo_name = safe_unicode(repo_name)
1728 user = AuthUser(user.user_id)
1728 user = AuthUser(user.user_id)
1729 log.debug(
1729 log.debug(
1730 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1730 'Checking VCS protocol permissions %s for user:%s repo:`%s`',
1731 self.required_perms, user, repo_name)
1731 self.required_perms, user, repo_name)
1732
1732
1733 if self.check_permissions(user, repo_name):
1733 if self.check_permissions(user, repo_name):
1734 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1734 log.debug('Permission to repo:`%s` GRANTED for user:%s @ %s',
1735 repo_name, user, 'PermissionMiddleware')
1735 repo_name, user, 'PermissionMiddleware')
1736 return True
1736 return True
1737
1737
1738 else:
1738 else:
1739 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1739 log.debug('Permission to repo:`%s` DENIED for user:%s @ %s',
1740 repo_name, user, 'PermissionMiddleware')
1740 repo_name, user, 'PermissionMiddleware')
1741 return False
1741 return False
1742
1742
1743 def check_permissions(self, user, repo_name):
1743 def check_permissions(self, user, repo_name):
1744 perms = user.permissions_with_scope({'repo_name': repo_name})
1744 perms = user.permissions_with_scope({'repo_name': repo_name})
1745
1745
1746 try:
1746 try:
1747 user_perms = set([perms['repositories'][repo_name]])
1747 user_perms = set([perms['repositories'][repo_name]])
1748 except Exception:
1748 except Exception:
1749 log.exception('Error while accessing user permissions')
1749 log.exception('Error while accessing user permissions')
1750 return False
1750 return False
1751
1751
1752 if self.required_perms.intersection(user_perms):
1752 if self.required_perms.intersection(user_perms):
1753 return True
1753 return True
1754 return False
1754 return False
1755
1755
1756
1756
1757 # SPECIAL VERSION TO HANDLE API AUTH
1757 # SPECIAL VERSION TO HANDLE API AUTH
1758 class _BaseApiPerm(object):
1758 class _BaseApiPerm(object):
1759 def __init__(self, *perms):
1759 def __init__(self, *perms):
1760 self.required_perms = set(perms)
1760 self.required_perms = set(perms)
1761
1761
1762 def __call__(self, check_location=None, user=None, repo_name=None,
1762 def __call__(self, check_location=None, user=None, repo_name=None,
1763 group_name=None, user_group_name=None):
1763 group_name=None, user_group_name=None):
1764 cls_name = self.__class__.__name__
1764 cls_name = self.__class__.__name__
1765 check_scope = 'global:%s' % (self.required_perms,)
1765 check_scope = 'global:%s' % (self.required_perms,)
1766 if repo_name:
1766 if repo_name:
1767 check_scope += ', repo_name:%s' % (repo_name,)
1767 check_scope += ', repo_name:%s' % (repo_name,)
1768
1768
1769 if group_name:
1769 if group_name:
1770 check_scope += ', repo_group_name:%s' % (group_name,)
1770 check_scope += ', repo_group_name:%s' % (group_name,)
1771
1771
1772 if user_group_name:
1772 if user_group_name:
1773 check_scope += ', user_group_name:%s' % (user_group_name,)
1773 check_scope += ', user_group_name:%s' % (user_group_name,)
1774
1774
1775 log.debug(
1775 log.debug(
1776 'checking cls:%s %s %s @ %s'
1776 'checking cls:%s %s %s @ %s'
1777 % (cls_name, self.required_perms, check_scope, check_location))
1777 % (cls_name, self.required_perms, check_scope, check_location))
1778 if not user:
1778 if not user:
1779 log.debug('Empty User passed into arguments')
1779 log.debug('Empty User passed into arguments')
1780 return False
1780 return False
1781
1781
1782 # process user
1782 # process user
1783 if not isinstance(user, AuthUser):
1783 if not isinstance(user, AuthUser):
1784 user = AuthUser(user.user_id)
1784 user = AuthUser(user.user_id)
1785 if not check_location:
1785 if not check_location:
1786 check_location = 'unspecified'
1786 check_location = 'unspecified'
1787 if self.check_permissions(user.permissions, repo_name, group_name,
1787 if self.check_permissions(user.permissions, repo_name, group_name,
1788 user_group_name):
1788 user_group_name):
1789 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1789 log.debug('Permission to repo:`%s` GRANTED for user:`%s` @ %s',
1790 check_scope, user, check_location)
1790 check_scope, user, check_location)
1791 return True
1791 return True
1792
1792
1793 else:
1793 else:
1794 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1794 log.debug('Permission to repo:`%s` DENIED for user:`%s` @ %s',
1795 check_scope, user, check_location)
1795 check_scope, user, check_location)
1796 return False
1796 return False
1797
1797
1798 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1798 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1799 user_group_name=None):
1799 user_group_name=None):
1800 """
1800 """
1801 implement in child class should return True if permissions are ok,
1801 implement in child class should return True if permissions are ok,
1802 False otherwise
1802 False otherwise
1803
1803
1804 :param perm_defs: dict with permission definitions
1804 :param perm_defs: dict with permission definitions
1805 :param repo_name: repo name
1805 :param repo_name: repo name
1806 """
1806 """
1807 raise NotImplementedError()
1807 raise NotImplementedError()
1808
1808
1809
1809
1810 class HasPermissionAllApi(_BaseApiPerm):
1810 class HasPermissionAllApi(_BaseApiPerm):
1811 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1811 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1812 user_group_name=None):
1812 user_group_name=None):
1813 if self.required_perms.issubset(perm_defs.get('global')):
1813 if self.required_perms.issubset(perm_defs.get('global')):
1814 return True
1814 return True
1815 return False
1815 return False
1816
1816
1817
1817
1818 class HasPermissionAnyApi(_BaseApiPerm):
1818 class HasPermissionAnyApi(_BaseApiPerm):
1819 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1819 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1820 user_group_name=None):
1820 user_group_name=None):
1821 if self.required_perms.intersection(perm_defs.get('global')):
1821 if self.required_perms.intersection(perm_defs.get('global')):
1822 return True
1822 return True
1823 return False
1823 return False
1824
1824
1825
1825
1826 class HasRepoPermissionAllApi(_BaseApiPerm):
1826 class HasRepoPermissionAllApi(_BaseApiPerm):
1827 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1827 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1828 user_group_name=None):
1828 user_group_name=None):
1829 try:
1829 try:
1830 _user_perms = set([perm_defs['repositories'][repo_name]])
1830 _user_perms = set([perm_defs['repositories'][repo_name]])
1831 except KeyError:
1831 except KeyError:
1832 log.warning(traceback.format_exc())
1832 log.warning(traceback.format_exc())
1833 return False
1833 return False
1834 if self.required_perms.issubset(_user_perms):
1834 if self.required_perms.issubset(_user_perms):
1835 return True
1835 return True
1836 return False
1836 return False
1837
1837
1838
1838
1839 class HasRepoPermissionAnyApi(_BaseApiPerm):
1839 class HasRepoPermissionAnyApi(_BaseApiPerm):
1840 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1840 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1841 user_group_name=None):
1841 user_group_name=None):
1842 try:
1842 try:
1843 _user_perms = set([perm_defs['repositories'][repo_name]])
1843 _user_perms = set([perm_defs['repositories'][repo_name]])
1844 except KeyError:
1844 except KeyError:
1845 log.warning(traceback.format_exc())
1845 log.warning(traceback.format_exc())
1846 return False
1846 return False
1847 if self.required_perms.intersection(_user_perms):
1847 if self.required_perms.intersection(_user_perms):
1848 return True
1848 return True
1849 return False
1849 return False
1850
1850
1851
1851
1852 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1852 class HasRepoGroupPermissionAnyApi(_BaseApiPerm):
1853 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1853 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1854 user_group_name=None):
1854 user_group_name=None):
1855 try:
1855 try:
1856 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1856 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1857 except KeyError:
1857 except KeyError:
1858 log.warning(traceback.format_exc())
1858 log.warning(traceback.format_exc())
1859 return False
1859 return False
1860 if self.required_perms.intersection(_user_perms):
1860 if self.required_perms.intersection(_user_perms):
1861 return True
1861 return True
1862 return False
1862 return False
1863
1863
1864
1864
1865 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1865 class HasRepoGroupPermissionAllApi(_BaseApiPerm):
1866 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1866 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1867 user_group_name=None):
1867 user_group_name=None):
1868 try:
1868 try:
1869 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1869 _user_perms = set([perm_defs['repositories_groups'][group_name]])
1870 except KeyError:
1870 except KeyError:
1871 log.warning(traceback.format_exc())
1871 log.warning(traceback.format_exc())
1872 return False
1872 return False
1873 if self.required_perms.issubset(_user_perms):
1873 if self.required_perms.issubset(_user_perms):
1874 return True
1874 return True
1875 return False
1875 return False
1876
1876
1877
1877
1878 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1878 class HasUserGroupPermissionAnyApi(_BaseApiPerm):
1879 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1879 def check_permissions(self, perm_defs, repo_name=None, group_name=None,
1880 user_group_name=None):
1880 user_group_name=None):
1881 try:
1881 try:
1882 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1882 _user_perms = set([perm_defs['user_groups'][user_group_name]])
1883 except KeyError:
1883 except KeyError:
1884 log.warning(traceback.format_exc())
1884 log.warning(traceback.format_exc())
1885 return False
1885 return False
1886 if self.required_perms.intersection(_user_perms):
1886 if self.required_perms.intersection(_user_perms):
1887 return True
1887 return True
1888 return False
1888 return False
1889
1889
1890
1890
1891 def check_ip_access(source_ip, allowed_ips=None):
1891 def check_ip_access(source_ip, allowed_ips=None):
1892 """
1892 """
1893 Checks if source_ip is a subnet of any of allowed_ips.
1893 Checks if source_ip is a subnet of any of allowed_ips.
1894
1894
1895 :param source_ip:
1895 :param source_ip:
1896 :param allowed_ips: list of allowed ips together with mask
1896 :param allowed_ips: list of allowed ips together with mask
1897 """
1897 """
1898 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1898 log.debug('checking if ip:%s is subnet of %s' % (source_ip, allowed_ips))
1899 source_ip_address = ipaddress.ip_address(source_ip)
1899 source_ip_address = ipaddress.ip_address(source_ip)
1900 if isinstance(allowed_ips, (tuple, list, set)):
1900 if isinstance(allowed_ips, (tuple, list, set)):
1901 for ip in allowed_ips:
1901 for ip in allowed_ips:
1902 try:
1902 try:
1903 network_address = ipaddress.ip_network(ip, strict=False)
1903 network_address = ipaddress.ip_network(ip, strict=False)
1904 if source_ip_address in network_address:
1904 if source_ip_address in network_address:
1905 log.debug('IP %s is network %s' %
1905 log.debug('IP %s is network %s' %
1906 (source_ip_address, network_address))
1906 (source_ip_address, network_address))
1907 return True
1907 return True
1908 # for any case we cannot determine the IP, don't crash just
1908 # for any case we cannot determine the IP, don't crash just
1909 # skip it and log as error, we want to say forbidden still when
1909 # skip it and log as error, we want to say forbidden still when
1910 # sending bad IP
1910 # sending bad IP
1911 except Exception:
1911 except Exception:
1912 log.error(traceback.format_exc())
1912 log.error(traceback.format_exc())
1913 continue
1913 continue
1914 return False
1914 return False
1915
1915
1916
1916
1917 def get_cython_compat_decorator(wrapper, func):
1917 def get_cython_compat_decorator(wrapper, func):
1918 """
1918 """
1919 Creates a cython compatible decorator. The previously used
1919 Creates a cython compatible decorator. The previously used
1920 decorator.decorator() function seems to be incompatible with cython.
1920 decorator.decorator() function seems to be incompatible with cython.
1921
1921
1922 :param wrapper: __wrapper method of the decorator class
1922 :param wrapper: __wrapper method of the decorator class
1923 :param func: decorated function
1923 :param func: decorated function
1924 """
1924 """
1925 @wraps(func)
1925 @wraps(func)
1926 def local_wrapper(*args, **kwds):
1926 def local_wrapper(*args, **kwds):
1927 return wrapper(func, *args, **kwds)
1927 return wrapper(func, *args, **kwds)
1928 local_wrapper.__wrapped__ = func
1928 local_wrapper.__wrapped__ = func
1929 return local_wrapper
1929 return local_wrapper
@@ -1,3922 +1,3917 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 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
37
38 from sqlalchemy import *
38 from sqlalchemy import *
39 from sqlalchemy.ext.declarative import declared_attr
39 from sqlalchemy.ext.declarative import declared_attr
40 from sqlalchemy.ext.hybrid import hybrid_property
40 from sqlalchemy.ext.hybrid import hybrid_property
41 from sqlalchemy.orm import (
41 from sqlalchemy.orm import (
42 relationship, joinedload, class_mapper, validates, aliased)
42 relationship, joinedload, class_mapper, validates, aliased)
43 from sqlalchemy.sql.expression import true
43 from sqlalchemy.sql.expression import true
44 from beaker.cache import cache_region
44 from beaker.cache import cache_region
45 from webob.exc import HTTPNotFound
45 from webob.exc import HTTPNotFound
46 from zope.cachedescriptors.property import Lazy as LazyProperty
46 from zope.cachedescriptors.property import Lazy as LazyProperty
47
47
48 from pylons import url
48 from pylons import url
49 from pylons.i18n.translation import lazy_ugettext as _
49 from pylons.i18n.translation import lazy_ugettext as _
50
50
51 from rhodecode.lib.vcs import get_vcs_instance
51 from rhodecode.lib.vcs import get_vcs_instance
52 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
52 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
53 from rhodecode.lib.utils2 import (
53 from rhodecode.lib.utils2 import (
54 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
54 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
55 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
55 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
56 glob2re, StrictAttributeDict, cleaned_uri)
56 glob2re, StrictAttributeDict, cleaned_uri)
57 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
57 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
58 from rhodecode.lib.ext_json import json
58 from rhodecode.lib.ext_json import json
59 from rhodecode.lib.caching_query import FromCache
59 from rhodecode.lib.caching_query import FromCache
60 from rhodecode.lib.encrypt import AESCipher
60 from rhodecode.lib.encrypt import AESCipher
61
61
62 from rhodecode.model.meta import Base, Session
62 from rhodecode.model.meta import Base, Session
63
63
64 URL_SEP = '/'
64 URL_SEP = '/'
65 log = logging.getLogger(__name__)
65 log = logging.getLogger(__name__)
66
66
67 # =============================================================================
67 # =============================================================================
68 # BASE CLASSES
68 # BASE CLASSES
69 # =============================================================================
69 # =============================================================================
70
70
71 # this is propagated from .ini file rhodecode.encrypted_values.secret or
71 # this is propagated from .ini file rhodecode.encrypted_values.secret or
72 # beaker.session.secret if first is not set.
72 # beaker.session.secret if first is not set.
73 # and initialized at environment.py
73 # and initialized at environment.py
74 ENCRYPTION_KEY = None
74 ENCRYPTION_KEY = None
75
75
76 # used to sort permissions by types, '#' used here is not allowed to be in
76 # used to sort permissions by types, '#' used here is not allowed to be in
77 # usernames, and it's very early in sorted string.printable table.
77 # usernames, and it's very early in sorted string.printable table.
78 PERMISSION_TYPE_SORT = {
78 PERMISSION_TYPE_SORT = {
79 'admin': '####',
79 'admin': '####',
80 'write': '###',
80 'write': '###',
81 'read': '##',
81 'read': '##',
82 'none': '#',
82 'none': '#',
83 }
83 }
84
84
85
85
86 def display_sort(obj):
86 def display_sort(obj):
87 """
87 """
88 Sort function used to sort permissions in .permissions() function of
88 Sort function used to sort permissions in .permissions() function of
89 Repository, RepoGroup, UserGroup. Also it put the default user in front
89 Repository, RepoGroup, UserGroup. Also it put the default user in front
90 of all other resources
90 of all other resources
91 """
91 """
92
92
93 if obj.username == User.DEFAULT_USER:
93 if obj.username == User.DEFAULT_USER:
94 return '#####'
94 return '#####'
95 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
95 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
96 return prefix + obj.username
96 return prefix + obj.username
97
97
98
98
99 def _hash_key(k):
99 def _hash_key(k):
100 return md5_safe(k)
100 return md5_safe(k)
101
101
102
102
103 class EncryptedTextValue(TypeDecorator):
103 class EncryptedTextValue(TypeDecorator):
104 """
104 """
105 Special column for encrypted long text data, use like::
105 Special column for encrypted long text data, use like::
106
106
107 value = Column("encrypted_value", EncryptedValue(), nullable=False)
107 value = Column("encrypted_value", EncryptedValue(), nullable=False)
108
108
109 This column is intelligent so if value is in unencrypted form it return
109 This column is intelligent so if value is in unencrypted form it return
110 unencrypted form, but on save it always encrypts
110 unencrypted form, but on save it always encrypts
111 """
111 """
112 impl = Text
112 impl = Text
113
113
114 def process_bind_param(self, value, dialect):
114 def process_bind_param(self, value, dialect):
115 if not value:
115 if not value:
116 return value
116 return value
117 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
117 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
118 # protect against double encrypting if someone manually starts
118 # protect against double encrypting if someone manually starts
119 # doing
119 # doing
120 raise ValueError('value needs to be in unencrypted format, ie. '
120 raise ValueError('value needs to be in unencrypted format, ie. '
121 'not starting with enc$aes')
121 'not starting with enc$aes')
122 return 'enc$aes_hmac$%s' % AESCipher(
122 return 'enc$aes_hmac$%s' % AESCipher(
123 ENCRYPTION_KEY, hmac=True).encrypt(value)
123 ENCRYPTION_KEY, hmac=True).encrypt(value)
124
124
125 def process_result_value(self, value, dialect):
125 def process_result_value(self, value, dialect):
126 import rhodecode
126 import rhodecode
127
127
128 if not value:
128 if not value:
129 return value
129 return value
130
130
131 parts = value.split('$', 3)
131 parts = value.split('$', 3)
132 if not len(parts) == 3:
132 if not len(parts) == 3:
133 # probably not encrypted values
133 # probably not encrypted values
134 return value
134 return value
135 else:
135 else:
136 if parts[0] != 'enc':
136 if parts[0] != 'enc':
137 # parts ok but without our header ?
137 # parts ok but without our header ?
138 return value
138 return value
139 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
139 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
140 'rhodecode.encrypted_values.strict') or True)
140 'rhodecode.encrypted_values.strict') or True)
141 # at that stage we know it's our encryption
141 # at that stage we know it's our encryption
142 if parts[1] == 'aes':
142 if parts[1] == 'aes':
143 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
143 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
144 elif parts[1] == 'aes_hmac':
144 elif parts[1] == 'aes_hmac':
145 decrypted_data = AESCipher(
145 decrypted_data = AESCipher(
146 ENCRYPTION_KEY, hmac=True,
146 ENCRYPTION_KEY, hmac=True,
147 strict_verification=enc_strict_mode).decrypt(parts[2])
147 strict_verification=enc_strict_mode).decrypt(parts[2])
148 else:
148 else:
149 raise ValueError(
149 raise ValueError(
150 'Encryption type part is wrong, must be `aes` '
150 'Encryption type part is wrong, must be `aes` '
151 'or `aes_hmac`, got `%s` instead' % (parts[1]))
151 'or `aes_hmac`, got `%s` instead' % (parts[1]))
152 return decrypted_data
152 return decrypted_data
153
153
154
154
155 class BaseModel(object):
155 class BaseModel(object):
156 """
156 """
157 Base Model for all classes
157 Base Model for all classes
158 """
158 """
159
159
160 @classmethod
160 @classmethod
161 def _get_keys(cls):
161 def _get_keys(cls):
162 """return column names for this model """
162 """return column names for this model """
163 return class_mapper(cls).c.keys()
163 return class_mapper(cls).c.keys()
164
164
165 def get_dict(self):
165 def get_dict(self):
166 """
166 """
167 return dict with keys and values corresponding
167 return dict with keys and values corresponding
168 to this model data """
168 to this model data """
169
169
170 d = {}
170 d = {}
171 for k in self._get_keys():
171 for k in self._get_keys():
172 d[k] = getattr(self, k)
172 d[k] = getattr(self, k)
173
173
174 # also use __json__() if present to get additional fields
174 # also use __json__() if present to get additional fields
175 _json_attr = getattr(self, '__json__', None)
175 _json_attr = getattr(self, '__json__', None)
176 if _json_attr:
176 if _json_attr:
177 # update with attributes from __json__
177 # update with attributes from __json__
178 if callable(_json_attr):
178 if callable(_json_attr):
179 _json_attr = _json_attr()
179 _json_attr = _json_attr()
180 for k, val in _json_attr.iteritems():
180 for k, val in _json_attr.iteritems():
181 d[k] = val
181 d[k] = val
182 return d
182 return d
183
183
184 def get_appstruct(self):
184 def get_appstruct(self):
185 """return list with keys and values tuples corresponding
185 """return list with keys and values tuples corresponding
186 to this model data """
186 to this model data """
187
187
188 l = []
188 l = []
189 for k in self._get_keys():
189 for k in self._get_keys():
190 l.append((k, getattr(self, k),))
190 l.append((k, getattr(self, k),))
191 return l
191 return l
192
192
193 def populate_obj(self, populate_dict):
193 def populate_obj(self, populate_dict):
194 """populate model with data from given populate_dict"""
194 """populate model with data from given populate_dict"""
195
195
196 for k in self._get_keys():
196 for k in self._get_keys():
197 if k in populate_dict:
197 if k in populate_dict:
198 setattr(self, k, populate_dict[k])
198 setattr(self, k, populate_dict[k])
199
199
200 @classmethod
200 @classmethod
201 def query(cls):
201 def query(cls):
202 return Session().query(cls)
202 return Session().query(cls)
203
203
204 @classmethod
204 @classmethod
205 def get(cls, id_):
205 def get(cls, id_):
206 if id_:
206 if id_:
207 return cls.query().get(id_)
207 return cls.query().get(id_)
208
208
209 @classmethod
209 @classmethod
210 def get_or_404(cls, id_):
210 def get_or_404(cls, id_):
211 try:
211 try:
212 id_ = int(id_)
212 id_ = int(id_)
213 except (TypeError, ValueError):
213 except (TypeError, ValueError):
214 raise HTTPNotFound
214 raise HTTPNotFound
215
215
216 res = cls.query().get(id_)
216 res = cls.query().get(id_)
217 if not res:
217 if not res:
218 raise HTTPNotFound
218 raise HTTPNotFound
219 return res
219 return res
220
220
221 @classmethod
221 @classmethod
222 def getAll(cls):
222 def getAll(cls):
223 # deprecated and left for backward compatibility
223 # deprecated and left for backward compatibility
224 return cls.get_all()
224 return cls.get_all()
225
225
226 @classmethod
226 @classmethod
227 def get_all(cls):
227 def get_all(cls):
228 return cls.query().all()
228 return cls.query().all()
229
229
230 @classmethod
230 @classmethod
231 def delete(cls, id_):
231 def delete(cls, id_):
232 obj = cls.query().get(id_)
232 obj = cls.query().get(id_)
233 Session().delete(obj)
233 Session().delete(obj)
234
234
235 @classmethod
235 @classmethod
236 def identity_cache(cls, session, attr_name, value):
236 def identity_cache(cls, session, attr_name, value):
237 exist_in_session = []
237 exist_in_session = []
238 for (item_cls, pkey), instance in session.identity_map.items():
238 for (item_cls, pkey), instance in session.identity_map.items():
239 if cls == item_cls and getattr(instance, attr_name) == value:
239 if cls == item_cls and getattr(instance, attr_name) == value:
240 exist_in_session.append(instance)
240 exist_in_session.append(instance)
241 if exist_in_session:
241 if exist_in_session:
242 if len(exist_in_session) == 1:
242 if len(exist_in_session) == 1:
243 return exist_in_session[0]
243 return exist_in_session[0]
244 log.exception(
244 log.exception(
245 'multiple objects with attr %s and '
245 'multiple objects with attr %s and '
246 'value %s found with same name: %r',
246 'value %s found with same name: %r',
247 attr_name, value, exist_in_session)
247 attr_name, value, exist_in_session)
248
248
249 def __repr__(self):
249 def __repr__(self):
250 if hasattr(self, '__unicode__'):
250 if hasattr(self, '__unicode__'):
251 # python repr needs to return str
251 # python repr needs to return str
252 try:
252 try:
253 return safe_str(self.__unicode__())
253 return safe_str(self.__unicode__())
254 except UnicodeDecodeError:
254 except UnicodeDecodeError:
255 pass
255 pass
256 return '<DB:%s>' % (self.__class__.__name__)
256 return '<DB:%s>' % (self.__class__.__name__)
257
257
258
258
259 class RhodeCodeSetting(Base, BaseModel):
259 class RhodeCodeSetting(Base, BaseModel):
260 __tablename__ = 'rhodecode_settings'
260 __tablename__ = 'rhodecode_settings'
261 __table_args__ = (
261 __table_args__ = (
262 UniqueConstraint('app_settings_name'),
262 UniqueConstraint('app_settings_name'),
263 {'extend_existing': True, 'mysql_engine': 'InnoDB',
263 {'extend_existing': True, 'mysql_engine': 'InnoDB',
264 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
264 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
265 )
265 )
266
266
267 SETTINGS_TYPES = {
267 SETTINGS_TYPES = {
268 'str': safe_str,
268 'str': safe_str,
269 'int': safe_int,
269 'int': safe_int,
270 'unicode': safe_unicode,
270 'unicode': safe_unicode,
271 'bool': str2bool,
271 'bool': str2bool,
272 'list': functools.partial(aslist, sep=',')
272 'list': functools.partial(aslist, sep=',')
273 }
273 }
274 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
274 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
275 GLOBAL_CONF_KEY = 'app_settings'
275 GLOBAL_CONF_KEY = 'app_settings'
276
276
277 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
277 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
278 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
278 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
279 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
279 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
280 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
280 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
281
281
282 def __init__(self, key='', val='', type='unicode'):
282 def __init__(self, key='', val='', type='unicode'):
283 self.app_settings_name = key
283 self.app_settings_name = key
284 self.app_settings_type = type
284 self.app_settings_type = type
285 self.app_settings_value = val
285 self.app_settings_value = val
286
286
287 @validates('_app_settings_value')
287 @validates('_app_settings_value')
288 def validate_settings_value(self, key, val):
288 def validate_settings_value(self, key, val):
289 assert type(val) == unicode
289 assert type(val) == unicode
290 return val
290 return val
291
291
292 @hybrid_property
292 @hybrid_property
293 def app_settings_value(self):
293 def app_settings_value(self):
294 v = self._app_settings_value
294 v = self._app_settings_value
295 _type = self.app_settings_type
295 _type = self.app_settings_type
296 if _type:
296 if _type:
297 _type = self.app_settings_type.split('.')[0]
297 _type = self.app_settings_type.split('.')[0]
298 # decode the encrypted value
298 # decode the encrypted value
299 if 'encrypted' in self.app_settings_type:
299 if 'encrypted' in self.app_settings_type:
300 cipher = EncryptedTextValue()
300 cipher = EncryptedTextValue()
301 v = safe_unicode(cipher.process_result_value(v, None))
301 v = safe_unicode(cipher.process_result_value(v, None))
302
302
303 converter = self.SETTINGS_TYPES.get(_type) or \
303 converter = self.SETTINGS_TYPES.get(_type) or \
304 self.SETTINGS_TYPES['unicode']
304 self.SETTINGS_TYPES['unicode']
305 return converter(v)
305 return converter(v)
306
306
307 @app_settings_value.setter
307 @app_settings_value.setter
308 def app_settings_value(self, val):
308 def app_settings_value(self, val):
309 """
309 """
310 Setter that will always make sure we use unicode in app_settings_value
310 Setter that will always make sure we use unicode in app_settings_value
311
311
312 :param val:
312 :param val:
313 """
313 """
314 val = safe_unicode(val)
314 val = safe_unicode(val)
315 # encode the encrypted value
315 # encode the encrypted value
316 if 'encrypted' in self.app_settings_type:
316 if 'encrypted' in self.app_settings_type:
317 cipher = EncryptedTextValue()
317 cipher = EncryptedTextValue()
318 val = safe_unicode(cipher.process_bind_param(val, None))
318 val = safe_unicode(cipher.process_bind_param(val, None))
319 self._app_settings_value = val
319 self._app_settings_value = val
320
320
321 @hybrid_property
321 @hybrid_property
322 def app_settings_type(self):
322 def app_settings_type(self):
323 return self._app_settings_type
323 return self._app_settings_type
324
324
325 @app_settings_type.setter
325 @app_settings_type.setter
326 def app_settings_type(self, val):
326 def app_settings_type(self, val):
327 if val.split('.')[0] not in self.SETTINGS_TYPES:
327 if val.split('.')[0] not in self.SETTINGS_TYPES:
328 raise Exception('type must be one of %s got %s'
328 raise Exception('type must be one of %s got %s'
329 % (self.SETTINGS_TYPES.keys(), val))
329 % (self.SETTINGS_TYPES.keys(), val))
330 self._app_settings_type = val
330 self._app_settings_type = val
331
331
332 def __unicode__(self):
332 def __unicode__(self):
333 return u"<%s('%s:%s[%s]')>" % (
333 return u"<%s('%s:%s[%s]')>" % (
334 self.__class__.__name__,
334 self.__class__.__name__,
335 self.app_settings_name, self.app_settings_value,
335 self.app_settings_name, self.app_settings_value,
336 self.app_settings_type
336 self.app_settings_type
337 )
337 )
338
338
339
339
340 class RhodeCodeUi(Base, BaseModel):
340 class RhodeCodeUi(Base, BaseModel):
341 __tablename__ = 'rhodecode_ui'
341 __tablename__ = 'rhodecode_ui'
342 __table_args__ = (
342 __table_args__ = (
343 UniqueConstraint('ui_key'),
343 UniqueConstraint('ui_key'),
344 {'extend_existing': True, 'mysql_engine': 'InnoDB',
344 {'extend_existing': True, 'mysql_engine': 'InnoDB',
345 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
345 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
346 )
346 )
347
347
348 HOOK_REPO_SIZE = 'changegroup.repo_size'
348 HOOK_REPO_SIZE = 'changegroup.repo_size'
349 # HG
349 # HG
350 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
350 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
351 HOOK_PULL = 'outgoing.pull_logger'
351 HOOK_PULL = 'outgoing.pull_logger'
352 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
352 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
353 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
353 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
354 HOOK_PUSH = 'changegroup.push_logger'
354 HOOK_PUSH = 'changegroup.push_logger'
355
355
356 # TODO: johbo: Unify way how hooks are configured for git and hg,
356 # TODO: johbo: Unify way how hooks are configured for git and hg,
357 # git part is currently hardcoded.
357 # git part is currently hardcoded.
358
358
359 # SVN PATTERNS
359 # SVN PATTERNS
360 SVN_BRANCH_ID = 'vcs_svn_branch'
360 SVN_BRANCH_ID = 'vcs_svn_branch'
361 SVN_TAG_ID = 'vcs_svn_tag'
361 SVN_TAG_ID = 'vcs_svn_tag'
362
362
363 ui_id = Column(
363 ui_id = Column(
364 "ui_id", Integer(), nullable=False, unique=True, default=None,
364 "ui_id", Integer(), nullable=False, unique=True, default=None,
365 primary_key=True)
365 primary_key=True)
366 ui_section = Column(
366 ui_section = Column(
367 "ui_section", String(255), nullable=True, unique=None, default=None)
367 "ui_section", String(255), nullable=True, unique=None, default=None)
368 ui_key = Column(
368 ui_key = Column(
369 "ui_key", String(255), nullable=True, unique=None, default=None)
369 "ui_key", String(255), nullable=True, unique=None, default=None)
370 ui_value = Column(
370 ui_value = Column(
371 "ui_value", String(255), nullable=True, unique=None, default=None)
371 "ui_value", String(255), nullable=True, unique=None, default=None)
372 ui_active = Column(
372 ui_active = Column(
373 "ui_active", Boolean(), nullable=True, unique=None, default=True)
373 "ui_active", Boolean(), nullable=True, unique=None, default=True)
374
374
375 def __repr__(self):
375 def __repr__(self):
376 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
376 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
377 self.ui_key, self.ui_value)
377 self.ui_key, self.ui_value)
378
378
379
379
380 class RepoRhodeCodeSetting(Base, BaseModel):
380 class RepoRhodeCodeSetting(Base, BaseModel):
381 __tablename__ = 'repo_rhodecode_settings'
381 __tablename__ = 'repo_rhodecode_settings'
382 __table_args__ = (
382 __table_args__ = (
383 UniqueConstraint(
383 UniqueConstraint(
384 'app_settings_name', 'repository_id',
384 'app_settings_name', 'repository_id',
385 name='uq_repo_rhodecode_setting_name_repo_id'),
385 name='uq_repo_rhodecode_setting_name_repo_id'),
386 {'extend_existing': True, 'mysql_engine': 'InnoDB',
386 {'extend_existing': True, 'mysql_engine': 'InnoDB',
387 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
387 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
388 )
388 )
389
389
390 repository_id = Column(
390 repository_id = Column(
391 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
391 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
392 nullable=False)
392 nullable=False)
393 app_settings_id = Column(
393 app_settings_id = Column(
394 "app_settings_id", Integer(), nullable=False, unique=True,
394 "app_settings_id", Integer(), nullable=False, unique=True,
395 default=None, primary_key=True)
395 default=None, primary_key=True)
396 app_settings_name = Column(
396 app_settings_name = Column(
397 "app_settings_name", String(255), nullable=True, unique=None,
397 "app_settings_name", String(255), nullable=True, unique=None,
398 default=None)
398 default=None)
399 _app_settings_value = Column(
399 _app_settings_value = Column(
400 "app_settings_value", String(4096), nullable=True, unique=None,
400 "app_settings_value", String(4096), nullable=True, unique=None,
401 default=None)
401 default=None)
402 _app_settings_type = Column(
402 _app_settings_type = Column(
403 "app_settings_type", String(255), nullable=True, unique=None,
403 "app_settings_type", String(255), nullable=True, unique=None,
404 default=None)
404 default=None)
405
405
406 repository = relationship('Repository')
406 repository = relationship('Repository')
407
407
408 def __init__(self, repository_id, key='', val='', type='unicode'):
408 def __init__(self, repository_id, key='', val='', type='unicode'):
409 self.repository_id = repository_id
409 self.repository_id = repository_id
410 self.app_settings_name = key
410 self.app_settings_name = key
411 self.app_settings_type = type
411 self.app_settings_type = type
412 self.app_settings_value = val
412 self.app_settings_value = val
413
413
414 @validates('_app_settings_value')
414 @validates('_app_settings_value')
415 def validate_settings_value(self, key, val):
415 def validate_settings_value(self, key, val):
416 assert type(val) == unicode
416 assert type(val) == unicode
417 return val
417 return val
418
418
419 @hybrid_property
419 @hybrid_property
420 def app_settings_value(self):
420 def app_settings_value(self):
421 v = self._app_settings_value
421 v = self._app_settings_value
422 type_ = self.app_settings_type
422 type_ = self.app_settings_type
423 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
423 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
424 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
424 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
425 return converter(v)
425 return converter(v)
426
426
427 @app_settings_value.setter
427 @app_settings_value.setter
428 def app_settings_value(self, val):
428 def app_settings_value(self, val):
429 """
429 """
430 Setter that will always make sure we use unicode in app_settings_value
430 Setter that will always make sure we use unicode in app_settings_value
431
431
432 :param val:
432 :param val:
433 """
433 """
434 self._app_settings_value = safe_unicode(val)
434 self._app_settings_value = safe_unicode(val)
435
435
436 @hybrid_property
436 @hybrid_property
437 def app_settings_type(self):
437 def app_settings_type(self):
438 return self._app_settings_type
438 return self._app_settings_type
439
439
440 @app_settings_type.setter
440 @app_settings_type.setter
441 def app_settings_type(self, val):
441 def app_settings_type(self, val):
442 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
442 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
443 if val not in SETTINGS_TYPES:
443 if val not in SETTINGS_TYPES:
444 raise Exception('type must be one of %s got %s'
444 raise Exception('type must be one of %s got %s'
445 % (SETTINGS_TYPES.keys(), val))
445 % (SETTINGS_TYPES.keys(), val))
446 self._app_settings_type = val
446 self._app_settings_type = val
447
447
448 def __unicode__(self):
448 def __unicode__(self):
449 return u"<%s('%s:%s:%s[%s]')>" % (
449 return u"<%s('%s:%s:%s[%s]')>" % (
450 self.__class__.__name__, self.repository.repo_name,
450 self.__class__.__name__, self.repository.repo_name,
451 self.app_settings_name, self.app_settings_value,
451 self.app_settings_name, self.app_settings_value,
452 self.app_settings_type
452 self.app_settings_type
453 )
453 )
454
454
455
455
456 class RepoRhodeCodeUi(Base, BaseModel):
456 class RepoRhodeCodeUi(Base, BaseModel):
457 __tablename__ = 'repo_rhodecode_ui'
457 __tablename__ = 'repo_rhodecode_ui'
458 __table_args__ = (
458 __table_args__ = (
459 UniqueConstraint(
459 UniqueConstraint(
460 'repository_id', 'ui_section', 'ui_key',
460 'repository_id', 'ui_section', 'ui_key',
461 name='uq_repo_rhodecode_ui_repository_id_section_key'),
461 name='uq_repo_rhodecode_ui_repository_id_section_key'),
462 {'extend_existing': True, 'mysql_engine': 'InnoDB',
462 {'extend_existing': True, 'mysql_engine': 'InnoDB',
463 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
463 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
464 )
464 )
465
465
466 repository_id = Column(
466 repository_id = Column(
467 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
467 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
468 nullable=False)
468 nullable=False)
469 ui_id = Column(
469 ui_id = Column(
470 "ui_id", Integer(), nullable=False, unique=True, default=None,
470 "ui_id", Integer(), nullable=False, unique=True, default=None,
471 primary_key=True)
471 primary_key=True)
472 ui_section = Column(
472 ui_section = Column(
473 "ui_section", String(255), nullable=True, unique=None, default=None)
473 "ui_section", String(255), nullable=True, unique=None, default=None)
474 ui_key = Column(
474 ui_key = Column(
475 "ui_key", String(255), nullable=True, unique=None, default=None)
475 "ui_key", String(255), nullable=True, unique=None, default=None)
476 ui_value = Column(
476 ui_value = Column(
477 "ui_value", String(255), nullable=True, unique=None, default=None)
477 "ui_value", String(255), nullable=True, unique=None, default=None)
478 ui_active = Column(
478 ui_active = Column(
479 "ui_active", Boolean(), nullable=True, unique=None, default=True)
479 "ui_active", Boolean(), nullable=True, unique=None, default=True)
480
480
481 repository = relationship('Repository')
481 repository = relationship('Repository')
482
482
483 def __repr__(self):
483 def __repr__(self):
484 return '<%s[%s:%s]%s=>%s]>' % (
484 return '<%s[%s:%s]%s=>%s]>' % (
485 self.__class__.__name__, self.repository.repo_name,
485 self.__class__.__name__, self.repository.repo_name,
486 self.ui_section, self.ui_key, self.ui_value)
486 self.ui_section, self.ui_key, self.ui_value)
487
487
488
488
489 class User(Base, BaseModel):
489 class User(Base, BaseModel):
490 __tablename__ = 'users'
490 __tablename__ = 'users'
491 __table_args__ = (
491 __table_args__ = (
492 UniqueConstraint('username'), UniqueConstraint('email'),
492 UniqueConstraint('username'), UniqueConstraint('email'),
493 Index('u_username_idx', 'username'),
493 Index('u_username_idx', 'username'),
494 Index('u_email_idx', 'email'),
494 Index('u_email_idx', 'email'),
495 {'extend_existing': True, 'mysql_engine': 'InnoDB',
495 {'extend_existing': True, 'mysql_engine': 'InnoDB',
496 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
496 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
497 )
497 )
498 DEFAULT_USER = 'default'
498 DEFAULT_USER = 'default'
499 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
499 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
500 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
500 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
501
501
502 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
502 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
503 username = Column("username", String(255), nullable=True, unique=None, default=None)
503 username = Column("username", String(255), nullable=True, unique=None, default=None)
504 password = Column("password", String(255), nullable=True, unique=None, default=None)
504 password = Column("password", String(255), nullable=True, unique=None, default=None)
505 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
505 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
506 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
506 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
507 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
507 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
508 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
508 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
509 _email = Column("email", String(255), nullable=True, unique=None, default=None)
509 _email = Column("email", String(255), nullable=True, unique=None, default=None)
510 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
510 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
511 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
511 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
512 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
512 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
513 api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
513 api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
514 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
514 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
515 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
515 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
516 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
516 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
517
517
518 user_log = relationship('UserLog')
518 user_log = relationship('UserLog')
519 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
519 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
520
520
521 repositories = relationship('Repository')
521 repositories = relationship('Repository')
522 repository_groups = relationship('RepoGroup')
522 repository_groups = relationship('RepoGroup')
523 user_groups = relationship('UserGroup')
523 user_groups = relationship('UserGroup')
524
524
525 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
525 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
526 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
526 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
527
527
528 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
528 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
529 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
529 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
530 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
530 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
531
531
532 group_member = relationship('UserGroupMember', cascade='all')
532 group_member = relationship('UserGroupMember', cascade='all')
533
533
534 notifications = relationship('UserNotification', cascade='all')
534 notifications = relationship('UserNotification', cascade='all')
535 # notifications assigned to this user
535 # notifications assigned to this user
536 user_created_notifications = relationship('Notification', cascade='all')
536 user_created_notifications = relationship('Notification', cascade='all')
537 # comments created by this user
537 # comments created by this user
538 user_comments = relationship('ChangesetComment', cascade='all')
538 user_comments = relationship('ChangesetComment', cascade='all')
539 # user profile extra info
539 # user profile extra info
540 user_emails = relationship('UserEmailMap', cascade='all')
540 user_emails = relationship('UserEmailMap', cascade='all')
541 user_ip_map = relationship('UserIpMap', cascade='all')
541 user_ip_map = relationship('UserIpMap', cascade='all')
542 user_auth_tokens = relationship('UserApiKeys', cascade='all')
542 user_auth_tokens = relationship('UserApiKeys', cascade='all')
543 # gists
543 # gists
544 user_gists = relationship('Gist', cascade='all')
544 user_gists = relationship('Gist', cascade='all')
545 # user pull requests
545 # user pull requests
546 user_pull_requests = relationship('PullRequest', cascade='all')
546 user_pull_requests = relationship('PullRequest', cascade='all')
547 # external identities
547 # external identities
548 extenal_identities = relationship(
548 extenal_identities = relationship(
549 'ExternalIdentity',
549 'ExternalIdentity',
550 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
550 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
551 cascade='all')
551 cascade='all')
552
552
553 def __unicode__(self):
553 def __unicode__(self):
554 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
554 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
555 self.user_id, self.username)
555 self.user_id, self.username)
556
556
557 @hybrid_property
557 @hybrid_property
558 def email(self):
558 def email(self):
559 return self._email
559 return self._email
560
560
561 @email.setter
561 @email.setter
562 def email(self, val):
562 def email(self, val):
563 self._email = val.lower() if val else None
563 self._email = val.lower() if val else None
564
564
565 @property
565 @property
566 def firstname(self):
566 def firstname(self):
567 # alias for future
567 # alias for future
568 return self.name
568 return self.name
569
569
570 @property
570 @property
571 def emails(self):
571 def emails(self):
572 other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
572 other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
573 return [self.email] + [x.email for x in other]
573 return [self.email] + [x.email for x in other]
574
574
575 @property
575 @property
576 def auth_tokens(self):
576 def auth_tokens(self):
577 return [self.api_key] + [x.api_key for x in self.extra_auth_tokens]
577 return [self.api_key] + [x.api_key for x in self.extra_auth_tokens]
578
578
579 @property
579 @property
580 def extra_auth_tokens(self):
580 def extra_auth_tokens(self):
581 return UserApiKeys.query().filter(UserApiKeys.user == self).all()
581 return UserApiKeys.query().filter(UserApiKeys.user == self).all()
582
582
583 @property
583 @property
584 def feed_token(self):
584 def feed_token(self):
585 return self.get_feed_token()
585 return self.get_feed_token()
586
586
587 def get_feed_token(self):
587 def get_feed_token(self):
588 feed_tokens = UserApiKeys.query()\
588 feed_tokens = UserApiKeys.query()\
589 .filter(UserApiKeys.user == self)\
589 .filter(UserApiKeys.user == self)\
590 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
590 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
591 .all()
591 .all()
592 if feed_tokens:
592 if feed_tokens:
593 return feed_tokens[0].api_key
593 return feed_tokens[0].api_key
594 return 'NO_FEED_TOKEN_AVAILABLE'
594 return 'NO_FEED_TOKEN_AVAILABLE'
595
595
596 @classmethod
596 @classmethod
597 def extra_valid_auth_tokens(cls, user, role=None):
597 def extra_valid_auth_tokens(cls, user, role=None):
598 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
598 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
599 .filter(or_(UserApiKeys.expires == -1,
599 .filter(or_(UserApiKeys.expires == -1,
600 UserApiKeys.expires >= time.time()))
600 UserApiKeys.expires >= time.time()))
601 if role:
601 if role:
602 tokens = tokens.filter(or_(UserApiKeys.role == role,
602 tokens = tokens.filter(or_(UserApiKeys.role == role,
603 UserApiKeys.role == UserApiKeys.ROLE_ALL))
603 UserApiKeys.role == UserApiKeys.ROLE_ALL))
604 return tokens.all()
604 return tokens.all()
605
605
606 def authenticate_by_token(self, auth_token, roles=None,
606 def authenticate_by_token(self, auth_token, roles=None):
607 include_builtin_token=False):
608 from rhodecode.lib import auth
607 from rhodecode.lib import auth
609
608
610 log.debug('Trying to authenticate user: %s via auth-token, '
609 log.debug('Trying to authenticate user: %s via auth-token, '
611 'and roles: %s', self, roles)
610 'and roles: %s', self, roles)
612
611
613 if not auth_token:
612 if not auth_token:
614 return False
613 return False
615
614
616 crypto_backend = auth.crypto_backend()
615 crypto_backend = auth.crypto_backend()
617
616
618 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
617 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
619 tokens_q = UserApiKeys.query()\
618 tokens_q = UserApiKeys.query()\
620 .filter(UserApiKeys.user_id == self.user_id)\
619 .filter(UserApiKeys.user_id == self.user_id)\
621 .filter(or_(UserApiKeys.expires == -1,
620 .filter(or_(UserApiKeys.expires == -1,
622 UserApiKeys.expires >= time.time()))
621 UserApiKeys.expires >= time.time()))
623
622
624 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
623 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
625
624
626 maybe_builtin = []
627 if include_builtin_token:
628 maybe_builtin = [AttributeDict({'api_key': self.api_key})]
629
630 plain_tokens = []
625 plain_tokens = []
631 hash_tokens = []
626 hash_tokens = []
632
627
633 for token in tokens_q.all() + maybe_builtin:
628 for token in tokens_q.all():
634 if token.api_key.startswith(crypto_backend.ENC_PREF):
629 if token.api_key.startswith(crypto_backend.ENC_PREF):
635 hash_tokens.append(token.api_key)
630 hash_tokens.append(token.api_key)
636 else:
631 else:
637 plain_tokens.append(token.api_key)
632 plain_tokens.append(token.api_key)
638
633
639 is_plain_match = auth_token in plain_tokens
634 is_plain_match = auth_token in plain_tokens
640 if is_plain_match:
635 if is_plain_match:
641 return True
636 return True
642
637
643 for hashed in hash_tokens:
638 for hashed in hash_tokens:
644 # marcink: this is expensive to calculate, but the most secure
639 # marcink: this is expensive to calculate, but the most secure
645 match = crypto_backend.hash_check(auth_token, hashed)
640 match = crypto_backend.hash_check(auth_token, hashed)
646 if match:
641 if match:
647 return True
642 return True
648
643
649 return False
644 return False
650
645
651 @property
646 @property
652 def builtin_token_roles(self):
647 def builtin_token_roles(self):
653 roles = [
648 roles = [
654 UserApiKeys.ROLE_API, UserApiKeys.ROLE_FEED, UserApiKeys.ROLE_HTTP
649 UserApiKeys.ROLE_API, UserApiKeys.ROLE_FEED, UserApiKeys.ROLE_HTTP
655 ]
650 ]
656 return map(UserApiKeys._get_role_name, roles)
651 return map(UserApiKeys._get_role_name, roles)
657
652
658 @property
653 @property
659 def ip_addresses(self):
654 def ip_addresses(self):
660 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
655 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
661 return [x.ip_addr for x in ret]
656 return [x.ip_addr for x in ret]
662
657
663 @property
658 @property
664 def username_and_name(self):
659 def username_and_name(self):
665 return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
660 return '%s (%s %s)' % (self.username, self.firstname, self.lastname)
666
661
667 @property
662 @property
668 def username_or_name_or_email(self):
663 def username_or_name_or_email(self):
669 full_name = self.full_name if self.full_name is not ' ' else None
664 full_name = self.full_name if self.full_name is not ' ' else None
670 return self.username or full_name or self.email
665 return self.username or full_name or self.email
671
666
672 @property
667 @property
673 def full_name(self):
668 def full_name(self):
674 return '%s %s' % (self.firstname, self.lastname)
669 return '%s %s' % (self.firstname, self.lastname)
675
670
676 @property
671 @property
677 def full_name_or_username(self):
672 def full_name_or_username(self):
678 return ('%s %s' % (self.firstname, self.lastname)
673 return ('%s %s' % (self.firstname, self.lastname)
679 if (self.firstname and self.lastname) else self.username)
674 if (self.firstname and self.lastname) else self.username)
680
675
681 @property
676 @property
682 def full_contact(self):
677 def full_contact(self):
683 return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
678 return '%s %s <%s>' % (self.firstname, self.lastname, self.email)
684
679
685 @property
680 @property
686 def short_contact(self):
681 def short_contact(self):
687 return '%s %s' % (self.firstname, self.lastname)
682 return '%s %s' % (self.firstname, self.lastname)
688
683
689 @property
684 @property
690 def is_admin(self):
685 def is_admin(self):
691 return self.admin
686 return self.admin
692
687
693 @property
688 @property
694 def AuthUser(self):
689 def AuthUser(self):
695 """
690 """
696 Returns instance of AuthUser for this user
691 Returns instance of AuthUser for this user
697 """
692 """
698 from rhodecode.lib.auth import AuthUser
693 from rhodecode.lib.auth import AuthUser
699 return AuthUser(user_id=self.user_id, api_key=self.api_key,
694 return AuthUser(user_id=self.user_id, api_key=self.api_key,
700 username=self.username)
695 username=self.username)
701
696
702 @hybrid_property
697 @hybrid_property
703 def user_data(self):
698 def user_data(self):
704 if not self._user_data:
699 if not self._user_data:
705 return {}
700 return {}
706
701
707 try:
702 try:
708 return json.loads(self._user_data)
703 return json.loads(self._user_data)
709 except TypeError:
704 except TypeError:
710 return {}
705 return {}
711
706
712 @user_data.setter
707 @user_data.setter
713 def user_data(self, val):
708 def user_data(self, val):
714 if not isinstance(val, dict):
709 if not isinstance(val, dict):
715 raise Exception('user_data must be dict, got %s' % type(val))
710 raise Exception('user_data must be dict, got %s' % type(val))
716 try:
711 try:
717 self._user_data = json.dumps(val)
712 self._user_data = json.dumps(val)
718 except Exception:
713 except Exception:
719 log.error(traceback.format_exc())
714 log.error(traceback.format_exc())
720
715
721 @classmethod
716 @classmethod
722 def get_by_username(cls, username, case_insensitive=False,
717 def get_by_username(cls, username, case_insensitive=False,
723 cache=False, identity_cache=False):
718 cache=False, identity_cache=False):
724 session = Session()
719 session = Session()
725
720
726 if case_insensitive:
721 if case_insensitive:
727 q = cls.query().filter(
722 q = cls.query().filter(
728 func.lower(cls.username) == func.lower(username))
723 func.lower(cls.username) == func.lower(username))
729 else:
724 else:
730 q = cls.query().filter(cls.username == username)
725 q = cls.query().filter(cls.username == username)
731
726
732 if cache:
727 if cache:
733 if identity_cache:
728 if identity_cache:
734 val = cls.identity_cache(session, 'username', username)
729 val = cls.identity_cache(session, 'username', username)
735 if val:
730 if val:
736 return val
731 return val
737 else:
732 else:
738 q = q.options(
733 q = q.options(
739 FromCache("sql_cache_short",
734 FromCache("sql_cache_short",
740 "get_user_by_name_%s" % _hash_key(username)))
735 "get_user_by_name_%s" % _hash_key(username)))
741
736
742 return q.scalar()
737 return q.scalar()
743
738
744 @classmethod
739 @classmethod
745 def get_by_auth_token(cls, auth_token, cache=False, fallback=True):
740 def get_by_auth_token(cls, auth_token, cache=False, fallback=True):
746 q = cls.query().filter(cls.api_key == auth_token)
741 q = cls.query().filter(cls.api_key == auth_token)
747
742
748 if cache:
743 if cache:
749 q = q.options(FromCache("sql_cache_short",
744 q = q.options(FromCache("sql_cache_short",
750 "get_auth_token_%s" % auth_token))
745 "get_auth_token_%s" % auth_token))
751 res = q.scalar()
746 res = q.scalar()
752
747
753 if fallback and not res:
748 if fallback and not res:
754 #fallback to additional keys
749 #fallback to additional keys
755 _res = UserApiKeys.query()\
750 _res = UserApiKeys.query()\
756 .filter(UserApiKeys.api_key == auth_token)\
751 .filter(UserApiKeys.api_key == auth_token)\
757 .filter(or_(UserApiKeys.expires == -1,
752 .filter(or_(UserApiKeys.expires == -1,
758 UserApiKeys.expires >= time.time()))\
753 UserApiKeys.expires >= time.time()))\
759 .first()
754 .first()
760 if _res:
755 if _res:
761 res = _res.user
756 res = _res.user
762 return res
757 return res
763
758
764 @classmethod
759 @classmethod
765 def get_by_email(cls, email, case_insensitive=False, cache=False):
760 def get_by_email(cls, email, case_insensitive=False, cache=False):
766
761
767 if case_insensitive:
762 if case_insensitive:
768 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
763 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
769
764
770 else:
765 else:
771 q = cls.query().filter(cls.email == email)
766 q = cls.query().filter(cls.email == email)
772
767
773 if cache:
768 if cache:
774 q = q.options(FromCache("sql_cache_short",
769 q = q.options(FromCache("sql_cache_short",
775 "get_email_key_%s" % _hash_key(email)))
770 "get_email_key_%s" % _hash_key(email)))
776
771
777 ret = q.scalar()
772 ret = q.scalar()
778 if ret is None:
773 if ret is None:
779 q = UserEmailMap.query()
774 q = UserEmailMap.query()
780 # try fetching in alternate email map
775 # try fetching in alternate email map
781 if case_insensitive:
776 if case_insensitive:
782 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
777 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
783 else:
778 else:
784 q = q.filter(UserEmailMap.email == email)
779 q = q.filter(UserEmailMap.email == email)
785 q = q.options(joinedload(UserEmailMap.user))
780 q = q.options(joinedload(UserEmailMap.user))
786 if cache:
781 if cache:
787 q = q.options(FromCache("sql_cache_short",
782 q = q.options(FromCache("sql_cache_short",
788 "get_email_map_key_%s" % email))
783 "get_email_map_key_%s" % email))
789 ret = getattr(q.scalar(), 'user', None)
784 ret = getattr(q.scalar(), 'user', None)
790
785
791 return ret
786 return ret
792
787
793 @classmethod
788 @classmethod
794 def get_from_cs_author(cls, author):
789 def get_from_cs_author(cls, author):
795 """
790 """
796 Tries to get User objects out of commit author string
791 Tries to get User objects out of commit author string
797
792
798 :param author:
793 :param author:
799 """
794 """
800 from rhodecode.lib.helpers import email, author_name
795 from rhodecode.lib.helpers import email, author_name
801 # Valid email in the attribute passed, see if they're in the system
796 # Valid email in the attribute passed, see if they're in the system
802 _email = email(author)
797 _email = email(author)
803 if _email:
798 if _email:
804 user = cls.get_by_email(_email, case_insensitive=True)
799 user = cls.get_by_email(_email, case_insensitive=True)
805 if user:
800 if user:
806 return user
801 return user
807 # Maybe we can match by username?
802 # Maybe we can match by username?
808 _author = author_name(author)
803 _author = author_name(author)
809 user = cls.get_by_username(_author, case_insensitive=True)
804 user = cls.get_by_username(_author, case_insensitive=True)
810 if user:
805 if user:
811 return user
806 return user
812
807
813 def update_userdata(self, **kwargs):
808 def update_userdata(self, **kwargs):
814 usr = self
809 usr = self
815 old = usr.user_data
810 old = usr.user_data
816 old.update(**kwargs)
811 old.update(**kwargs)
817 usr.user_data = old
812 usr.user_data = old
818 Session().add(usr)
813 Session().add(usr)
819 log.debug('updated userdata with ', kwargs)
814 log.debug('updated userdata with ', kwargs)
820
815
821 def update_lastlogin(self):
816 def update_lastlogin(self):
822 """Update user lastlogin"""
817 """Update user lastlogin"""
823 self.last_login = datetime.datetime.now()
818 self.last_login = datetime.datetime.now()
824 Session().add(self)
819 Session().add(self)
825 log.debug('updated user %s lastlogin', self.username)
820 log.debug('updated user %s lastlogin', self.username)
826
821
827 def update_lastactivity(self):
822 def update_lastactivity(self):
828 """Update user lastactivity"""
823 """Update user lastactivity"""
829 usr = self
824 usr = self
830 old = usr.user_data
825 old = usr.user_data
831 old.update({'last_activity': time.time()})
826 old.update({'last_activity': time.time()})
832 usr.user_data = old
827 usr.user_data = old
833 Session().add(usr)
828 Session().add(usr)
834 log.debug('updated user %s lastactivity', usr.username)
829 log.debug('updated user %s lastactivity', usr.username)
835
830
836 def update_password(self, new_password, change_api_key=False):
831 def update_password(self, new_password, change_api_key=False):
837 from rhodecode.lib.auth import get_crypt_password,generate_auth_token
832 from rhodecode.lib.auth import get_crypt_password,generate_auth_token
838
833
839 self.password = get_crypt_password(new_password)
834 self.password = get_crypt_password(new_password)
840 if change_api_key:
835 if change_api_key:
841 self.api_key = generate_auth_token(self.username)
836 self.api_key = generate_auth_token(self.username)
842 Session().add(self)
837 Session().add(self)
843
838
844 @classmethod
839 @classmethod
845 def get_first_super_admin(cls):
840 def get_first_super_admin(cls):
846 user = User.query().filter(User.admin == true()).first()
841 user = User.query().filter(User.admin == true()).first()
847 if user is None:
842 if user is None:
848 raise Exception('FATAL: Missing administrative account!')
843 raise Exception('FATAL: Missing administrative account!')
849 return user
844 return user
850
845
851 @classmethod
846 @classmethod
852 def get_all_super_admins(cls):
847 def get_all_super_admins(cls):
853 """
848 """
854 Returns all admin accounts sorted by username
849 Returns all admin accounts sorted by username
855 """
850 """
856 return User.query().filter(User.admin == true())\
851 return User.query().filter(User.admin == true())\
857 .order_by(User.username.asc()).all()
852 .order_by(User.username.asc()).all()
858
853
859 @classmethod
854 @classmethod
860 def get_default_user(cls, cache=False):
855 def get_default_user(cls, cache=False):
861 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
856 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
862 if user is None:
857 if user is None:
863 raise Exception('FATAL: Missing default account!')
858 raise Exception('FATAL: Missing default account!')
864 return user
859 return user
865
860
866 def _get_default_perms(self, user, suffix=''):
861 def _get_default_perms(self, user, suffix=''):
867 from rhodecode.model.permission import PermissionModel
862 from rhodecode.model.permission import PermissionModel
868 return PermissionModel().get_default_perms(user.user_perms, suffix)
863 return PermissionModel().get_default_perms(user.user_perms, suffix)
869
864
870 def get_default_perms(self, suffix=''):
865 def get_default_perms(self, suffix=''):
871 return self._get_default_perms(self, suffix)
866 return self._get_default_perms(self, suffix)
872
867
873 def get_api_data(self, include_secrets=False, details='full'):
868 def get_api_data(self, include_secrets=False, details='full'):
874 """
869 """
875 Common function for generating user related data for API
870 Common function for generating user related data for API
876
871
877 :param include_secrets: By default secrets in the API data will be replaced
872 :param include_secrets: By default secrets in the API data will be replaced
878 by a placeholder value to prevent exposing this data by accident. In case
873 by a placeholder value to prevent exposing this data by accident. In case
879 this data shall be exposed, set this flag to ``True``.
874 this data shall be exposed, set this flag to ``True``.
880
875
881 :param details: details can be 'basic|full' basic gives only a subset of
876 :param details: details can be 'basic|full' basic gives only a subset of
882 the available user information that includes user_id, name and emails.
877 the available user information that includes user_id, name and emails.
883 """
878 """
884 user = self
879 user = self
885 user_data = self.user_data
880 user_data = self.user_data
886 data = {
881 data = {
887 'user_id': user.user_id,
882 'user_id': user.user_id,
888 'username': user.username,
883 'username': user.username,
889 'firstname': user.name,
884 'firstname': user.name,
890 'lastname': user.lastname,
885 'lastname': user.lastname,
891 'email': user.email,
886 'email': user.email,
892 'emails': user.emails,
887 'emails': user.emails,
893 }
888 }
894 if details == 'basic':
889 if details == 'basic':
895 return data
890 return data
896
891
897 api_key_length = 40
892 api_key_length = 40
898 api_key_replacement = '*' * api_key_length
893 api_key_replacement = '*' * api_key_length
899
894
900 extras = {
895 extras = {
901 'api_key': api_key_replacement,
896 'api_key': api_key_replacement,
902 'api_keys': [api_key_replacement],
897 'api_keys': [api_key_replacement],
903 'active': user.active,
898 'active': user.active,
904 'admin': user.admin,
899 'admin': user.admin,
905 'extern_type': user.extern_type,
900 'extern_type': user.extern_type,
906 'extern_name': user.extern_name,
901 'extern_name': user.extern_name,
907 'last_login': user.last_login,
902 'last_login': user.last_login,
908 'ip_addresses': user.ip_addresses,
903 'ip_addresses': user.ip_addresses,
909 'language': user_data.get('language')
904 'language': user_data.get('language')
910 }
905 }
911 data.update(extras)
906 data.update(extras)
912
907
913 if include_secrets:
908 if include_secrets:
914 data['api_key'] = user.api_key
909 data['api_key'] = user.api_key
915 data['api_keys'] = user.auth_tokens
910 data['api_keys'] = user.auth_tokens
916 return data
911 return data
917
912
918 def __json__(self):
913 def __json__(self):
919 data = {
914 data = {
920 'full_name': self.full_name,
915 'full_name': self.full_name,
921 'full_name_or_username': self.full_name_or_username,
916 'full_name_or_username': self.full_name_or_username,
922 'short_contact': self.short_contact,
917 'short_contact': self.short_contact,
923 'full_contact': self.full_contact,
918 'full_contact': self.full_contact,
924 }
919 }
925 data.update(self.get_api_data())
920 data.update(self.get_api_data())
926 return data
921 return data
927
922
928
923
929 class UserApiKeys(Base, BaseModel):
924 class UserApiKeys(Base, BaseModel):
930 __tablename__ = 'user_api_keys'
925 __tablename__ = 'user_api_keys'
931 __table_args__ = (
926 __table_args__ = (
932 Index('uak_api_key_idx', 'api_key'),
927 Index('uak_api_key_idx', 'api_key'),
933 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
928 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
934 UniqueConstraint('api_key'),
929 UniqueConstraint('api_key'),
935 {'extend_existing': True, 'mysql_engine': 'InnoDB',
930 {'extend_existing': True, 'mysql_engine': 'InnoDB',
936 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
931 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
937 )
932 )
938 __mapper_args__ = {}
933 __mapper_args__ = {}
939
934
940 # ApiKey role
935 # ApiKey role
941 ROLE_ALL = 'token_role_all'
936 ROLE_ALL = 'token_role_all'
942 ROLE_HTTP = 'token_role_http'
937 ROLE_HTTP = 'token_role_http'
943 ROLE_VCS = 'token_role_vcs'
938 ROLE_VCS = 'token_role_vcs'
944 ROLE_API = 'token_role_api'
939 ROLE_API = 'token_role_api'
945 ROLE_FEED = 'token_role_feed'
940 ROLE_FEED = 'token_role_feed'
946 ROLE_PASSWORD_RESET = 'token_password_reset'
941 ROLE_PASSWORD_RESET = 'token_password_reset'
947
942
948 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
943 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
949
944
950 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
945 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
951 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
946 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
952 api_key = Column("api_key", String(255), nullable=False, unique=True)
947 api_key = Column("api_key", String(255), nullable=False, unique=True)
953 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
948 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
954 expires = Column('expires', Float(53), nullable=False)
949 expires = Column('expires', Float(53), nullable=False)
955 role = Column('role', String(255), nullable=True)
950 role = Column('role', String(255), nullable=True)
956 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
951 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
957
952
958 # scope columns
953 # scope columns
959 repo_id = Column(
954 repo_id = Column(
960 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
955 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
961 nullable=True, unique=None, default=None)
956 nullable=True, unique=None, default=None)
962 repo = relationship('Repository', lazy='joined')
957 repo = relationship('Repository', lazy='joined')
963
958
964 repo_group_id = Column(
959 repo_group_id = Column(
965 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
960 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
966 nullable=True, unique=None, default=None)
961 nullable=True, unique=None, default=None)
967 repo_group = relationship('RepoGroup', lazy='joined')
962 repo_group = relationship('RepoGroup', lazy='joined')
968
963
969 user = relationship('User', lazy='joined')
964 user = relationship('User', lazy='joined')
970
965
971 @classmethod
966 @classmethod
972 def _get_role_name(cls, role):
967 def _get_role_name(cls, role):
973 return {
968 return {
974 cls.ROLE_ALL: _('all'),
969 cls.ROLE_ALL: _('all'),
975 cls.ROLE_HTTP: _('http/web interface'),
970 cls.ROLE_HTTP: _('http/web interface'),
976 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
971 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
977 cls.ROLE_API: _('api calls'),
972 cls.ROLE_API: _('api calls'),
978 cls.ROLE_FEED: _('feed access'),
973 cls.ROLE_FEED: _('feed access'),
979 }.get(role, role)
974 }.get(role, role)
980
975
981 @property
976 @property
982 def expired(self):
977 def expired(self):
983 if self.expires == -1:
978 if self.expires == -1:
984 return False
979 return False
985 return time.time() > self.expires
980 return time.time() > self.expires
986
981
987 @property
982 @property
988 def role_humanized(self):
983 def role_humanized(self):
989 return self._get_role_name(self.role)
984 return self._get_role_name(self.role)
990
985
991
986
992 class UserEmailMap(Base, BaseModel):
987 class UserEmailMap(Base, BaseModel):
993 __tablename__ = 'user_email_map'
988 __tablename__ = 'user_email_map'
994 __table_args__ = (
989 __table_args__ = (
995 Index('uem_email_idx', 'email'),
990 Index('uem_email_idx', 'email'),
996 UniqueConstraint('email'),
991 UniqueConstraint('email'),
997 {'extend_existing': True, 'mysql_engine': 'InnoDB',
992 {'extend_existing': True, 'mysql_engine': 'InnoDB',
998 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
993 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
999 )
994 )
1000 __mapper_args__ = {}
995 __mapper_args__ = {}
1001
996
1002 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
997 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1003 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
998 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1004 _email = Column("email", String(255), nullable=True, unique=False, default=None)
999 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1005 user = relationship('User', lazy='joined')
1000 user = relationship('User', lazy='joined')
1006
1001
1007 @validates('_email')
1002 @validates('_email')
1008 def validate_email(self, key, email):
1003 def validate_email(self, key, email):
1009 # check if this email is not main one
1004 # check if this email is not main one
1010 main_email = Session().query(User).filter(User.email == email).scalar()
1005 main_email = Session().query(User).filter(User.email == email).scalar()
1011 if main_email is not None:
1006 if main_email is not None:
1012 raise AttributeError('email %s is present is user table' % email)
1007 raise AttributeError('email %s is present is user table' % email)
1013 return email
1008 return email
1014
1009
1015 @hybrid_property
1010 @hybrid_property
1016 def email(self):
1011 def email(self):
1017 return self._email
1012 return self._email
1018
1013
1019 @email.setter
1014 @email.setter
1020 def email(self, val):
1015 def email(self, val):
1021 self._email = val.lower() if val else None
1016 self._email = val.lower() if val else None
1022
1017
1023
1018
1024 class UserIpMap(Base, BaseModel):
1019 class UserIpMap(Base, BaseModel):
1025 __tablename__ = 'user_ip_map'
1020 __tablename__ = 'user_ip_map'
1026 __table_args__ = (
1021 __table_args__ = (
1027 UniqueConstraint('user_id', 'ip_addr'),
1022 UniqueConstraint('user_id', 'ip_addr'),
1028 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1023 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1029 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1024 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1030 )
1025 )
1031 __mapper_args__ = {}
1026 __mapper_args__ = {}
1032
1027
1033 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1028 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1034 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1029 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1035 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1030 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1036 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1031 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1037 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1032 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1038 user = relationship('User', lazy='joined')
1033 user = relationship('User', lazy='joined')
1039
1034
1040 @classmethod
1035 @classmethod
1041 def _get_ip_range(cls, ip_addr):
1036 def _get_ip_range(cls, ip_addr):
1042 net = ipaddress.ip_network(ip_addr, strict=False)
1037 net = ipaddress.ip_network(ip_addr, strict=False)
1043 return [str(net.network_address), str(net.broadcast_address)]
1038 return [str(net.network_address), str(net.broadcast_address)]
1044
1039
1045 def __json__(self):
1040 def __json__(self):
1046 return {
1041 return {
1047 'ip_addr': self.ip_addr,
1042 'ip_addr': self.ip_addr,
1048 'ip_range': self._get_ip_range(self.ip_addr),
1043 'ip_range': self._get_ip_range(self.ip_addr),
1049 }
1044 }
1050
1045
1051 def __unicode__(self):
1046 def __unicode__(self):
1052 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1047 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1053 self.user_id, self.ip_addr)
1048 self.user_id, self.ip_addr)
1054
1049
1055 class UserLog(Base, BaseModel):
1050 class UserLog(Base, BaseModel):
1056 __tablename__ = 'user_logs'
1051 __tablename__ = 'user_logs'
1057 __table_args__ = (
1052 __table_args__ = (
1058 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1053 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1059 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1054 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1060 )
1055 )
1061 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1056 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1062 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1057 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1063 username = Column("username", String(255), nullable=True, unique=None, default=None)
1058 username = Column("username", String(255), nullable=True, unique=None, default=None)
1064 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
1059 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
1065 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1060 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1066 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1061 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1067 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1062 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1068 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1063 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1069
1064
1070 def __unicode__(self):
1065 def __unicode__(self):
1071 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1066 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1072 self.repository_name,
1067 self.repository_name,
1073 self.action)
1068 self.action)
1074
1069
1075 @property
1070 @property
1076 def action_as_day(self):
1071 def action_as_day(self):
1077 return datetime.date(*self.action_date.timetuple()[:3])
1072 return datetime.date(*self.action_date.timetuple()[:3])
1078
1073
1079 user = relationship('User')
1074 user = relationship('User')
1080 repository = relationship('Repository', cascade='')
1075 repository = relationship('Repository', cascade='')
1081
1076
1082
1077
1083 class UserGroup(Base, BaseModel):
1078 class UserGroup(Base, BaseModel):
1084 __tablename__ = 'users_groups'
1079 __tablename__ = 'users_groups'
1085 __table_args__ = (
1080 __table_args__ = (
1086 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1081 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1087 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1082 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1088 )
1083 )
1089
1084
1090 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1085 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1091 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1086 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1092 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1087 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1093 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1088 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1094 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1089 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1095 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1090 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1096 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1091 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1097 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1092 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1098
1093
1099 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1094 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1100 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1095 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1101 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1096 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1102 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1097 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1103 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1098 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1104 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1099 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1105
1100
1106 user = relationship('User')
1101 user = relationship('User')
1107
1102
1108 @hybrid_property
1103 @hybrid_property
1109 def group_data(self):
1104 def group_data(self):
1110 if not self._group_data:
1105 if not self._group_data:
1111 return {}
1106 return {}
1112
1107
1113 try:
1108 try:
1114 return json.loads(self._group_data)
1109 return json.loads(self._group_data)
1115 except TypeError:
1110 except TypeError:
1116 return {}
1111 return {}
1117
1112
1118 @group_data.setter
1113 @group_data.setter
1119 def group_data(self, val):
1114 def group_data(self, val):
1120 try:
1115 try:
1121 self._group_data = json.dumps(val)
1116 self._group_data = json.dumps(val)
1122 except Exception:
1117 except Exception:
1123 log.error(traceback.format_exc())
1118 log.error(traceback.format_exc())
1124
1119
1125 def __unicode__(self):
1120 def __unicode__(self):
1126 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1121 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1127 self.users_group_id,
1122 self.users_group_id,
1128 self.users_group_name)
1123 self.users_group_name)
1129
1124
1130 @classmethod
1125 @classmethod
1131 def get_by_group_name(cls, group_name, cache=False,
1126 def get_by_group_name(cls, group_name, cache=False,
1132 case_insensitive=False):
1127 case_insensitive=False):
1133 if case_insensitive:
1128 if case_insensitive:
1134 q = cls.query().filter(func.lower(cls.users_group_name) ==
1129 q = cls.query().filter(func.lower(cls.users_group_name) ==
1135 func.lower(group_name))
1130 func.lower(group_name))
1136
1131
1137 else:
1132 else:
1138 q = cls.query().filter(cls.users_group_name == group_name)
1133 q = cls.query().filter(cls.users_group_name == group_name)
1139 if cache:
1134 if cache:
1140 q = q.options(FromCache(
1135 q = q.options(FromCache(
1141 "sql_cache_short",
1136 "sql_cache_short",
1142 "get_group_%s" % _hash_key(group_name)))
1137 "get_group_%s" % _hash_key(group_name)))
1143 return q.scalar()
1138 return q.scalar()
1144
1139
1145 @classmethod
1140 @classmethod
1146 def get(cls, user_group_id, cache=False):
1141 def get(cls, user_group_id, cache=False):
1147 user_group = cls.query()
1142 user_group = cls.query()
1148 if cache:
1143 if cache:
1149 user_group = user_group.options(FromCache("sql_cache_short",
1144 user_group = user_group.options(FromCache("sql_cache_short",
1150 "get_users_group_%s" % user_group_id))
1145 "get_users_group_%s" % user_group_id))
1151 return user_group.get(user_group_id)
1146 return user_group.get(user_group_id)
1152
1147
1153 def permissions(self, with_admins=True, with_owner=True):
1148 def permissions(self, with_admins=True, with_owner=True):
1154 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1149 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1155 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1150 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1156 joinedload(UserUserGroupToPerm.user),
1151 joinedload(UserUserGroupToPerm.user),
1157 joinedload(UserUserGroupToPerm.permission),)
1152 joinedload(UserUserGroupToPerm.permission),)
1158
1153
1159 # get owners and admins and permissions. We do a trick of re-writing
1154 # get owners and admins and permissions. We do a trick of re-writing
1160 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1155 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1161 # has a global reference and changing one object propagates to all
1156 # has a global reference and changing one object propagates to all
1162 # others. This means if admin is also an owner admin_row that change
1157 # others. This means if admin is also an owner admin_row that change
1163 # would propagate to both objects
1158 # would propagate to both objects
1164 perm_rows = []
1159 perm_rows = []
1165 for _usr in q.all():
1160 for _usr in q.all():
1166 usr = AttributeDict(_usr.user.get_dict())
1161 usr = AttributeDict(_usr.user.get_dict())
1167 usr.permission = _usr.permission.permission_name
1162 usr.permission = _usr.permission.permission_name
1168 perm_rows.append(usr)
1163 perm_rows.append(usr)
1169
1164
1170 # filter the perm rows by 'default' first and then sort them by
1165 # filter the perm rows by 'default' first and then sort them by
1171 # admin,write,read,none permissions sorted again alphabetically in
1166 # admin,write,read,none permissions sorted again alphabetically in
1172 # each group
1167 # each group
1173 perm_rows = sorted(perm_rows, key=display_sort)
1168 perm_rows = sorted(perm_rows, key=display_sort)
1174
1169
1175 _admin_perm = 'usergroup.admin'
1170 _admin_perm = 'usergroup.admin'
1176 owner_row = []
1171 owner_row = []
1177 if with_owner:
1172 if with_owner:
1178 usr = AttributeDict(self.user.get_dict())
1173 usr = AttributeDict(self.user.get_dict())
1179 usr.owner_row = True
1174 usr.owner_row = True
1180 usr.permission = _admin_perm
1175 usr.permission = _admin_perm
1181 owner_row.append(usr)
1176 owner_row.append(usr)
1182
1177
1183 super_admin_rows = []
1178 super_admin_rows = []
1184 if with_admins:
1179 if with_admins:
1185 for usr in User.get_all_super_admins():
1180 for usr in User.get_all_super_admins():
1186 # if this admin is also owner, don't double the record
1181 # if this admin is also owner, don't double the record
1187 if usr.user_id == owner_row[0].user_id:
1182 if usr.user_id == owner_row[0].user_id:
1188 owner_row[0].admin_row = True
1183 owner_row[0].admin_row = True
1189 else:
1184 else:
1190 usr = AttributeDict(usr.get_dict())
1185 usr = AttributeDict(usr.get_dict())
1191 usr.admin_row = True
1186 usr.admin_row = True
1192 usr.permission = _admin_perm
1187 usr.permission = _admin_perm
1193 super_admin_rows.append(usr)
1188 super_admin_rows.append(usr)
1194
1189
1195 return super_admin_rows + owner_row + perm_rows
1190 return super_admin_rows + owner_row + perm_rows
1196
1191
1197 def permission_user_groups(self):
1192 def permission_user_groups(self):
1198 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1193 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1199 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1194 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1200 joinedload(UserGroupUserGroupToPerm.target_user_group),
1195 joinedload(UserGroupUserGroupToPerm.target_user_group),
1201 joinedload(UserGroupUserGroupToPerm.permission),)
1196 joinedload(UserGroupUserGroupToPerm.permission),)
1202
1197
1203 perm_rows = []
1198 perm_rows = []
1204 for _user_group in q.all():
1199 for _user_group in q.all():
1205 usr = AttributeDict(_user_group.user_group.get_dict())
1200 usr = AttributeDict(_user_group.user_group.get_dict())
1206 usr.permission = _user_group.permission.permission_name
1201 usr.permission = _user_group.permission.permission_name
1207 perm_rows.append(usr)
1202 perm_rows.append(usr)
1208
1203
1209 return perm_rows
1204 return perm_rows
1210
1205
1211 def _get_default_perms(self, user_group, suffix=''):
1206 def _get_default_perms(self, user_group, suffix=''):
1212 from rhodecode.model.permission import PermissionModel
1207 from rhodecode.model.permission import PermissionModel
1213 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1208 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1214
1209
1215 def get_default_perms(self, suffix=''):
1210 def get_default_perms(self, suffix=''):
1216 return self._get_default_perms(self, suffix)
1211 return self._get_default_perms(self, suffix)
1217
1212
1218 def get_api_data(self, with_group_members=True, include_secrets=False):
1213 def get_api_data(self, with_group_members=True, include_secrets=False):
1219 """
1214 """
1220 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1215 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1221 basically forwarded.
1216 basically forwarded.
1222
1217
1223 """
1218 """
1224 user_group = self
1219 user_group = self
1225
1220
1226 data = {
1221 data = {
1227 'users_group_id': user_group.users_group_id,
1222 'users_group_id': user_group.users_group_id,
1228 'group_name': user_group.users_group_name,
1223 'group_name': user_group.users_group_name,
1229 'group_description': user_group.user_group_description,
1224 'group_description': user_group.user_group_description,
1230 'active': user_group.users_group_active,
1225 'active': user_group.users_group_active,
1231 'owner': user_group.user.username,
1226 'owner': user_group.user.username,
1232 }
1227 }
1233 if with_group_members:
1228 if with_group_members:
1234 users = []
1229 users = []
1235 for user in user_group.members:
1230 for user in user_group.members:
1236 user = user.user
1231 user = user.user
1237 users.append(user.get_api_data(include_secrets=include_secrets))
1232 users.append(user.get_api_data(include_secrets=include_secrets))
1238 data['users'] = users
1233 data['users'] = users
1239
1234
1240 return data
1235 return data
1241
1236
1242
1237
1243 class UserGroupMember(Base, BaseModel):
1238 class UserGroupMember(Base, BaseModel):
1244 __tablename__ = 'users_groups_members'
1239 __tablename__ = 'users_groups_members'
1245 __table_args__ = (
1240 __table_args__ = (
1246 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1241 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1247 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1242 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1248 )
1243 )
1249
1244
1250 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1245 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1251 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1246 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1252 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1247 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1253
1248
1254 user = relationship('User', lazy='joined')
1249 user = relationship('User', lazy='joined')
1255 users_group = relationship('UserGroup')
1250 users_group = relationship('UserGroup')
1256
1251
1257 def __init__(self, gr_id='', u_id=''):
1252 def __init__(self, gr_id='', u_id=''):
1258 self.users_group_id = gr_id
1253 self.users_group_id = gr_id
1259 self.user_id = u_id
1254 self.user_id = u_id
1260
1255
1261
1256
1262 class RepositoryField(Base, BaseModel):
1257 class RepositoryField(Base, BaseModel):
1263 __tablename__ = 'repositories_fields'
1258 __tablename__ = 'repositories_fields'
1264 __table_args__ = (
1259 __table_args__ = (
1265 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1260 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1266 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1261 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1267 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1262 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1268 )
1263 )
1269 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1264 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1270
1265
1271 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1266 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1272 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1267 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1273 field_key = Column("field_key", String(250))
1268 field_key = Column("field_key", String(250))
1274 field_label = Column("field_label", String(1024), nullable=False)
1269 field_label = Column("field_label", String(1024), nullable=False)
1275 field_value = Column("field_value", String(10000), nullable=False)
1270 field_value = Column("field_value", String(10000), nullable=False)
1276 field_desc = Column("field_desc", String(1024), nullable=False)
1271 field_desc = Column("field_desc", String(1024), nullable=False)
1277 field_type = Column("field_type", String(255), nullable=False, unique=None)
1272 field_type = Column("field_type", String(255), nullable=False, unique=None)
1278 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1273 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1279
1274
1280 repository = relationship('Repository')
1275 repository = relationship('Repository')
1281
1276
1282 @property
1277 @property
1283 def field_key_prefixed(self):
1278 def field_key_prefixed(self):
1284 return 'ex_%s' % self.field_key
1279 return 'ex_%s' % self.field_key
1285
1280
1286 @classmethod
1281 @classmethod
1287 def un_prefix_key(cls, key):
1282 def un_prefix_key(cls, key):
1288 if key.startswith(cls.PREFIX):
1283 if key.startswith(cls.PREFIX):
1289 return key[len(cls.PREFIX):]
1284 return key[len(cls.PREFIX):]
1290 return key
1285 return key
1291
1286
1292 @classmethod
1287 @classmethod
1293 def get_by_key_name(cls, key, repo):
1288 def get_by_key_name(cls, key, repo):
1294 row = cls.query()\
1289 row = cls.query()\
1295 .filter(cls.repository == repo)\
1290 .filter(cls.repository == repo)\
1296 .filter(cls.field_key == key).scalar()
1291 .filter(cls.field_key == key).scalar()
1297 return row
1292 return row
1298
1293
1299
1294
1300 class Repository(Base, BaseModel):
1295 class Repository(Base, BaseModel):
1301 __tablename__ = 'repositories'
1296 __tablename__ = 'repositories'
1302 __table_args__ = (
1297 __table_args__ = (
1303 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1298 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1304 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1299 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1305 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1300 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1306 )
1301 )
1307 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1302 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1308 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1303 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1309
1304
1310 STATE_CREATED = 'repo_state_created'
1305 STATE_CREATED = 'repo_state_created'
1311 STATE_PENDING = 'repo_state_pending'
1306 STATE_PENDING = 'repo_state_pending'
1312 STATE_ERROR = 'repo_state_error'
1307 STATE_ERROR = 'repo_state_error'
1313
1308
1314 LOCK_AUTOMATIC = 'lock_auto'
1309 LOCK_AUTOMATIC = 'lock_auto'
1315 LOCK_API = 'lock_api'
1310 LOCK_API = 'lock_api'
1316 LOCK_WEB = 'lock_web'
1311 LOCK_WEB = 'lock_web'
1317 LOCK_PULL = 'lock_pull'
1312 LOCK_PULL = 'lock_pull'
1318
1313
1319 NAME_SEP = URL_SEP
1314 NAME_SEP = URL_SEP
1320
1315
1321 repo_id = Column(
1316 repo_id = Column(
1322 "repo_id", Integer(), nullable=False, unique=True, default=None,
1317 "repo_id", Integer(), nullable=False, unique=True, default=None,
1323 primary_key=True)
1318 primary_key=True)
1324 _repo_name = Column(
1319 _repo_name = Column(
1325 "repo_name", Text(), nullable=False, default=None)
1320 "repo_name", Text(), nullable=False, default=None)
1326 _repo_name_hash = Column(
1321 _repo_name_hash = Column(
1327 "repo_name_hash", String(255), nullable=False, unique=True)
1322 "repo_name_hash", String(255), nullable=False, unique=True)
1328 repo_state = Column("repo_state", String(255), nullable=True)
1323 repo_state = Column("repo_state", String(255), nullable=True)
1329
1324
1330 clone_uri = Column(
1325 clone_uri = Column(
1331 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1326 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1332 default=None)
1327 default=None)
1333 repo_type = Column(
1328 repo_type = Column(
1334 "repo_type", String(255), nullable=False, unique=False, default=None)
1329 "repo_type", String(255), nullable=False, unique=False, default=None)
1335 user_id = Column(
1330 user_id = Column(
1336 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1331 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1337 unique=False, default=None)
1332 unique=False, default=None)
1338 private = Column(
1333 private = Column(
1339 "private", Boolean(), nullable=True, unique=None, default=None)
1334 "private", Boolean(), nullable=True, unique=None, default=None)
1340 enable_statistics = Column(
1335 enable_statistics = Column(
1341 "statistics", Boolean(), nullable=True, unique=None, default=True)
1336 "statistics", Boolean(), nullable=True, unique=None, default=True)
1342 enable_downloads = Column(
1337 enable_downloads = Column(
1343 "downloads", Boolean(), nullable=True, unique=None, default=True)
1338 "downloads", Boolean(), nullable=True, unique=None, default=True)
1344 description = Column(
1339 description = Column(
1345 "description", String(10000), nullable=True, unique=None, default=None)
1340 "description", String(10000), nullable=True, unique=None, default=None)
1346 created_on = Column(
1341 created_on = Column(
1347 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1342 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1348 default=datetime.datetime.now)
1343 default=datetime.datetime.now)
1349 updated_on = Column(
1344 updated_on = Column(
1350 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1345 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1351 default=datetime.datetime.now)
1346 default=datetime.datetime.now)
1352 _landing_revision = Column(
1347 _landing_revision = Column(
1353 "landing_revision", String(255), nullable=False, unique=False,
1348 "landing_revision", String(255), nullable=False, unique=False,
1354 default=None)
1349 default=None)
1355 enable_locking = Column(
1350 enable_locking = Column(
1356 "enable_locking", Boolean(), nullable=False, unique=None,
1351 "enable_locking", Boolean(), nullable=False, unique=None,
1357 default=False)
1352 default=False)
1358 _locked = Column(
1353 _locked = Column(
1359 "locked", String(255), nullable=True, unique=False, default=None)
1354 "locked", String(255), nullable=True, unique=False, default=None)
1360 _changeset_cache = Column(
1355 _changeset_cache = Column(
1361 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1356 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1362
1357
1363 fork_id = Column(
1358 fork_id = Column(
1364 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1359 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1365 nullable=True, unique=False, default=None)
1360 nullable=True, unique=False, default=None)
1366 group_id = Column(
1361 group_id = Column(
1367 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1362 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1368 unique=False, default=None)
1363 unique=False, default=None)
1369
1364
1370 user = relationship('User', lazy='joined')
1365 user = relationship('User', lazy='joined')
1371 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1366 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1372 group = relationship('RepoGroup', lazy='joined')
1367 group = relationship('RepoGroup', lazy='joined')
1373 repo_to_perm = relationship(
1368 repo_to_perm = relationship(
1374 'UserRepoToPerm', cascade='all',
1369 'UserRepoToPerm', cascade='all',
1375 order_by='UserRepoToPerm.repo_to_perm_id')
1370 order_by='UserRepoToPerm.repo_to_perm_id')
1376 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1371 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1377 stats = relationship('Statistics', cascade='all', uselist=False)
1372 stats = relationship('Statistics', cascade='all', uselist=False)
1378
1373
1379 followers = relationship(
1374 followers = relationship(
1380 'UserFollowing',
1375 'UserFollowing',
1381 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1376 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1382 cascade='all')
1377 cascade='all')
1383 extra_fields = relationship(
1378 extra_fields = relationship(
1384 'RepositoryField', cascade="all, delete, delete-orphan")
1379 'RepositoryField', cascade="all, delete, delete-orphan")
1385 logs = relationship('UserLog')
1380 logs = relationship('UserLog')
1386 comments = relationship(
1381 comments = relationship(
1387 'ChangesetComment', cascade="all, delete, delete-orphan")
1382 'ChangesetComment', cascade="all, delete, delete-orphan")
1388 pull_requests_source = relationship(
1383 pull_requests_source = relationship(
1389 'PullRequest',
1384 'PullRequest',
1390 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1385 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1391 cascade="all, delete, delete-orphan")
1386 cascade="all, delete, delete-orphan")
1392 pull_requests_target = relationship(
1387 pull_requests_target = relationship(
1393 'PullRequest',
1388 'PullRequest',
1394 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1389 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1395 cascade="all, delete, delete-orphan")
1390 cascade="all, delete, delete-orphan")
1396 ui = relationship('RepoRhodeCodeUi', cascade="all")
1391 ui = relationship('RepoRhodeCodeUi', cascade="all")
1397 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1392 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1398 integrations = relationship('Integration',
1393 integrations = relationship('Integration',
1399 cascade="all, delete, delete-orphan")
1394 cascade="all, delete, delete-orphan")
1400
1395
1401 def __unicode__(self):
1396 def __unicode__(self):
1402 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1397 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1403 safe_unicode(self.repo_name))
1398 safe_unicode(self.repo_name))
1404
1399
1405 @hybrid_property
1400 @hybrid_property
1406 def landing_rev(self):
1401 def landing_rev(self):
1407 # always should return [rev_type, rev]
1402 # always should return [rev_type, rev]
1408 if self._landing_revision:
1403 if self._landing_revision:
1409 _rev_info = self._landing_revision.split(':')
1404 _rev_info = self._landing_revision.split(':')
1410 if len(_rev_info) < 2:
1405 if len(_rev_info) < 2:
1411 _rev_info.insert(0, 'rev')
1406 _rev_info.insert(0, 'rev')
1412 return [_rev_info[0], _rev_info[1]]
1407 return [_rev_info[0], _rev_info[1]]
1413 return [None, None]
1408 return [None, None]
1414
1409
1415 @landing_rev.setter
1410 @landing_rev.setter
1416 def landing_rev(self, val):
1411 def landing_rev(self, val):
1417 if ':' not in val:
1412 if ':' not in val:
1418 raise ValueError('value must be delimited with `:` and consist '
1413 raise ValueError('value must be delimited with `:` and consist '
1419 'of <rev_type>:<rev>, got %s instead' % val)
1414 'of <rev_type>:<rev>, got %s instead' % val)
1420 self._landing_revision = val
1415 self._landing_revision = val
1421
1416
1422 @hybrid_property
1417 @hybrid_property
1423 def locked(self):
1418 def locked(self):
1424 if self._locked:
1419 if self._locked:
1425 user_id, timelocked, reason = self._locked.split(':')
1420 user_id, timelocked, reason = self._locked.split(':')
1426 lock_values = int(user_id), timelocked, reason
1421 lock_values = int(user_id), timelocked, reason
1427 else:
1422 else:
1428 lock_values = [None, None, None]
1423 lock_values = [None, None, None]
1429 return lock_values
1424 return lock_values
1430
1425
1431 @locked.setter
1426 @locked.setter
1432 def locked(self, val):
1427 def locked(self, val):
1433 if val and isinstance(val, (list, tuple)):
1428 if val and isinstance(val, (list, tuple)):
1434 self._locked = ':'.join(map(str, val))
1429 self._locked = ':'.join(map(str, val))
1435 else:
1430 else:
1436 self._locked = None
1431 self._locked = None
1437
1432
1438 @hybrid_property
1433 @hybrid_property
1439 def changeset_cache(self):
1434 def changeset_cache(self):
1440 from rhodecode.lib.vcs.backends.base import EmptyCommit
1435 from rhodecode.lib.vcs.backends.base import EmptyCommit
1441 dummy = EmptyCommit().__json__()
1436 dummy = EmptyCommit().__json__()
1442 if not self._changeset_cache:
1437 if not self._changeset_cache:
1443 return dummy
1438 return dummy
1444 try:
1439 try:
1445 return json.loads(self._changeset_cache)
1440 return json.loads(self._changeset_cache)
1446 except TypeError:
1441 except TypeError:
1447 return dummy
1442 return dummy
1448 except Exception:
1443 except Exception:
1449 log.error(traceback.format_exc())
1444 log.error(traceback.format_exc())
1450 return dummy
1445 return dummy
1451
1446
1452 @changeset_cache.setter
1447 @changeset_cache.setter
1453 def changeset_cache(self, val):
1448 def changeset_cache(self, val):
1454 try:
1449 try:
1455 self._changeset_cache = json.dumps(val)
1450 self._changeset_cache = json.dumps(val)
1456 except Exception:
1451 except Exception:
1457 log.error(traceback.format_exc())
1452 log.error(traceback.format_exc())
1458
1453
1459 @hybrid_property
1454 @hybrid_property
1460 def repo_name(self):
1455 def repo_name(self):
1461 return self._repo_name
1456 return self._repo_name
1462
1457
1463 @repo_name.setter
1458 @repo_name.setter
1464 def repo_name(self, value):
1459 def repo_name(self, value):
1465 self._repo_name = value
1460 self._repo_name = value
1466 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1461 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1467
1462
1468 @classmethod
1463 @classmethod
1469 def normalize_repo_name(cls, repo_name):
1464 def normalize_repo_name(cls, repo_name):
1470 """
1465 """
1471 Normalizes os specific repo_name to the format internally stored inside
1466 Normalizes os specific repo_name to the format internally stored inside
1472 database using URL_SEP
1467 database using URL_SEP
1473
1468
1474 :param cls:
1469 :param cls:
1475 :param repo_name:
1470 :param repo_name:
1476 """
1471 """
1477 return cls.NAME_SEP.join(repo_name.split(os.sep))
1472 return cls.NAME_SEP.join(repo_name.split(os.sep))
1478
1473
1479 @classmethod
1474 @classmethod
1480 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1475 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1481 session = Session()
1476 session = Session()
1482 q = session.query(cls).filter(cls.repo_name == repo_name)
1477 q = session.query(cls).filter(cls.repo_name == repo_name)
1483
1478
1484 if cache:
1479 if cache:
1485 if identity_cache:
1480 if identity_cache:
1486 val = cls.identity_cache(session, 'repo_name', repo_name)
1481 val = cls.identity_cache(session, 'repo_name', repo_name)
1487 if val:
1482 if val:
1488 return val
1483 return val
1489 else:
1484 else:
1490 q = q.options(
1485 q = q.options(
1491 FromCache("sql_cache_short",
1486 FromCache("sql_cache_short",
1492 "get_repo_by_name_%s" % _hash_key(repo_name)))
1487 "get_repo_by_name_%s" % _hash_key(repo_name)))
1493
1488
1494 return q.scalar()
1489 return q.scalar()
1495
1490
1496 @classmethod
1491 @classmethod
1497 def get_by_full_path(cls, repo_full_path):
1492 def get_by_full_path(cls, repo_full_path):
1498 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1493 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1499 repo_name = cls.normalize_repo_name(repo_name)
1494 repo_name = cls.normalize_repo_name(repo_name)
1500 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1495 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1501
1496
1502 @classmethod
1497 @classmethod
1503 def get_repo_forks(cls, repo_id):
1498 def get_repo_forks(cls, repo_id):
1504 return cls.query().filter(Repository.fork_id == repo_id)
1499 return cls.query().filter(Repository.fork_id == repo_id)
1505
1500
1506 @classmethod
1501 @classmethod
1507 def base_path(cls):
1502 def base_path(cls):
1508 """
1503 """
1509 Returns base path when all repos are stored
1504 Returns base path when all repos are stored
1510
1505
1511 :param cls:
1506 :param cls:
1512 """
1507 """
1513 q = Session().query(RhodeCodeUi)\
1508 q = Session().query(RhodeCodeUi)\
1514 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1509 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1515 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1510 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1516 return q.one().ui_value
1511 return q.one().ui_value
1517
1512
1518 @classmethod
1513 @classmethod
1519 def is_valid(cls, repo_name):
1514 def is_valid(cls, repo_name):
1520 """
1515 """
1521 returns True if given repo name is a valid filesystem repository
1516 returns True if given repo name is a valid filesystem repository
1522
1517
1523 :param cls:
1518 :param cls:
1524 :param repo_name:
1519 :param repo_name:
1525 """
1520 """
1526 from rhodecode.lib.utils import is_valid_repo
1521 from rhodecode.lib.utils import is_valid_repo
1527
1522
1528 return is_valid_repo(repo_name, cls.base_path())
1523 return is_valid_repo(repo_name, cls.base_path())
1529
1524
1530 @classmethod
1525 @classmethod
1531 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1526 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1532 case_insensitive=True):
1527 case_insensitive=True):
1533 q = Repository.query()
1528 q = Repository.query()
1534
1529
1535 if not isinstance(user_id, Optional):
1530 if not isinstance(user_id, Optional):
1536 q = q.filter(Repository.user_id == user_id)
1531 q = q.filter(Repository.user_id == user_id)
1537
1532
1538 if not isinstance(group_id, Optional):
1533 if not isinstance(group_id, Optional):
1539 q = q.filter(Repository.group_id == group_id)
1534 q = q.filter(Repository.group_id == group_id)
1540
1535
1541 if case_insensitive:
1536 if case_insensitive:
1542 q = q.order_by(func.lower(Repository.repo_name))
1537 q = q.order_by(func.lower(Repository.repo_name))
1543 else:
1538 else:
1544 q = q.order_by(Repository.repo_name)
1539 q = q.order_by(Repository.repo_name)
1545 return q.all()
1540 return q.all()
1546
1541
1547 @property
1542 @property
1548 def forks(self):
1543 def forks(self):
1549 """
1544 """
1550 Return forks of this repo
1545 Return forks of this repo
1551 """
1546 """
1552 return Repository.get_repo_forks(self.repo_id)
1547 return Repository.get_repo_forks(self.repo_id)
1553
1548
1554 @property
1549 @property
1555 def parent(self):
1550 def parent(self):
1556 """
1551 """
1557 Returns fork parent
1552 Returns fork parent
1558 """
1553 """
1559 return self.fork
1554 return self.fork
1560
1555
1561 @property
1556 @property
1562 def just_name(self):
1557 def just_name(self):
1563 return self.repo_name.split(self.NAME_SEP)[-1]
1558 return self.repo_name.split(self.NAME_SEP)[-1]
1564
1559
1565 @property
1560 @property
1566 def groups_with_parents(self):
1561 def groups_with_parents(self):
1567 groups = []
1562 groups = []
1568 if self.group is None:
1563 if self.group is None:
1569 return groups
1564 return groups
1570
1565
1571 cur_gr = self.group
1566 cur_gr = self.group
1572 groups.insert(0, cur_gr)
1567 groups.insert(0, cur_gr)
1573 while 1:
1568 while 1:
1574 gr = getattr(cur_gr, 'parent_group', None)
1569 gr = getattr(cur_gr, 'parent_group', None)
1575 cur_gr = cur_gr.parent_group
1570 cur_gr = cur_gr.parent_group
1576 if gr is None:
1571 if gr is None:
1577 break
1572 break
1578 groups.insert(0, gr)
1573 groups.insert(0, gr)
1579
1574
1580 return groups
1575 return groups
1581
1576
1582 @property
1577 @property
1583 def groups_and_repo(self):
1578 def groups_and_repo(self):
1584 return self.groups_with_parents, self
1579 return self.groups_with_parents, self
1585
1580
1586 @LazyProperty
1581 @LazyProperty
1587 def repo_path(self):
1582 def repo_path(self):
1588 """
1583 """
1589 Returns base full path for that repository means where it actually
1584 Returns base full path for that repository means where it actually
1590 exists on a filesystem
1585 exists on a filesystem
1591 """
1586 """
1592 q = Session().query(RhodeCodeUi).filter(
1587 q = Session().query(RhodeCodeUi).filter(
1593 RhodeCodeUi.ui_key == self.NAME_SEP)
1588 RhodeCodeUi.ui_key == self.NAME_SEP)
1594 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1589 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1595 return q.one().ui_value
1590 return q.one().ui_value
1596
1591
1597 @property
1592 @property
1598 def repo_full_path(self):
1593 def repo_full_path(self):
1599 p = [self.repo_path]
1594 p = [self.repo_path]
1600 # we need to split the name by / since this is how we store the
1595 # we need to split the name by / since this is how we store the
1601 # names in the database, but that eventually needs to be converted
1596 # names in the database, but that eventually needs to be converted
1602 # into a valid system path
1597 # into a valid system path
1603 p += self.repo_name.split(self.NAME_SEP)
1598 p += self.repo_name.split(self.NAME_SEP)
1604 return os.path.join(*map(safe_unicode, p))
1599 return os.path.join(*map(safe_unicode, p))
1605
1600
1606 @property
1601 @property
1607 def cache_keys(self):
1602 def cache_keys(self):
1608 """
1603 """
1609 Returns associated cache keys for that repo
1604 Returns associated cache keys for that repo
1610 """
1605 """
1611 return CacheKey.query()\
1606 return CacheKey.query()\
1612 .filter(CacheKey.cache_args == self.repo_name)\
1607 .filter(CacheKey.cache_args == self.repo_name)\
1613 .order_by(CacheKey.cache_key)\
1608 .order_by(CacheKey.cache_key)\
1614 .all()
1609 .all()
1615
1610
1616 def get_new_name(self, repo_name):
1611 def get_new_name(self, repo_name):
1617 """
1612 """
1618 returns new full repository name based on assigned group and new new
1613 returns new full repository name based on assigned group and new new
1619
1614
1620 :param group_name:
1615 :param group_name:
1621 """
1616 """
1622 path_prefix = self.group.full_path_splitted if self.group else []
1617 path_prefix = self.group.full_path_splitted if self.group else []
1623 return self.NAME_SEP.join(path_prefix + [repo_name])
1618 return self.NAME_SEP.join(path_prefix + [repo_name])
1624
1619
1625 @property
1620 @property
1626 def _config(self):
1621 def _config(self):
1627 """
1622 """
1628 Returns db based config object.
1623 Returns db based config object.
1629 """
1624 """
1630 from rhodecode.lib.utils import make_db_config
1625 from rhodecode.lib.utils import make_db_config
1631 return make_db_config(clear_session=False, repo=self)
1626 return make_db_config(clear_session=False, repo=self)
1632
1627
1633 def permissions(self, with_admins=True, with_owner=True):
1628 def permissions(self, with_admins=True, with_owner=True):
1634 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1629 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1635 q = q.options(joinedload(UserRepoToPerm.repository),
1630 q = q.options(joinedload(UserRepoToPerm.repository),
1636 joinedload(UserRepoToPerm.user),
1631 joinedload(UserRepoToPerm.user),
1637 joinedload(UserRepoToPerm.permission),)
1632 joinedload(UserRepoToPerm.permission),)
1638
1633
1639 # get owners and admins and permissions. We do a trick of re-writing
1634 # get owners and admins and permissions. We do a trick of re-writing
1640 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1635 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1641 # has a global reference and changing one object propagates to all
1636 # has a global reference and changing one object propagates to all
1642 # others. This means if admin is also an owner admin_row that change
1637 # others. This means if admin is also an owner admin_row that change
1643 # would propagate to both objects
1638 # would propagate to both objects
1644 perm_rows = []
1639 perm_rows = []
1645 for _usr in q.all():
1640 for _usr in q.all():
1646 usr = AttributeDict(_usr.user.get_dict())
1641 usr = AttributeDict(_usr.user.get_dict())
1647 usr.permission = _usr.permission.permission_name
1642 usr.permission = _usr.permission.permission_name
1648 perm_rows.append(usr)
1643 perm_rows.append(usr)
1649
1644
1650 # filter the perm rows by 'default' first and then sort them by
1645 # filter the perm rows by 'default' first and then sort them by
1651 # admin,write,read,none permissions sorted again alphabetically in
1646 # admin,write,read,none permissions sorted again alphabetically in
1652 # each group
1647 # each group
1653 perm_rows = sorted(perm_rows, key=display_sort)
1648 perm_rows = sorted(perm_rows, key=display_sort)
1654
1649
1655 _admin_perm = 'repository.admin'
1650 _admin_perm = 'repository.admin'
1656 owner_row = []
1651 owner_row = []
1657 if with_owner:
1652 if with_owner:
1658 usr = AttributeDict(self.user.get_dict())
1653 usr = AttributeDict(self.user.get_dict())
1659 usr.owner_row = True
1654 usr.owner_row = True
1660 usr.permission = _admin_perm
1655 usr.permission = _admin_perm
1661 owner_row.append(usr)
1656 owner_row.append(usr)
1662
1657
1663 super_admin_rows = []
1658 super_admin_rows = []
1664 if with_admins:
1659 if with_admins:
1665 for usr in User.get_all_super_admins():
1660 for usr in User.get_all_super_admins():
1666 # if this admin is also owner, don't double the record
1661 # if this admin is also owner, don't double the record
1667 if usr.user_id == owner_row[0].user_id:
1662 if usr.user_id == owner_row[0].user_id:
1668 owner_row[0].admin_row = True
1663 owner_row[0].admin_row = True
1669 else:
1664 else:
1670 usr = AttributeDict(usr.get_dict())
1665 usr = AttributeDict(usr.get_dict())
1671 usr.admin_row = True
1666 usr.admin_row = True
1672 usr.permission = _admin_perm
1667 usr.permission = _admin_perm
1673 super_admin_rows.append(usr)
1668 super_admin_rows.append(usr)
1674
1669
1675 return super_admin_rows + owner_row + perm_rows
1670 return super_admin_rows + owner_row + perm_rows
1676
1671
1677 def permission_user_groups(self):
1672 def permission_user_groups(self):
1678 q = UserGroupRepoToPerm.query().filter(
1673 q = UserGroupRepoToPerm.query().filter(
1679 UserGroupRepoToPerm.repository == self)
1674 UserGroupRepoToPerm.repository == self)
1680 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1675 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1681 joinedload(UserGroupRepoToPerm.users_group),
1676 joinedload(UserGroupRepoToPerm.users_group),
1682 joinedload(UserGroupRepoToPerm.permission),)
1677 joinedload(UserGroupRepoToPerm.permission),)
1683
1678
1684 perm_rows = []
1679 perm_rows = []
1685 for _user_group in q.all():
1680 for _user_group in q.all():
1686 usr = AttributeDict(_user_group.users_group.get_dict())
1681 usr = AttributeDict(_user_group.users_group.get_dict())
1687 usr.permission = _user_group.permission.permission_name
1682 usr.permission = _user_group.permission.permission_name
1688 perm_rows.append(usr)
1683 perm_rows.append(usr)
1689
1684
1690 return perm_rows
1685 return perm_rows
1691
1686
1692 def get_api_data(self, include_secrets=False):
1687 def get_api_data(self, include_secrets=False):
1693 """
1688 """
1694 Common function for generating repo api data
1689 Common function for generating repo api data
1695
1690
1696 :param include_secrets: See :meth:`User.get_api_data`.
1691 :param include_secrets: See :meth:`User.get_api_data`.
1697
1692
1698 """
1693 """
1699 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1694 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1700 # move this methods on models level.
1695 # move this methods on models level.
1701 from rhodecode.model.settings import SettingsModel
1696 from rhodecode.model.settings import SettingsModel
1702
1697
1703 repo = self
1698 repo = self
1704 _user_id, _time, _reason = self.locked
1699 _user_id, _time, _reason = self.locked
1705
1700
1706 data = {
1701 data = {
1707 'repo_id': repo.repo_id,
1702 'repo_id': repo.repo_id,
1708 'repo_name': repo.repo_name,
1703 'repo_name': repo.repo_name,
1709 'repo_type': repo.repo_type,
1704 'repo_type': repo.repo_type,
1710 'clone_uri': repo.clone_uri or '',
1705 'clone_uri': repo.clone_uri or '',
1711 'url': url('summary_home', repo_name=self.repo_name, qualified=True),
1706 'url': url('summary_home', repo_name=self.repo_name, qualified=True),
1712 'private': repo.private,
1707 'private': repo.private,
1713 'created_on': repo.created_on,
1708 'created_on': repo.created_on,
1714 'description': repo.description,
1709 'description': repo.description,
1715 'landing_rev': repo.landing_rev,
1710 'landing_rev': repo.landing_rev,
1716 'owner': repo.user.username,
1711 'owner': repo.user.username,
1717 'fork_of': repo.fork.repo_name if repo.fork else None,
1712 'fork_of': repo.fork.repo_name if repo.fork else None,
1718 'enable_statistics': repo.enable_statistics,
1713 'enable_statistics': repo.enable_statistics,
1719 'enable_locking': repo.enable_locking,
1714 'enable_locking': repo.enable_locking,
1720 'enable_downloads': repo.enable_downloads,
1715 'enable_downloads': repo.enable_downloads,
1721 'last_changeset': repo.changeset_cache,
1716 'last_changeset': repo.changeset_cache,
1722 'locked_by': User.get(_user_id).get_api_data(
1717 'locked_by': User.get(_user_id).get_api_data(
1723 include_secrets=include_secrets) if _user_id else None,
1718 include_secrets=include_secrets) if _user_id else None,
1724 'locked_date': time_to_datetime(_time) if _time else None,
1719 'locked_date': time_to_datetime(_time) if _time else None,
1725 'lock_reason': _reason if _reason else None,
1720 'lock_reason': _reason if _reason else None,
1726 }
1721 }
1727
1722
1728 # TODO: mikhail: should be per-repo settings here
1723 # TODO: mikhail: should be per-repo settings here
1729 rc_config = SettingsModel().get_all_settings()
1724 rc_config = SettingsModel().get_all_settings()
1730 repository_fields = str2bool(
1725 repository_fields = str2bool(
1731 rc_config.get('rhodecode_repository_fields'))
1726 rc_config.get('rhodecode_repository_fields'))
1732 if repository_fields:
1727 if repository_fields:
1733 for f in self.extra_fields:
1728 for f in self.extra_fields:
1734 data[f.field_key_prefixed] = f.field_value
1729 data[f.field_key_prefixed] = f.field_value
1735
1730
1736 return data
1731 return data
1737
1732
1738 @classmethod
1733 @classmethod
1739 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1734 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1740 if not lock_time:
1735 if not lock_time:
1741 lock_time = time.time()
1736 lock_time = time.time()
1742 if not lock_reason:
1737 if not lock_reason:
1743 lock_reason = cls.LOCK_AUTOMATIC
1738 lock_reason = cls.LOCK_AUTOMATIC
1744 repo.locked = [user_id, lock_time, lock_reason]
1739 repo.locked = [user_id, lock_time, lock_reason]
1745 Session().add(repo)
1740 Session().add(repo)
1746 Session().commit()
1741 Session().commit()
1747
1742
1748 @classmethod
1743 @classmethod
1749 def unlock(cls, repo):
1744 def unlock(cls, repo):
1750 repo.locked = None
1745 repo.locked = None
1751 Session().add(repo)
1746 Session().add(repo)
1752 Session().commit()
1747 Session().commit()
1753
1748
1754 @classmethod
1749 @classmethod
1755 def getlock(cls, repo):
1750 def getlock(cls, repo):
1756 return repo.locked
1751 return repo.locked
1757
1752
1758 def is_user_lock(self, user_id):
1753 def is_user_lock(self, user_id):
1759 if self.lock[0]:
1754 if self.lock[0]:
1760 lock_user_id = safe_int(self.lock[0])
1755 lock_user_id = safe_int(self.lock[0])
1761 user_id = safe_int(user_id)
1756 user_id = safe_int(user_id)
1762 # both are ints, and they are equal
1757 # both are ints, and they are equal
1763 return all([lock_user_id, user_id]) and lock_user_id == user_id
1758 return all([lock_user_id, user_id]) and lock_user_id == user_id
1764
1759
1765 return False
1760 return False
1766
1761
1767 def get_locking_state(self, action, user_id, only_when_enabled=True):
1762 def get_locking_state(self, action, user_id, only_when_enabled=True):
1768 """
1763 """
1769 Checks locking on this repository, if locking is enabled and lock is
1764 Checks locking on this repository, if locking is enabled and lock is
1770 present returns a tuple of make_lock, locked, locked_by.
1765 present returns a tuple of make_lock, locked, locked_by.
1771 make_lock can have 3 states None (do nothing) True, make lock
1766 make_lock can have 3 states None (do nothing) True, make lock
1772 False release lock, This value is later propagated to hooks, which
1767 False release lock, This value is later propagated to hooks, which
1773 do the locking. Think about this as signals passed to hooks what to do.
1768 do the locking. Think about this as signals passed to hooks what to do.
1774
1769
1775 """
1770 """
1776 # TODO: johbo: This is part of the business logic and should be moved
1771 # TODO: johbo: This is part of the business logic and should be moved
1777 # into the RepositoryModel.
1772 # into the RepositoryModel.
1778
1773
1779 if action not in ('push', 'pull'):
1774 if action not in ('push', 'pull'):
1780 raise ValueError("Invalid action value: %s" % repr(action))
1775 raise ValueError("Invalid action value: %s" % repr(action))
1781
1776
1782 # defines if locked error should be thrown to user
1777 # defines if locked error should be thrown to user
1783 currently_locked = False
1778 currently_locked = False
1784 # defines if new lock should be made, tri-state
1779 # defines if new lock should be made, tri-state
1785 make_lock = None
1780 make_lock = None
1786 repo = self
1781 repo = self
1787 user = User.get(user_id)
1782 user = User.get(user_id)
1788
1783
1789 lock_info = repo.locked
1784 lock_info = repo.locked
1790
1785
1791 if repo and (repo.enable_locking or not only_when_enabled):
1786 if repo and (repo.enable_locking or not only_when_enabled):
1792 if action == 'push':
1787 if action == 'push':
1793 # check if it's already locked !, if it is compare users
1788 # check if it's already locked !, if it is compare users
1794 locked_by_user_id = lock_info[0]
1789 locked_by_user_id = lock_info[0]
1795 if user.user_id == locked_by_user_id:
1790 if user.user_id == locked_by_user_id:
1796 log.debug(
1791 log.debug(
1797 'Got `push` action from user %s, now unlocking', user)
1792 'Got `push` action from user %s, now unlocking', user)
1798 # unlock if we have push from user who locked
1793 # unlock if we have push from user who locked
1799 make_lock = False
1794 make_lock = False
1800 else:
1795 else:
1801 # we're not the same user who locked, ban with
1796 # we're not the same user who locked, ban with
1802 # code defined in settings (default is 423 HTTP Locked) !
1797 # code defined in settings (default is 423 HTTP Locked) !
1803 log.debug('Repo %s is currently locked by %s', repo, user)
1798 log.debug('Repo %s is currently locked by %s', repo, user)
1804 currently_locked = True
1799 currently_locked = True
1805 elif action == 'pull':
1800 elif action == 'pull':
1806 # [0] user [1] date
1801 # [0] user [1] date
1807 if lock_info[0] and lock_info[1]:
1802 if lock_info[0] and lock_info[1]:
1808 log.debug('Repo %s is currently locked by %s', repo, user)
1803 log.debug('Repo %s is currently locked by %s', repo, user)
1809 currently_locked = True
1804 currently_locked = True
1810 else:
1805 else:
1811 log.debug('Setting lock on repo %s by %s', repo, user)
1806 log.debug('Setting lock on repo %s by %s', repo, user)
1812 make_lock = True
1807 make_lock = True
1813
1808
1814 else:
1809 else:
1815 log.debug('Repository %s do not have locking enabled', repo)
1810 log.debug('Repository %s do not have locking enabled', repo)
1816
1811
1817 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1812 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1818 make_lock, currently_locked, lock_info)
1813 make_lock, currently_locked, lock_info)
1819
1814
1820 from rhodecode.lib.auth import HasRepoPermissionAny
1815 from rhodecode.lib.auth import HasRepoPermissionAny
1821 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1816 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1822 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1817 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1823 # if we don't have at least write permission we cannot make a lock
1818 # if we don't have at least write permission we cannot make a lock
1824 log.debug('lock state reset back to FALSE due to lack '
1819 log.debug('lock state reset back to FALSE due to lack '
1825 'of at least read permission')
1820 'of at least read permission')
1826 make_lock = False
1821 make_lock = False
1827
1822
1828 return make_lock, currently_locked, lock_info
1823 return make_lock, currently_locked, lock_info
1829
1824
1830 @property
1825 @property
1831 def last_db_change(self):
1826 def last_db_change(self):
1832 return self.updated_on
1827 return self.updated_on
1833
1828
1834 @property
1829 @property
1835 def clone_uri_hidden(self):
1830 def clone_uri_hidden(self):
1836 clone_uri = self.clone_uri
1831 clone_uri = self.clone_uri
1837 if clone_uri:
1832 if clone_uri:
1838 import urlobject
1833 import urlobject
1839 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
1834 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
1840 if url_obj.password:
1835 if url_obj.password:
1841 clone_uri = url_obj.with_password('*****')
1836 clone_uri = url_obj.with_password('*****')
1842 return clone_uri
1837 return clone_uri
1843
1838
1844 def clone_url(self, **override):
1839 def clone_url(self, **override):
1845 qualified_home_url = url('home', qualified=True)
1840 qualified_home_url = url('home', qualified=True)
1846
1841
1847 uri_tmpl = None
1842 uri_tmpl = None
1848 if 'with_id' in override:
1843 if 'with_id' in override:
1849 uri_tmpl = self.DEFAULT_CLONE_URI_ID
1844 uri_tmpl = self.DEFAULT_CLONE_URI_ID
1850 del override['with_id']
1845 del override['with_id']
1851
1846
1852 if 'uri_tmpl' in override:
1847 if 'uri_tmpl' in override:
1853 uri_tmpl = override['uri_tmpl']
1848 uri_tmpl = override['uri_tmpl']
1854 del override['uri_tmpl']
1849 del override['uri_tmpl']
1855
1850
1856 # we didn't override our tmpl from **overrides
1851 # we didn't override our tmpl from **overrides
1857 if not uri_tmpl:
1852 if not uri_tmpl:
1858 uri_tmpl = self.DEFAULT_CLONE_URI
1853 uri_tmpl = self.DEFAULT_CLONE_URI
1859 try:
1854 try:
1860 from pylons import tmpl_context as c
1855 from pylons import tmpl_context as c
1861 uri_tmpl = c.clone_uri_tmpl
1856 uri_tmpl = c.clone_uri_tmpl
1862 except Exception:
1857 except Exception:
1863 # in any case if we call this outside of request context,
1858 # in any case if we call this outside of request context,
1864 # ie, not having tmpl_context set up
1859 # ie, not having tmpl_context set up
1865 pass
1860 pass
1866
1861
1867 return get_clone_url(uri_tmpl=uri_tmpl,
1862 return get_clone_url(uri_tmpl=uri_tmpl,
1868 qualifed_home_url=qualified_home_url,
1863 qualifed_home_url=qualified_home_url,
1869 repo_name=self.repo_name,
1864 repo_name=self.repo_name,
1870 repo_id=self.repo_id, **override)
1865 repo_id=self.repo_id, **override)
1871
1866
1872 def set_state(self, state):
1867 def set_state(self, state):
1873 self.repo_state = state
1868 self.repo_state = state
1874 Session().add(self)
1869 Session().add(self)
1875 #==========================================================================
1870 #==========================================================================
1876 # SCM PROPERTIES
1871 # SCM PROPERTIES
1877 #==========================================================================
1872 #==========================================================================
1878
1873
1879 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
1874 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
1880 return get_commit_safe(
1875 return get_commit_safe(
1881 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
1876 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
1882
1877
1883 def get_changeset(self, rev=None, pre_load=None):
1878 def get_changeset(self, rev=None, pre_load=None):
1884 warnings.warn("Use get_commit", DeprecationWarning)
1879 warnings.warn("Use get_commit", DeprecationWarning)
1885 commit_id = None
1880 commit_id = None
1886 commit_idx = None
1881 commit_idx = None
1887 if isinstance(rev, basestring):
1882 if isinstance(rev, basestring):
1888 commit_id = rev
1883 commit_id = rev
1889 else:
1884 else:
1890 commit_idx = rev
1885 commit_idx = rev
1891 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
1886 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
1892 pre_load=pre_load)
1887 pre_load=pre_load)
1893
1888
1894 def get_landing_commit(self):
1889 def get_landing_commit(self):
1895 """
1890 """
1896 Returns landing commit, or if that doesn't exist returns the tip
1891 Returns landing commit, or if that doesn't exist returns the tip
1897 """
1892 """
1898 _rev_type, _rev = self.landing_rev
1893 _rev_type, _rev = self.landing_rev
1899 commit = self.get_commit(_rev)
1894 commit = self.get_commit(_rev)
1900 if isinstance(commit, EmptyCommit):
1895 if isinstance(commit, EmptyCommit):
1901 return self.get_commit()
1896 return self.get_commit()
1902 return commit
1897 return commit
1903
1898
1904 def update_commit_cache(self, cs_cache=None, config=None):
1899 def update_commit_cache(self, cs_cache=None, config=None):
1905 """
1900 """
1906 Update cache of last changeset for repository, keys should be::
1901 Update cache of last changeset for repository, keys should be::
1907
1902
1908 short_id
1903 short_id
1909 raw_id
1904 raw_id
1910 revision
1905 revision
1911 parents
1906 parents
1912 message
1907 message
1913 date
1908 date
1914 author
1909 author
1915
1910
1916 :param cs_cache:
1911 :param cs_cache:
1917 """
1912 """
1918 from rhodecode.lib.vcs.backends.base import BaseChangeset
1913 from rhodecode.lib.vcs.backends.base import BaseChangeset
1919 if cs_cache is None:
1914 if cs_cache is None:
1920 # use no-cache version here
1915 # use no-cache version here
1921 scm_repo = self.scm_instance(cache=False, config=config)
1916 scm_repo = self.scm_instance(cache=False, config=config)
1922 if scm_repo:
1917 if scm_repo:
1923 cs_cache = scm_repo.get_commit(
1918 cs_cache = scm_repo.get_commit(
1924 pre_load=["author", "date", "message", "parents"])
1919 pre_load=["author", "date", "message", "parents"])
1925 else:
1920 else:
1926 cs_cache = EmptyCommit()
1921 cs_cache = EmptyCommit()
1927
1922
1928 if isinstance(cs_cache, BaseChangeset):
1923 if isinstance(cs_cache, BaseChangeset):
1929 cs_cache = cs_cache.__json__()
1924 cs_cache = cs_cache.__json__()
1930
1925
1931 def is_outdated(new_cs_cache):
1926 def is_outdated(new_cs_cache):
1932 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
1927 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
1933 new_cs_cache['revision'] != self.changeset_cache['revision']):
1928 new_cs_cache['revision'] != self.changeset_cache['revision']):
1934 return True
1929 return True
1935 return False
1930 return False
1936
1931
1937 # check if we have maybe already latest cached revision
1932 # check if we have maybe already latest cached revision
1938 if is_outdated(cs_cache) or not self.changeset_cache:
1933 if is_outdated(cs_cache) or not self.changeset_cache:
1939 _default = datetime.datetime.fromtimestamp(0)
1934 _default = datetime.datetime.fromtimestamp(0)
1940 last_change = cs_cache.get('date') or _default
1935 last_change = cs_cache.get('date') or _default
1941 log.debug('updated repo %s with new cs cache %s',
1936 log.debug('updated repo %s with new cs cache %s',
1942 self.repo_name, cs_cache)
1937 self.repo_name, cs_cache)
1943 self.updated_on = last_change
1938 self.updated_on = last_change
1944 self.changeset_cache = cs_cache
1939 self.changeset_cache = cs_cache
1945 Session().add(self)
1940 Session().add(self)
1946 Session().commit()
1941 Session().commit()
1947 else:
1942 else:
1948 log.debug('Skipping update_commit_cache for repo:`%s` '
1943 log.debug('Skipping update_commit_cache for repo:`%s` '
1949 'commit already with latest changes', self.repo_name)
1944 'commit already with latest changes', self.repo_name)
1950
1945
1951 @property
1946 @property
1952 def tip(self):
1947 def tip(self):
1953 return self.get_commit('tip')
1948 return self.get_commit('tip')
1954
1949
1955 @property
1950 @property
1956 def author(self):
1951 def author(self):
1957 return self.tip.author
1952 return self.tip.author
1958
1953
1959 @property
1954 @property
1960 def last_change(self):
1955 def last_change(self):
1961 return self.scm_instance().last_change
1956 return self.scm_instance().last_change
1962
1957
1963 def get_comments(self, revisions=None):
1958 def get_comments(self, revisions=None):
1964 """
1959 """
1965 Returns comments for this repository grouped by revisions
1960 Returns comments for this repository grouped by revisions
1966
1961
1967 :param revisions: filter query by revisions only
1962 :param revisions: filter query by revisions only
1968 """
1963 """
1969 cmts = ChangesetComment.query()\
1964 cmts = ChangesetComment.query()\
1970 .filter(ChangesetComment.repo == self)
1965 .filter(ChangesetComment.repo == self)
1971 if revisions:
1966 if revisions:
1972 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
1967 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
1973 grouped = collections.defaultdict(list)
1968 grouped = collections.defaultdict(list)
1974 for cmt in cmts.all():
1969 for cmt in cmts.all():
1975 grouped[cmt.revision].append(cmt)
1970 grouped[cmt.revision].append(cmt)
1976 return grouped
1971 return grouped
1977
1972
1978 def statuses(self, revisions=None):
1973 def statuses(self, revisions=None):
1979 """
1974 """
1980 Returns statuses for this repository
1975 Returns statuses for this repository
1981
1976
1982 :param revisions: list of revisions to get statuses for
1977 :param revisions: list of revisions to get statuses for
1983 """
1978 """
1984 statuses = ChangesetStatus.query()\
1979 statuses = ChangesetStatus.query()\
1985 .filter(ChangesetStatus.repo == self)\
1980 .filter(ChangesetStatus.repo == self)\
1986 .filter(ChangesetStatus.version == 0)
1981 .filter(ChangesetStatus.version == 0)
1987
1982
1988 if revisions:
1983 if revisions:
1989 # Try doing the filtering in chunks to avoid hitting limits
1984 # Try doing the filtering in chunks to avoid hitting limits
1990 size = 500
1985 size = 500
1991 status_results = []
1986 status_results = []
1992 for chunk in xrange(0, len(revisions), size):
1987 for chunk in xrange(0, len(revisions), size):
1993 status_results += statuses.filter(
1988 status_results += statuses.filter(
1994 ChangesetStatus.revision.in_(
1989 ChangesetStatus.revision.in_(
1995 revisions[chunk: chunk+size])
1990 revisions[chunk: chunk+size])
1996 ).all()
1991 ).all()
1997 else:
1992 else:
1998 status_results = statuses.all()
1993 status_results = statuses.all()
1999
1994
2000 grouped = {}
1995 grouped = {}
2001
1996
2002 # maybe we have open new pullrequest without a status?
1997 # maybe we have open new pullrequest without a status?
2003 stat = ChangesetStatus.STATUS_UNDER_REVIEW
1998 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2004 status_lbl = ChangesetStatus.get_status_lbl(stat)
1999 status_lbl = ChangesetStatus.get_status_lbl(stat)
2005 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2000 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2006 for rev in pr.revisions:
2001 for rev in pr.revisions:
2007 pr_id = pr.pull_request_id
2002 pr_id = pr.pull_request_id
2008 pr_repo = pr.target_repo.repo_name
2003 pr_repo = pr.target_repo.repo_name
2009 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2004 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2010
2005
2011 for stat in status_results:
2006 for stat in status_results:
2012 pr_id = pr_repo = None
2007 pr_id = pr_repo = None
2013 if stat.pull_request:
2008 if stat.pull_request:
2014 pr_id = stat.pull_request.pull_request_id
2009 pr_id = stat.pull_request.pull_request_id
2015 pr_repo = stat.pull_request.target_repo.repo_name
2010 pr_repo = stat.pull_request.target_repo.repo_name
2016 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2011 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2017 pr_id, pr_repo]
2012 pr_id, pr_repo]
2018 return grouped
2013 return grouped
2019
2014
2020 # ==========================================================================
2015 # ==========================================================================
2021 # SCM CACHE INSTANCE
2016 # SCM CACHE INSTANCE
2022 # ==========================================================================
2017 # ==========================================================================
2023
2018
2024 def scm_instance(self, **kwargs):
2019 def scm_instance(self, **kwargs):
2025 import rhodecode
2020 import rhodecode
2026
2021
2027 # Passing a config will not hit the cache currently only used
2022 # Passing a config will not hit the cache currently only used
2028 # for repo2dbmapper
2023 # for repo2dbmapper
2029 config = kwargs.pop('config', None)
2024 config = kwargs.pop('config', None)
2030 cache = kwargs.pop('cache', None)
2025 cache = kwargs.pop('cache', None)
2031 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2026 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2032 # if cache is NOT defined use default global, else we have a full
2027 # if cache is NOT defined use default global, else we have a full
2033 # control over cache behaviour
2028 # control over cache behaviour
2034 if cache is None and full_cache and not config:
2029 if cache is None and full_cache and not config:
2035 return self._get_instance_cached()
2030 return self._get_instance_cached()
2036 return self._get_instance(cache=bool(cache), config=config)
2031 return self._get_instance(cache=bool(cache), config=config)
2037
2032
2038 def _get_instance_cached(self):
2033 def _get_instance_cached(self):
2039 @cache_region('long_term')
2034 @cache_region('long_term')
2040 def _get_repo(cache_key):
2035 def _get_repo(cache_key):
2041 return self._get_instance()
2036 return self._get_instance()
2042
2037
2043 invalidator_context = CacheKey.repo_context_cache(
2038 invalidator_context = CacheKey.repo_context_cache(
2044 _get_repo, self.repo_name, None, thread_scoped=True)
2039 _get_repo, self.repo_name, None, thread_scoped=True)
2045
2040
2046 with invalidator_context as context:
2041 with invalidator_context as context:
2047 context.invalidate()
2042 context.invalidate()
2048 repo = context.compute()
2043 repo = context.compute()
2049
2044
2050 return repo
2045 return repo
2051
2046
2052 def _get_instance(self, cache=True, config=None):
2047 def _get_instance(self, cache=True, config=None):
2053 config = config or self._config
2048 config = config or self._config
2054 custom_wire = {
2049 custom_wire = {
2055 'cache': cache # controls the vcs.remote cache
2050 'cache': cache # controls the vcs.remote cache
2056 }
2051 }
2057 repo = get_vcs_instance(
2052 repo = get_vcs_instance(
2058 repo_path=safe_str(self.repo_full_path),
2053 repo_path=safe_str(self.repo_full_path),
2059 config=config,
2054 config=config,
2060 with_wire=custom_wire,
2055 with_wire=custom_wire,
2061 create=False,
2056 create=False,
2062 _vcs_alias=self.repo_type)
2057 _vcs_alias=self.repo_type)
2063
2058
2064 return repo
2059 return repo
2065
2060
2066 def __json__(self):
2061 def __json__(self):
2067 return {'landing_rev': self.landing_rev}
2062 return {'landing_rev': self.landing_rev}
2068
2063
2069 def get_dict(self):
2064 def get_dict(self):
2070
2065
2071 # Since we transformed `repo_name` to a hybrid property, we need to
2066 # Since we transformed `repo_name` to a hybrid property, we need to
2072 # keep compatibility with the code which uses `repo_name` field.
2067 # keep compatibility with the code which uses `repo_name` field.
2073
2068
2074 result = super(Repository, self).get_dict()
2069 result = super(Repository, self).get_dict()
2075 result['repo_name'] = result.pop('_repo_name', None)
2070 result['repo_name'] = result.pop('_repo_name', None)
2076 return result
2071 return result
2077
2072
2078
2073
2079 class RepoGroup(Base, BaseModel):
2074 class RepoGroup(Base, BaseModel):
2080 __tablename__ = 'groups'
2075 __tablename__ = 'groups'
2081 __table_args__ = (
2076 __table_args__ = (
2082 UniqueConstraint('group_name', 'group_parent_id'),
2077 UniqueConstraint('group_name', 'group_parent_id'),
2083 CheckConstraint('group_id != group_parent_id'),
2078 CheckConstraint('group_id != group_parent_id'),
2084 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2079 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2085 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2080 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2086 )
2081 )
2087 __mapper_args__ = {'order_by': 'group_name'}
2082 __mapper_args__ = {'order_by': 'group_name'}
2088
2083
2089 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2084 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2090
2085
2091 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2086 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2092 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2087 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2093 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2088 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2094 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2089 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2095 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2090 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2096 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2091 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2097 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2092 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2098 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2093 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2099
2094
2100 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2095 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2101 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2096 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2102 parent_group = relationship('RepoGroup', remote_side=group_id)
2097 parent_group = relationship('RepoGroup', remote_side=group_id)
2103 user = relationship('User')
2098 user = relationship('User')
2104 integrations = relationship('Integration',
2099 integrations = relationship('Integration',
2105 cascade="all, delete, delete-orphan")
2100 cascade="all, delete, delete-orphan")
2106
2101
2107 def __init__(self, group_name='', parent_group=None):
2102 def __init__(self, group_name='', parent_group=None):
2108 self.group_name = group_name
2103 self.group_name = group_name
2109 self.parent_group = parent_group
2104 self.parent_group = parent_group
2110
2105
2111 def __unicode__(self):
2106 def __unicode__(self):
2112 return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
2107 return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
2113 self.group_name)
2108 self.group_name)
2114
2109
2115 @classmethod
2110 @classmethod
2116 def _generate_choice(cls, repo_group):
2111 def _generate_choice(cls, repo_group):
2117 from webhelpers.html import literal as _literal
2112 from webhelpers.html import literal as _literal
2118 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2113 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2119 return repo_group.group_id, _name(repo_group.full_path_splitted)
2114 return repo_group.group_id, _name(repo_group.full_path_splitted)
2120
2115
2121 @classmethod
2116 @classmethod
2122 def groups_choices(cls, groups=None, show_empty_group=True):
2117 def groups_choices(cls, groups=None, show_empty_group=True):
2123 if not groups:
2118 if not groups:
2124 groups = cls.query().all()
2119 groups = cls.query().all()
2125
2120
2126 repo_groups = []
2121 repo_groups = []
2127 if show_empty_group:
2122 if show_empty_group:
2128 repo_groups = [('-1', u'-- %s --' % _('No parent'))]
2123 repo_groups = [('-1', u'-- %s --' % _('No parent'))]
2129
2124
2130 repo_groups.extend([cls._generate_choice(x) for x in groups])
2125 repo_groups.extend([cls._generate_choice(x) for x in groups])
2131
2126
2132 repo_groups = sorted(
2127 repo_groups = sorted(
2133 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2128 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2134 return repo_groups
2129 return repo_groups
2135
2130
2136 @classmethod
2131 @classmethod
2137 def url_sep(cls):
2132 def url_sep(cls):
2138 return URL_SEP
2133 return URL_SEP
2139
2134
2140 @classmethod
2135 @classmethod
2141 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2136 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2142 if case_insensitive:
2137 if case_insensitive:
2143 gr = cls.query().filter(func.lower(cls.group_name)
2138 gr = cls.query().filter(func.lower(cls.group_name)
2144 == func.lower(group_name))
2139 == func.lower(group_name))
2145 else:
2140 else:
2146 gr = cls.query().filter(cls.group_name == group_name)
2141 gr = cls.query().filter(cls.group_name == group_name)
2147 if cache:
2142 if cache:
2148 gr = gr.options(FromCache(
2143 gr = gr.options(FromCache(
2149 "sql_cache_short",
2144 "sql_cache_short",
2150 "get_group_%s" % _hash_key(group_name)))
2145 "get_group_%s" % _hash_key(group_name)))
2151 return gr.scalar()
2146 return gr.scalar()
2152
2147
2153 @classmethod
2148 @classmethod
2154 def get_user_personal_repo_group(cls, user_id):
2149 def get_user_personal_repo_group(cls, user_id):
2155 user = User.get(user_id)
2150 user = User.get(user_id)
2156 return cls.query()\
2151 return cls.query()\
2157 .filter(cls.personal == true())\
2152 .filter(cls.personal == true())\
2158 .filter(cls.user == user).scalar()
2153 .filter(cls.user == user).scalar()
2159
2154
2160 @classmethod
2155 @classmethod
2161 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2156 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2162 case_insensitive=True):
2157 case_insensitive=True):
2163 q = RepoGroup.query()
2158 q = RepoGroup.query()
2164
2159
2165 if not isinstance(user_id, Optional):
2160 if not isinstance(user_id, Optional):
2166 q = q.filter(RepoGroup.user_id == user_id)
2161 q = q.filter(RepoGroup.user_id == user_id)
2167
2162
2168 if not isinstance(group_id, Optional):
2163 if not isinstance(group_id, Optional):
2169 q = q.filter(RepoGroup.group_parent_id == group_id)
2164 q = q.filter(RepoGroup.group_parent_id == group_id)
2170
2165
2171 if case_insensitive:
2166 if case_insensitive:
2172 q = q.order_by(func.lower(RepoGroup.group_name))
2167 q = q.order_by(func.lower(RepoGroup.group_name))
2173 else:
2168 else:
2174 q = q.order_by(RepoGroup.group_name)
2169 q = q.order_by(RepoGroup.group_name)
2175 return q.all()
2170 return q.all()
2176
2171
2177 @property
2172 @property
2178 def parents(self):
2173 def parents(self):
2179 parents_recursion_limit = 10
2174 parents_recursion_limit = 10
2180 groups = []
2175 groups = []
2181 if self.parent_group is None:
2176 if self.parent_group is None:
2182 return groups
2177 return groups
2183 cur_gr = self.parent_group
2178 cur_gr = self.parent_group
2184 groups.insert(0, cur_gr)
2179 groups.insert(0, cur_gr)
2185 cnt = 0
2180 cnt = 0
2186 while 1:
2181 while 1:
2187 cnt += 1
2182 cnt += 1
2188 gr = getattr(cur_gr, 'parent_group', None)
2183 gr = getattr(cur_gr, 'parent_group', None)
2189 cur_gr = cur_gr.parent_group
2184 cur_gr = cur_gr.parent_group
2190 if gr is None:
2185 if gr is None:
2191 break
2186 break
2192 if cnt == parents_recursion_limit:
2187 if cnt == parents_recursion_limit:
2193 # this will prevent accidental infinit loops
2188 # this will prevent accidental infinit loops
2194 log.error(('more than %s parents found for group %s, stopping '
2189 log.error(('more than %s parents found for group %s, stopping '
2195 'recursive parent fetching' % (parents_recursion_limit, self)))
2190 'recursive parent fetching' % (parents_recursion_limit, self)))
2196 break
2191 break
2197
2192
2198 groups.insert(0, gr)
2193 groups.insert(0, gr)
2199 return groups
2194 return groups
2200
2195
2201 @property
2196 @property
2202 def children(self):
2197 def children(self):
2203 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2198 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2204
2199
2205 @property
2200 @property
2206 def name(self):
2201 def name(self):
2207 return self.group_name.split(RepoGroup.url_sep())[-1]
2202 return self.group_name.split(RepoGroup.url_sep())[-1]
2208
2203
2209 @property
2204 @property
2210 def full_path(self):
2205 def full_path(self):
2211 return self.group_name
2206 return self.group_name
2212
2207
2213 @property
2208 @property
2214 def full_path_splitted(self):
2209 def full_path_splitted(self):
2215 return self.group_name.split(RepoGroup.url_sep())
2210 return self.group_name.split(RepoGroup.url_sep())
2216
2211
2217 @property
2212 @property
2218 def repositories(self):
2213 def repositories(self):
2219 return Repository.query()\
2214 return Repository.query()\
2220 .filter(Repository.group == self)\
2215 .filter(Repository.group == self)\
2221 .order_by(Repository.repo_name)
2216 .order_by(Repository.repo_name)
2222
2217
2223 @property
2218 @property
2224 def repositories_recursive_count(self):
2219 def repositories_recursive_count(self):
2225 cnt = self.repositories.count()
2220 cnt = self.repositories.count()
2226
2221
2227 def children_count(group):
2222 def children_count(group):
2228 cnt = 0
2223 cnt = 0
2229 for child in group.children:
2224 for child in group.children:
2230 cnt += child.repositories.count()
2225 cnt += child.repositories.count()
2231 cnt += children_count(child)
2226 cnt += children_count(child)
2232 return cnt
2227 return cnt
2233
2228
2234 return cnt + children_count(self)
2229 return cnt + children_count(self)
2235
2230
2236 def _recursive_objects(self, include_repos=True):
2231 def _recursive_objects(self, include_repos=True):
2237 all_ = []
2232 all_ = []
2238
2233
2239 def _get_members(root_gr):
2234 def _get_members(root_gr):
2240 if include_repos:
2235 if include_repos:
2241 for r in root_gr.repositories:
2236 for r in root_gr.repositories:
2242 all_.append(r)
2237 all_.append(r)
2243 childs = root_gr.children.all()
2238 childs = root_gr.children.all()
2244 if childs:
2239 if childs:
2245 for gr in childs:
2240 for gr in childs:
2246 all_.append(gr)
2241 all_.append(gr)
2247 _get_members(gr)
2242 _get_members(gr)
2248
2243
2249 _get_members(self)
2244 _get_members(self)
2250 return [self] + all_
2245 return [self] + all_
2251
2246
2252 def recursive_groups_and_repos(self):
2247 def recursive_groups_and_repos(self):
2253 """
2248 """
2254 Recursive return all groups, with repositories in those groups
2249 Recursive return all groups, with repositories in those groups
2255 """
2250 """
2256 return self._recursive_objects()
2251 return self._recursive_objects()
2257
2252
2258 def recursive_groups(self):
2253 def recursive_groups(self):
2259 """
2254 """
2260 Returns all children groups for this group including children of children
2255 Returns all children groups for this group including children of children
2261 """
2256 """
2262 return self._recursive_objects(include_repos=False)
2257 return self._recursive_objects(include_repos=False)
2263
2258
2264 def get_new_name(self, group_name):
2259 def get_new_name(self, group_name):
2265 """
2260 """
2266 returns new full group name based on parent and new name
2261 returns new full group name based on parent and new name
2267
2262
2268 :param group_name:
2263 :param group_name:
2269 """
2264 """
2270 path_prefix = (self.parent_group.full_path_splitted if
2265 path_prefix = (self.parent_group.full_path_splitted if
2271 self.parent_group else [])
2266 self.parent_group else [])
2272 return RepoGroup.url_sep().join(path_prefix + [group_name])
2267 return RepoGroup.url_sep().join(path_prefix + [group_name])
2273
2268
2274 def permissions(self, with_admins=True, with_owner=True):
2269 def permissions(self, with_admins=True, with_owner=True):
2275 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2270 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2276 q = q.options(joinedload(UserRepoGroupToPerm.group),
2271 q = q.options(joinedload(UserRepoGroupToPerm.group),
2277 joinedload(UserRepoGroupToPerm.user),
2272 joinedload(UserRepoGroupToPerm.user),
2278 joinedload(UserRepoGroupToPerm.permission),)
2273 joinedload(UserRepoGroupToPerm.permission),)
2279
2274
2280 # get owners and admins and permissions. We do a trick of re-writing
2275 # get owners and admins and permissions. We do a trick of re-writing
2281 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2276 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2282 # has a global reference and changing one object propagates to all
2277 # has a global reference and changing one object propagates to all
2283 # others. This means if admin is also an owner admin_row that change
2278 # others. This means if admin is also an owner admin_row that change
2284 # would propagate to both objects
2279 # would propagate to both objects
2285 perm_rows = []
2280 perm_rows = []
2286 for _usr in q.all():
2281 for _usr in q.all():
2287 usr = AttributeDict(_usr.user.get_dict())
2282 usr = AttributeDict(_usr.user.get_dict())
2288 usr.permission = _usr.permission.permission_name
2283 usr.permission = _usr.permission.permission_name
2289 perm_rows.append(usr)
2284 perm_rows.append(usr)
2290
2285
2291 # filter the perm rows by 'default' first and then sort them by
2286 # filter the perm rows by 'default' first and then sort them by
2292 # admin,write,read,none permissions sorted again alphabetically in
2287 # admin,write,read,none permissions sorted again alphabetically in
2293 # each group
2288 # each group
2294 perm_rows = sorted(perm_rows, key=display_sort)
2289 perm_rows = sorted(perm_rows, key=display_sort)
2295
2290
2296 _admin_perm = 'group.admin'
2291 _admin_perm = 'group.admin'
2297 owner_row = []
2292 owner_row = []
2298 if with_owner:
2293 if with_owner:
2299 usr = AttributeDict(self.user.get_dict())
2294 usr = AttributeDict(self.user.get_dict())
2300 usr.owner_row = True
2295 usr.owner_row = True
2301 usr.permission = _admin_perm
2296 usr.permission = _admin_perm
2302 owner_row.append(usr)
2297 owner_row.append(usr)
2303
2298
2304 super_admin_rows = []
2299 super_admin_rows = []
2305 if with_admins:
2300 if with_admins:
2306 for usr in User.get_all_super_admins():
2301 for usr in User.get_all_super_admins():
2307 # if this admin is also owner, don't double the record
2302 # if this admin is also owner, don't double the record
2308 if usr.user_id == owner_row[0].user_id:
2303 if usr.user_id == owner_row[0].user_id:
2309 owner_row[0].admin_row = True
2304 owner_row[0].admin_row = True
2310 else:
2305 else:
2311 usr = AttributeDict(usr.get_dict())
2306 usr = AttributeDict(usr.get_dict())
2312 usr.admin_row = True
2307 usr.admin_row = True
2313 usr.permission = _admin_perm
2308 usr.permission = _admin_perm
2314 super_admin_rows.append(usr)
2309 super_admin_rows.append(usr)
2315
2310
2316 return super_admin_rows + owner_row + perm_rows
2311 return super_admin_rows + owner_row + perm_rows
2317
2312
2318 def permission_user_groups(self):
2313 def permission_user_groups(self):
2319 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2314 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2320 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2315 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2321 joinedload(UserGroupRepoGroupToPerm.users_group),
2316 joinedload(UserGroupRepoGroupToPerm.users_group),
2322 joinedload(UserGroupRepoGroupToPerm.permission),)
2317 joinedload(UserGroupRepoGroupToPerm.permission),)
2323
2318
2324 perm_rows = []
2319 perm_rows = []
2325 for _user_group in q.all():
2320 for _user_group in q.all():
2326 usr = AttributeDict(_user_group.users_group.get_dict())
2321 usr = AttributeDict(_user_group.users_group.get_dict())
2327 usr.permission = _user_group.permission.permission_name
2322 usr.permission = _user_group.permission.permission_name
2328 perm_rows.append(usr)
2323 perm_rows.append(usr)
2329
2324
2330 return perm_rows
2325 return perm_rows
2331
2326
2332 def get_api_data(self):
2327 def get_api_data(self):
2333 """
2328 """
2334 Common function for generating api data
2329 Common function for generating api data
2335
2330
2336 """
2331 """
2337 group = self
2332 group = self
2338 data = {
2333 data = {
2339 'group_id': group.group_id,
2334 'group_id': group.group_id,
2340 'group_name': group.group_name,
2335 'group_name': group.group_name,
2341 'group_description': group.group_description,
2336 'group_description': group.group_description,
2342 'parent_group': group.parent_group.group_name if group.parent_group else None,
2337 'parent_group': group.parent_group.group_name if group.parent_group else None,
2343 'repositories': [x.repo_name for x in group.repositories],
2338 'repositories': [x.repo_name for x in group.repositories],
2344 'owner': group.user.username,
2339 'owner': group.user.username,
2345 }
2340 }
2346 return data
2341 return data
2347
2342
2348
2343
2349 class Permission(Base, BaseModel):
2344 class Permission(Base, BaseModel):
2350 __tablename__ = 'permissions'
2345 __tablename__ = 'permissions'
2351 __table_args__ = (
2346 __table_args__ = (
2352 Index('p_perm_name_idx', 'permission_name'),
2347 Index('p_perm_name_idx', 'permission_name'),
2353 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2348 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2354 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2349 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2355 )
2350 )
2356 PERMS = [
2351 PERMS = [
2357 ('hg.admin', _('RhodeCode Super Administrator')),
2352 ('hg.admin', _('RhodeCode Super Administrator')),
2358
2353
2359 ('repository.none', _('Repository no access')),
2354 ('repository.none', _('Repository no access')),
2360 ('repository.read', _('Repository read access')),
2355 ('repository.read', _('Repository read access')),
2361 ('repository.write', _('Repository write access')),
2356 ('repository.write', _('Repository write access')),
2362 ('repository.admin', _('Repository admin access')),
2357 ('repository.admin', _('Repository admin access')),
2363
2358
2364 ('group.none', _('Repository group no access')),
2359 ('group.none', _('Repository group no access')),
2365 ('group.read', _('Repository group read access')),
2360 ('group.read', _('Repository group read access')),
2366 ('group.write', _('Repository group write access')),
2361 ('group.write', _('Repository group write access')),
2367 ('group.admin', _('Repository group admin access')),
2362 ('group.admin', _('Repository group admin access')),
2368
2363
2369 ('usergroup.none', _('User group no access')),
2364 ('usergroup.none', _('User group no access')),
2370 ('usergroup.read', _('User group read access')),
2365 ('usergroup.read', _('User group read access')),
2371 ('usergroup.write', _('User group write access')),
2366 ('usergroup.write', _('User group write access')),
2372 ('usergroup.admin', _('User group admin access')),
2367 ('usergroup.admin', _('User group admin access')),
2373
2368
2374 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2369 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2375 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2370 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2376
2371
2377 ('hg.usergroup.create.false', _('User Group creation disabled')),
2372 ('hg.usergroup.create.false', _('User Group creation disabled')),
2378 ('hg.usergroup.create.true', _('User Group creation enabled')),
2373 ('hg.usergroup.create.true', _('User Group creation enabled')),
2379
2374
2380 ('hg.create.none', _('Repository creation disabled')),
2375 ('hg.create.none', _('Repository creation disabled')),
2381 ('hg.create.repository', _('Repository creation enabled')),
2376 ('hg.create.repository', _('Repository creation enabled')),
2382 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2377 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2383 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2378 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2384
2379
2385 ('hg.fork.none', _('Repository forking disabled')),
2380 ('hg.fork.none', _('Repository forking disabled')),
2386 ('hg.fork.repository', _('Repository forking enabled')),
2381 ('hg.fork.repository', _('Repository forking enabled')),
2387
2382
2388 ('hg.register.none', _('Registration disabled')),
2383 ('hg.register.none', _('Registration disabled')),
2389 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2384 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2390 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2385 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2391
2386
2392 ('hg.password_reset.enabled', _('Password reset enabled')),
2387 ('hg.password_reset.enabled', _('Password reset enabled')),
2393 ('hg.password_reset.hidden', _('Password reset hidden')),
2388 ('hg.password_reset.hidden', _('Password reset hidden')),
2394 ('hg.password_reset.disabled', _('Password reset disabled')),
2389 ('hg.password_reset.disabled', _('Password reset disabled')),
2395
2390
2396 ('hg.extern_activate.manual', _('Manual activation of external account')),
2391 ('hg.extern_activate.manual', _('Manual activation of external account')),
2397 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2392 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2398
2393
2399 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2394 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2400 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2395 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2401 ]
2396 ]
2402
2397
2403 # definition of system default permissions for DEFAULT user
2398 # definition of system default permissions for DEFAULT user
2404 DEFAULT_USER_PERMISSIONS = [
2399 DEFAULT_USER_PERMISSIONS = [
2405 'repository.read',
2400 'repository.read',
2406 'group.read',
2401 'group.read',
2407 'usergroup.read',
2402 'usergroup.read',
2408 'hg.create.repository',
2403 'hg.create.repository',
2409 'hg.repogroup.create.false',
2404 'hg.repogroup.create.false',
2410 'hg.usergroup.create.false',
2405 'hg.usergroup.create.false',
2411 'hg.create.write_on_repogroup.true',
2406 'hg.create.write_on_repogroup.true',
2412 'hg.fork.repository',
2407 'hg.fork.repository',
2413 'hg.register.manual_activate',
2408 'hg.register.manual_activate',
2414 'hg.password_reset.enabled',
2409 'hg.password_reset.enabled',
2415 'hg.extern_activate.auto',
2410 'hg.extern_activate.auto',
2416 'hg.inherit_default_perms.true',
2411 'hg.inherit_default_perms.true',
2417 ]
2412 ]
2418
2413
2419 # defines which permissions are more important higher the more important
2414 # defines which permissions are more important higher the more important
2420 # Weight defines which permissions are more important.
2415 # Weight defines which permissions are more important.
2421 # The higher number the more important.
2416 # The higher number the more important.
2422 PERM_WEIGHTS = {
2417 PERM_WEIGHTS = {
2423 'repository.none': 0,
2418 'repository.none': 0,
2424 'repository.read': 1,
2419 'repository.read': 1,
2425 'repository.write': 3,
2420 'repository.write': 3,
2426 'repository.admin': 4,
2421 'repository.admin': 4,
2427
2422
2428 'group.none': 0,
2423 'group.none': 0,
2429 'group.read': 1,
2424 'group.read': 1,
2430 'group.write': 3,
2425 'group.write': 3,
2431 'group.admin': 4,
2426 'group.admin': 4,
2432
2427
2433 'usergroup.none': 0,
2428 'usergroup.none': 0,
2434 'usergroup.read': 1,
2429 'usergroup.read': 1,
2435 'usergroup.write': 3,
2430 'usergroup.write': 3,
2436 'usergroup.admin': 4,
2431 'usergroup.admin': 4,
2437
2432
2438 'hg.repogroup.create.false': 0,
2433 'hg.repogroup.create.false': 0,
2439 'hg.repogroup.create.true': 1,
2434 'hg.repogroup.create.true': 1,
2440
2435
2441 'hg.usergroup.create.false': 0,
2436 'hg.usergroup.create.false': 0,
2442 'hg.usergroup.create.true': 1,
2437 'hg.usergroup.create.true': 1,
2443
2438
2444 'hg.fork.none': 0,
2439 'hg.fork.none': 0,
2445 'hg.fork.repository': 1,
2440 'hg.fork.repository': 1,
2446 'hg.create.none': 0,
2441 'hg.create.none': 0,
2447 'hg.create.repository': 1
2442 'hg.create.repository': 1
2448 }
2443 }
2449
2444
2450 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2445 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2451 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2446 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2452 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2447 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2453
2448
2454 def __unicode__(self):
2449 def __unicode__(self):
2455 return u"<%s('%s:%s')>" % (
2450 return u"<%s('%s:%s')>" % (
2456 self.__class__.__name__, self.permission_id, self.permission_name
2451 self.__class__.__name__, self.permission_id, self.permission_name
2457 )
2452 )
2458
2453
2459 @classmethod
2454 @classmethod
2460 def get_by_key(cls, key):
2455 def get_by_key(cls, key):
2461 return cls.query().filter(cls.permission_name == key).scalar()
2456 return cls.query().filter(cls.permission_name == key).scalar()
2462
2457
2463 @classmethod
2458 @classmethod
2464 def get_default_repo_perms(cls, user_id, repo_id=None):
2459 def get_default_repo_perms(cls, user_id, repo_id=None):
2465 q = Session().query(UserRepoToPerm, Repository, Permission)\
2460 q = Session().query(UserRepoToPerm, Repository, Permission)\
2466 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2461 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2467 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2462 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2468 .filter(UserRepoToPerm.user_id == user_id)
2463 .filter(UserRepoToPerm.user_id == user_id)
2469 if repo_id:
2464 if repo_id:
2470 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2465 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2471 return q.all()
2466 return q.all()
2472
2467
2473 @classmethod
2468 @classmethod
2474 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2469 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2475 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2470 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2476 .join(
2471 .join(
2477 Permission,
2472 Permission,
2478 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2473 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2479 .join(
2474 .join(
2480 Repository,
2475 Repository,
2481 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2476 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2482 .join(
2477 .join(
2483 UserGroup,
2478 UserGroup,
2484 UserGroupRepoToPerm.users_group_id ==
2479 UserGroupRepoToPerm.users_group_id ==
2485 UserGroup.users_group_id)\
2480 UserGroup.users_group_id)\
2486 .join(
2481 .join(
2487 UserGroupMember,
2482 UserGroupMember,
2488 UserGroupRepoToPerm.users_group_id ==
2483 UserGroupRepoToPerm.users_group_id ==
2489 UserGroupMember.users_group_id)\
2484 UserGroupMember.users_group_id)\
2490 .filter(
2485 .filter(
2491 UserGroupMember.user_id == user_id,
2486 UserGroupMember.user_id == user_id,
2492 UserGroup.users_group_active == true())
2487 UserGroup.users_group_active == true())
2493 if repo_id:
2488 if repo_id:
2494 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2489 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2495 return q.all()
2490 return q.all()
2496
2491
2497 @classmethod
2492 @classmethod
2498 def get_default_group_perms(cls, user_id, repo_group_id=None):
2493 def get_default_group_perms(cls, user_id, repo_group_id=None):
2499 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2494 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2500 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2495 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2501 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2496 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2502 .filter(UserRepoGroupToPerm.user_id == user_id)
2497 .filter(UserRepoGroupToPerm.user_id == user_id)
2503 if repo_group_id:
2498 if repo_group_id:
2504 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2499 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2505 return q.all()
2500 return q.all()
2506
2501
2507 @classmethod
2502 @classmethod
2508 def get_default_group_perms_from_user_group(
2503 def get_default_group_perms_from_user_group(
2509 cls, user_id, repo_group_id=None):
2504 cls, user_id, repo_group_id=None):
2510 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2505 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2511 .join(
2506 .join(
2512 Permission,
2507 Permission,
2513 UserGroupRepoGroupToPerm.permission_id ==
2508 UserGroupRepoGroupToPerm.permission_id ==
2514 Permission.permission_id)\
2509 Permission.permission_id)\
2515 .join(
2510 .join(
2516 RepoGroup,
2511 RepoGroup,
2517 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2512 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2518 .join(
2513 .join(
2519 UserGroup,
2514 UserGroup,
2520 UserGroupRepoGroupToPerm.users_group_id ==
2515 UserGroupRepoGroupToPerm.users_group_id ==
2521 UserGroup.users_group_id)\
2516 UserGroup.users_group_id)\
2522 .join(
2517 .join(
2523 UserGroupMember,
2518 UserGroupMember,
2524 UserGroupRepoGroupToPerm.users_group_id ==
2519 UserGroupRepoGroupToPerm.users_group_id ==
2525 UserGroupMember.users_group_id)\
2520 UserGroupMember.users_group_id)\
2526 .filter(
2521 .filter(
2527 UserGroupMember.user_id == user_id,
2522 UserGroupMember.user_id == user_id,
2528 UserGroup.users_group_active == true())
2523 UserGroup.users_group_active == true())
2529 if repo_group_id:
2524 if repo_group_id:
2530 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2525 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2531 return q.all()
2526 return q.all()
2532
2527
2533 @classmethod
2528 @classmethod
2534 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2529 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2535 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2530 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2536 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2531 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2537 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2532 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2538 .filter(UserUserGroupToPerm.user_id == user_id)
2533 .filter(UserUserGroupToPerm.user_id == user_id)
2539 if user_group_id:
2534 if user_group_id:
2540 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2535 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2541 return q.all()
2536 return q.all()
2542
2537
2543 @classmethod
2538 @classmethod
2544 def get_default_user_group_perms_from_user_group(
2539 def get_default_user_group_perms_from_user_group(
2545 cls, user_id, user_group_id=None):
2540 cls, user_id, user_group_id=None):
2546 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2541 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2547 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2542 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2548 .join(
2543 .join(
2549 Permission,
2544 Permission,
2550 UserGroupUserGroupToPerm.permission_id ==
2545 UserGroupUserGroupToPerm.permission_id ==
2551 Permission.permission_id)\
2546 Permission.permission_id)\
2552 .join(
2547 .join(
2553 TargetUserGroup,
2548 TargetUserGroup,
2554 UserGroupUserGroupToPerm.target_user_group_id ==
2549 UserGroupUserGroupToPerm.target_user_group_id ==
2555 TargetUserGroup.users_group_id)\
2550 TargetUserGroup.users_group_id)\
2556 .join(
2551 .join(
2557 UserGroup,
2552 UserGroup,
2558 UserGroupUserGroupToPerm.user_group_id ==
2553 UserGroupUserGroupToPerm.user_group_id ==
2559 UserGroup.users_group_id)\
2554 UserGroup.users_group_id)\
2560 .join(
2555 .join(
2561 UserGroupMember,
2556 UserGroupMember,
2562 UserGroupUserGroupToPerm.user_group_id ==
2557 UserGroupUserGroupToPerm.user_group_id ==
2563 UserGroupMember.users_group_id)\
2558 UserGroupMember.users_group_id)\
2564 .filter(
2559 .filter(
2565 UserGroupMember.user_id == user_id,
2560 UserGroupMember.user_id == user_id,
2566 UserGroup.users_group_active == true())
2561 UserGroup.users_group_active == true())
2567 if user_group_id:
2562 if user_group_id:
2568 q = q.filter(
2563 q = q.filter(
2569 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2564 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2570
2565
2571 return q.all()
2566 return q.all()
2572
2567
2573
2568
2574 class UserRepoToPerm(Base, BaseModel):
2569 class UserRepoToPerm(Base, BaseModel):
2575 __tablename__ = 'repo_to_perm'
2570 __tablename__ = 'repo_to_perm'
2576 __table_args__ = (
2571 __table_args__ = (
2577 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2572 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2578 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2573 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2579 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2574 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2580 )
2575 )
2581 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2576 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2582 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2577 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2583 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2578 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2584 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2579 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2585
2580
2586 user = relationship('User')
2581 user = relationship('User')
2587 repository = relationship('Repository')
2582 repository = relationship('Repository')
2588 permission = relationship('Permission')
2583 permission = relationship('Permission')
2589
2584
2590 @classmethod
2585 @classmethod
2591 def create(cls, user, repository, permission):
2586 def create(cls, user, repository, permission):
2592 n = cls()
2587 n = cls()
2593 n.user = user
2588 n.user = user
2594 n.repository = repository
2589 n.repository = repository
2595 n.permission = permission
2590 n.permission = permission
2596 Session().add(n)
2591 Session().add(n)
2597 return n
2592 return n
2598
2593
2599 def __unicode__(self):
2594 def __unicode__(self):
2600 return u'<%s => %s >' % (self.user, self.repository)
2595 return u'<%s => %s >' % (self.user, self.repository)
2601
2596
2602
2597
2603 class UserUserGroupToPerm(Base, BaseModel):
2598 class UserUserGroupToPerm(Base, BaseModel):
2604 __tablename__ = 'user_user_group_to_perm'
2599 __tablename__ = 'user_user_group_to_perm'
2605 __table_args__ = (
2600 __table_args__ = (
2606 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2601 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2607 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2602 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2608 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2603 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2609 )
2604 )
2610 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2605 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2611 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2606 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2612 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2607 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2613 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2608 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2614
2609
2615 user = relationship('User')
2610 user = relationship('User')
2616 user_group = relationship('UserGroup')
2611 user_group = relationship('UserGroup')
2617 permission = relationship('Permission')
2612 permission = relationship('Permission')
2618
2613
2619 @classmethod
2614 @classmethod
2620 def create(cls, user, user_group, permission):
2615 def create(cls, user, user_group, permission):
2621 n = cls()
2616 n = cls()
2622 n.user = user
2617 n.user = user
2623 n.user_group = user_group
2618 n.user_group = user_group
2624 n.permission = permission
2619 n.permission = permission
2625 Session().add(n)
2620 Session().add(n)
2626 return n
2621 return n
2627
2622
2628 def __unicode__(self):
2623 def __unicode__(self):
2629 return u'<%s => %s >' % (self.user, self.user_group)
2624 return u'<%s => %s >' % (self.user, self.user_group)
2630
2625
2631
2626
2632 class UserToPerm(Base, BaseModel):
2627 class UserToPerm(Base, BaseModel):
2633 __tablename__ = 'user_to_perm'
2628 __tablename__ = 'user_to_perm'
2634 __table_args__ = (
2629 __table_args__ = (
2635 UniqueConstraint('user_id', 'permission_id'),
2630 UniqueConstraint('user_id', 'permission_id'),
2636 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2631 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2637 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2632 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2638 )
2633 )
2639 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2634 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2640 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2635 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2641 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2636 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2642
2637
2643 user = relationship('User')
2638 user = relationship('User')
2644 permission = relationship('Permission', lazy='joined')
2639 permission = relationship('Permission', lazy='joined')
2645
2640
2646 def __unicode__(self):
2641 def __unicode__(self):
2647 return u'<%s => %s >' % (self.user, self.permission)
2642 return u'<%s => %s >' % (self.user, self.permission)
2648
2643
2649
2644
2650 class UserGroupRepoToPerm(Base, BaseModel):
2645 class UserGroupRepoToPerm(Base, BaseModel):
2651 __tablename__ = 'users_group_repo_to_perm'
2646 __tablename__ = 'users_group_repo_to_perm'
2652 __table_args__ = (
2647 __table_args__ = (
2653 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2648 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2654 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2649 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2655 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2650 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2656 )
2651 )
2657 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2652 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2658 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2653 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2659 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2654 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2660 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2655 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2661
2656
2662 users_group = relationship('UserGroup')
2657 users_group = relationship('UserGroup')
2663 permission = relationship('Permission')
2658 permission = relationship('Permission')
2664 repository = relationship('Repository')
2659 repository = relationship('Repository')
2665
2660
2666 @classmethod
2661 @classmethod
2667 def create(cls, users_group, repository, permission):
2662 def create(cls, users_group, repository, permission):
2668 n = cls()
2663 n = cls()
2669 n.users_group = users_group
2664 n.users_group = users_group
2670 n.repository = repository
2665 n.repository = repository
2671 n.permission = permission
2666 n.permission = permission
2672 Session().add(n)
2667 Session().add(n)
2673 return n
2668 return n
2674
2669
2675 def __unicode__(self):
2670 def __unicode__(self):
2676 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2671 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2677
2672
2678
2673
2679 class UserGroupUserGroupToPerm(Base, BaseModel):
2674 class UserGroupUserGroupToPerm(Base, BaseModel):
2680 __tablename__ = 'user_group_user_group_to_perm'
2675 __tablename__ = 'user_group_user_group_to_perm'
2681 __table_args__ = (
2676 __table_args__ = (
2682 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2677 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2683 CheckConstraint('target_user_group_id != user_group_id'),
2678 CheckConstraint('target_user_group_id != user_group_id'),
2684 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2679 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2685 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2680 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2686 )
2681 )
2687 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)
2682 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)
2688 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2683 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2689 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2684 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2690 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2685 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2691
2686
2692 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2687 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2693 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2688 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2694 permission = relationship('Permission')
2689 permission = relationship('Permission')
2695
2690
2696 @classmethod
2691 @classmethod
2697 def create(cls, target_user_group, user_group, permission):
2692 def create(cls, target_user_group, user_group, permission):
2698 n = cls()
2693 n = cls()
2699 n.target_user_group = target_user_group
2694 n.target_user_group = target_user_group
2700 n.user_group = user_group
2695 n.user_group = user_group
2701 n.permission = permission
2696 n.permission = permission
2702 Session().add(n)
2697 Session().add(n)
2703 return n
2698 return n
2704
2699
2705 def __unicode__(self):
2700 def __unicode__(self):
2706 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2701 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2707
2702
2708
2703
2709 class UserGroupToPerm(Base, BaseModel):
2704 class UserGroupToPerm(Base, BaseModel):
2710 __tablename__ = 'users_group_to_perm'
2705 __tablename__ = 'users_group_to_perm'
2711 __table_args__ = (
2706 __table_args__ = (
2712 UniqueConstraint('users_group_id', 'permission_id',),
2707 UniqueConstraint('users_group_id', 'permission_id',),
2713 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2708 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2714 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2709 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2715 )
2710 )
2716 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2711 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2717 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2712 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2718 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2713 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2719
2714
2720 users_group = relationship('UserGroup')
2715 users_group = relationship('UserGroup')
2721 permission = relationship('Permission')
2716 permission = relationship('Permission')
2722
2717
2723
2718
2724 class UserRepoGroupToPerm(Base, BaseModel):
2719 class UserRepoGroupToPerm(Base, BaseModel):
2725 __tablename__ = 'user_repo_group_to_perm'
2720 __tablename__ = 'user_repo_group_to_perm'
2726 __table_args__ = (
2721 __table_args__ = (
2727 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2722 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2728 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2723 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2729 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2724 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2730 )
2725 )
2731
2726
2732 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2727 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2733 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2728 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2734 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2729 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2735 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2730 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2736
2731
2737 user = relationship('User')
2732 user = relationship('User')
2738 group = relationship('RepoGroup')
2733 group = relationship('RepoGroup')
2739 permission = relationship('Permission')
2734 permission = relationship('Permission')
2740
2735
2741 @classmethod
2736 @classmethod
2742 def create(cls, user, repository_group, permission):
2737 def create(cls, user, repository_group, permission):
2743 n = cls()
2738 n = cls()
2744 n.user = user
2739 n.user = user
2745 n.group = repository_group
2740 n.group = repository_group
2746 n.permission = permission
2741 n.permission = permission
2747 Session().add(n)
2742 Session().add(n)
2748 return n
2743 return n
2749
2744
2750
2745
2751 class UserGroupRepoGroupToPerm(Base, BaseModel):
2746 class UserGroupRepoGroupToPerm(Base, BaseModel):
2752 __tablename__ = 'users_group_repo_group_to_perm'
2747 __tablename__ = 'users_group_repo_group_to_perm'
2753 __table_args__ = (
2748 __table_args__ = (
2754 UniqueConstraint('users_group_id', 'group_id'),
2749 UniqueConstraint('users_group_id', 'group_id'),
2755 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2750 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2756 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2751 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2757 )
2752 )
2758
2753
2759 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)
2754 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)
2760 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2755 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2761 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2756 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2762 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2757 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2763
2758
2764 users_group = relationship('UserGroup')
2759 users_group = relationship('UserGroup')
2765 permission = relationship('Permission')
2760 permission = relationship('Permission')
2766 group = relationship('RepoGroup')
2761 group = relationship('RepoGroup')
2767
2762
2768 @classmethod
2763 @classmethod
2769 def create(cls, user_group, repository_group, permission):
2764 def create(cls, user_group, repository_group, permission):
2770 n = cls()
2765 n = cls()
2771 n.users_group = user_group
2766 n.users_group = user_group
2772 n.group = repository_group
2767 n.group = repository_group
2773 n.permission = permission
2768 n.permission = permission
2774 Session().add(n)
2769 Session().add(n)
2775 return n
2770 return n
2776
2771
2777 def __unicode__(self):
2772 def __unicode__(self):
2778 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2773 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2779
2774
2780
2775
2781 class Statistics(Base, BaseModel):
2776 class Statistics(Base, BaseModel):
2782 __tablename__ = 'statistics'
2777 __tablename__ = 'statistics'
2783 __table_args__ = (
2778 __table_args__ = (
2784 UniqueConstraint('repository_id'),
2779 UniqueConstraint('repository_id'),
2785 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2780 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2786 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2781 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2787 )
2782 )
2788 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2783 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2789 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2784 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2790 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2785 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2791 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2786 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2792 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2787 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2793 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2788 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2794
2789
2795 repository = relationship('Repository', single_parent=True)
2790 repository = relationship('Repository', single_parent=True)
2796
2791
2797
2792
2798 class UserFollowing(Base, BaseModel):
2793 class UserFollowing(Base, BaseModel):
2799 __tablename__ = 'user_followings'
2794 __tablename__ = 'user_followings'
2800 __table_args__ = (
2795 __table_args__ = (
2801 UniqueConstraint('user_id', 'follows_repository_id'),
2796 UniqueConstraint('user_id', 'follows_repository_id'),
2802 UniqueConstraint('user_id', 'follows_user_id'),
2797 UniqueConstraint('user_id', 'follows_user_id'),
2803 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2798 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2804 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2799 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2805 )
2800 )
2806
2801
2807 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2802 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2808 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2803 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2809 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2804 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2810 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2805 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2811 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2806 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2812
2807
2813 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2808 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2814
2809
2815 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2810 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2816 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2811 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2817
2812
2818 @classmethod
2813 @classmethod
2819 def get_repo_followers(cls, repo_id):
2814 def get_repo_followers(cls, repo_id):
2820 return cls.query().filter(cls.follows_repo_id == repo_id)
2815 return cls.query().filter(cls.follows_repo_id == repo_id)
2821
2816
2822
2817
2823 class CacheKey(Base, BaseModel):
2818 class CacheKey(Base, BaseModel):
2824 __tablename__ = 'cache_invalidation'
2819 __tablename__ = 'cache_invalidation'
2825 __table_args__ = (
2820 __table_args__ = (
2826 UniqueConstraint('cache_key'),
2821 UniqueConstraint('cache_key'),
2827 Index('key_idx', 'cache_key'),
2822 Index('key_idx', 'cache_key'),
2828 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2823 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2829 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2824 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2830 )
2825 )
2831 CACHE_TYPE_ATOM = 'ATOM'
2826 CACHE_TYPE_ATOM = 'ATOM'
2832 CACHE_TYPE_RSS = 'RSS'
2827 CACHE_TYPE_RSS = 'RSS'
2833 CACHE_TYPE_README = 'README'
2828 CACHE_TYPE_README = 'README'
2834
2829
2835 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2830 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2836 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
2831 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
2837 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
2832 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
2838 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
2833 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
2839
2834
2840 def __init__(self, cache_key, cache_args=''):
2835 def __init__(self, cache_key, cache_args=''):
2841 self.cache_key = cache_key
2836 self.cache_key = cache_key
2842 self.cache_args = cache_args
2837 self.cache_args = cache_args
2843 self.cache_active = False
2838 self.cache_active = False
2844
2839
2845 def __unicode__(self):
2840 def __unicode__(self):
2846 return u"<%s('%s:%s[%s]')>" % (
2841 return u"<%s('%s:%s[%s]')>" % (
2847 self.__class__.__name__,
2842 self.__class__.__name__,
2848 self.cache_id, self.cache_key, self.cache_active)
2843 self.cache_id, self.cache_key, self.cache_active)
2849
2844
2850 def _cache_key_partition(self):
2845 def _cache_key_partition(self):
2851 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
2846 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
2852 return prefix, repo_name, suffix
2847 return prefix, repo_name, suffix
2853
2848
2854 def get_prefix(self):
2849 def get_prefix(self):
2855 """
2850 """
2856 Try to extract prefix from existing cache key. The key could consist
2851 Try to extract prefix from existing cache key. The key could consist
2857 of prefix, repo_name, suffix
2852 of prefix, repo_name, suffix
2858 """
2853 """
2859 # this returns prefix, repo_name, suffix
2854 # this returns prefix, repo_name, suffix
2860 return self._cache_key_partition()[0]
2855 return self._cache_key_partition()[0]
2861
2856
2862 def get_suffix(self):
2857 def get_suffix(self):
2863 """
2858 """
2864 get suffix that might have been used in _get_cache_key to
2859 get suffix that might have been used in _get_cache_key to
2865 generate self.cache_key. Only used for informational purposes
2860 generate self.cache_key. Only used for informational purposes
2866 in repo_edit.mako.
2861 in repo_edit.mako.
2867 """
2862 """
2868 # prefix, repo_name, suffix
2863 # prefix, repo_name, suffix
2869 return self._cache_key_partition()[2]
2864 return self._cache_key_partition()[2]
2870
2865
2871 @classmethod
2866 @classmethod
2872 def delete_all_cache(cls):
2867 def delete_all_cache(cls):
2873 """
2868 """
2874 Delete all cache keys from database.
2869 Delete all cache keys from database.
2875 Should only be run when all instances are down and all entries
2870 Should only be run when all instances are down and all entries
2876 thus stale.
2871 thus stale.
2877 """
2872 """
2878 cls.query().delete()
2873 cls.query().delete()
2879 Session().commit()
2874 Session().commit()
2880
2875
2881 @classmethod
2876 @classmethod
2882 def get_cache_key(cls, repo_name, cache_type):
2877 def get_cache_key(cls, repo_name, cache_type):
2883 """
2878 """
2884
2879
2885 Generate a cache key for this process of RhodeCode instance.
2880 Generate a cache key for this process of RhodeCode instance.
2886 Prefix most likely will be process id or maybe explicitly set
2881 Prefix most likely will be process id or maybe explicitly set
2887 instance_id from .ini file.
2882 instance_id from .ini file.
2888 """
2883 """
2889 import rhodecode
2884 import rhodecode
2890 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
2885 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
2891
2886
2892 repo_as_unicode = safe_unicode(repo_name)
2887 repo_as_unicode = safe_unicode(repo_name)
2893 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
2888 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
2894 if cache_type else repo_as_unicode
2889 if cache_type else repo_as_unicode
2895
2890
2896 return u'{}{}'.format(prefix, key)
2891 return u'{}{}'.format(prefix, key)
2897
2892
2898 @classmethod
2893 @classmethod
2899 def set_invalidate(cls, repo_name, delete=False):
2894 def set_invalidate(cls, repo_name, delete=False):
2900 """
2895 """
2901 Mark all caches of a repo as invalid in the database.
2896 Mark all caches of a repo as invalid in the database.
2902 """
2897 """
2903
2898
2904 try:
2899 try:
2905 qry = Session().query(cls).filter(cls.cache_args == repo_name)
2900 qry = Session().query(cls).filter(cls.cache_args == repo_name)
2906 if delete:
2901 if delete:
2907 log.debug('cache objects deleted for repo %s',
2902 log.debug('cache objects deleted for repo %s',
2908 safe_str(repo_name))
2903 safe_str(repo_name))
2909 qry.delete()
2904 qry.delete()
2910 else:
2905 else:
2911 log.debug('cache objects marked as invalid for repo %s',
2906 log.debug('cache objects marked as invalid for repo %s',
2912 safe_str(repo_name))
2907 safe_str(repo_name))
2913 qry.update({"cache_active": False})
2908 qry.update({"cache_active": False})
2914
2909
2915 Session().commit()
2910 Session().commit()
2916 except Exception:
2911 except Exception:
2917 log.exception(
2912 log.exception(
2918 'Cache key invalidation failed for repository %s',
2913 'Cache key invalidation failed for repository %s',
2919 safe_str(repo_name))
2914 safe_str(repo_name))
2920 Session().rollback()
2915 Session().rollback()
2921
2916
2922 @classmethod
2917 @classmethod
2923 def get_active_cache(cls, cache_key):
2918 def get_active_cache(cls, cache_key):
2924 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
2919 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
2925 if inv_obj:
2920 if inv_obj:
2926 return inv_obj
2921 return inv_obj
2927 return None
2922 return None
2928
2923
2929 @classmethod
2924 @classmethod
2930 def repo_context_cache(cls, compute_func, repo_name, cache_type,
2925 def repo_context_cache(cls, compute_func, repo_name, cache_type,
2931 thread_scoped=False):
2926 thread_scoped=False):
2932 """
2927 """
2933 @cache_region('long_term')
2928 @cache_region('long_term')
2934 def _heavy_calculation(cache_key):
2929 def _heavy_calculation(cache_key):
2935 return 'result'
2930 return 'result'
2936
2931
2937 cache_context = CacheKey.repo_context_cache(
2932 cache_context = CacheKey.repo_context_cache(
2938 _heavy_calculation, repo_name, cache_type)
2933 _heavy_calculation, repo_name, cache_type)
2939
2934
2940 with cache_context as context:
2935 with cache_context as context:
2941 context.invalidate()
2936 context.invalidate()
2942 computed = context.compute()
2937 computed = context.compute()
2943
2938
2944 assert computed == 'result'
2939 assert computed == 'result'
2945 """
2940 """
2946 from rhodecode.lib import caches
2941 from rhodecode.lib import caches
2947 return caches.InvalidationContext(
2942 return caches.InvalidationContext(
2948 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
2943 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
2949
2944
2950
2945
2951 class ChangesetComment(Base, BaseModel):
2946 class ChangesetComment(Base, BaseModel):
2952 __tablename__ = 'changeset_comments'
2947 __tablename__ = 'changeset_comments'
2953 __table_args__ = (
2948 __table_args__ = (
2954 Index('cc_revision_idx', 'revision'),
2949 Index('cc_revision_idx', 'revision'),
2955 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2950 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2956 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2951 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2957 )
2952 )
2958
2953
2959 COMMENT_OUTDATED = u'comment_outdated'
2954 COMMENT_OUTDATED = u'comment_outdated'
2960 COMMENT_TYPE_NOTE = u'note'
2955 COMMENT_TYPE_NOTE = u'note'
2961 COMMENT_TYPE_TODO = u'todo'
2956 COMMENT_TYPE_TODO = u'todo'
2962 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
2957 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
2963
2958
2964 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
2959 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
2965 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2960 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
2966 revision = Column('revision', String(40), nullable=True)
2961 revision = Column('revision', String(40), nullable=True)
2967 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2962 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
2968 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
2963 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
2969 line_no = Column('line_no', Unicode(10), nullable=True)
2964 line_no = Column('line_no', Unicode(10), nullable=True)
2970 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
2965 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
2971 f_path = Column('f_path', Unicode(1000), nullable=True)
2966 f_path = Column('f_path', Unicode(1000), nullable=True)
2972 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
2967 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
2973 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
2968 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
2974 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2969 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2975 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2970 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2976 renderer = Column('renderer', Unicode(64), nullable=True)
2971 renderer = Column('renderer', Unicode(64), nullable=True)
2977 display_state = Column('display_state', Unicode(128), nullable=True)
2972 display_state = Column('display_state', Unicode(128), nullable=True)
2978
2973
2979 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
2974 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
2980 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
2975 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
2981 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
2976 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
2982 author = relationship('User', lazy='joined')
2977 author = relationship('User', lazy='joined')
2983 repo = relationship('Repository')
2978 repo = relationship('Repository')
2984 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
2979 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
2985 pull_request = relationship('PullRequest', lazy='joined')
2980 pull_request = relationship('PullRequest', lazy='joined')
2986 pull_request_version = relationship('PullRequestVersion')
2981 pull_request_version = relationship('PullRequestVersion')
2987
2982
2988 @classmethod
2983 @classmethod
2989 def get_users(cls, revision=None, pull_request_id=None):
2984 def get_users(cls, revision=None, pull_request_id=None):
2990 """
2985 """
2991 Returns user associated with this ChangesetComment. ie those
2986 Returns user associated with this ChangesetComment. ie those
2992 who actually commented
2987 who actually commented
2993
2988
2994 :param cls:
2989 :param cls:
2995 :param revision:
2990 :param revision:
2996 """
2991 """
2997 q = Session().query(User)\
2992 q = Session().query(User)\
2998 .join(ChangesetComment.author)
2993 .join(ChangesetComment.author)
2999 if revision:
2994 if revision:
3000 q = q.filter(cls.revision == revision)
2995 q = q.filter(cls.revision == revision)
3001 elif pull_request_id:
2996 elif pull_request_id:
3002 q = q.filter(cls.pull_request_id == pull_request_id)
2997 q = q.filter(cls.pull_request_id == pull_request_id)
3003 return q.all()
2998 return q.all()
3004
2999
3005 @classmethod
3000 @classmethod
3006 def get_index_from_version(cls, pr_version, versions):
3001 def get_index_from_version(cls, pr_version, versions):
3007 num_versions = [x.pull_request_version_id for x in versions]
3002 num_versions = [x.pull_request_version_id for x in versions]
3008 try:
3003 try:
3009 return num_versions.index(pr_version) +1
3004 return num_versions.index(pr_version) +1
3010 except (IndexError, ValueError):
3005 except (IndexError, ValueError):
3011 return
3006 return
3012
3007
3013 @property
3008 @property
3014 def outdated(self):
3009 def outdated(self):
3015 return self.display_state == self.COMMENT_OUTDATED
3010 return self.display_state == self.COMMENT_OUTDATED
3016
3011
3017 def outdated_at_version(self, version):
3012 def outdated_at_version(self, version):
3018 """
3013 """
3019 Checks if comment is outdated for given pull request version
3014 Checks if comment is outdated for given pull request version
3020 """
3015 """
3021 return self.outdated and self.pull_request_version_id != version
3016 return self.outdated and self.pull_request_version_id != version
3022
3017
3023 def older_than_version(self, version):
3018 def older_than_version(self, version):
3024 """
3019 """
3025 Checks if comment is made from previous version than given
3020 Checks if comment is made from previous version than given
3026 """
3021 """
3027 if version is None:
3022 if version is None:
3028 return self.pull_request_version_id is not None
3023 return self.pull_request_version_id is not None
3029
3024
3030 return self.pull_request_version_id < version
3025 return self.pull_request_version_id < version
3031
3026
3032 @property
3027 @property
3033 def resolved(self):
3028 def resolved(self):
3034 return self.resolved_by[0] if self.resolved_by else None
3029 return self.resolved_by[0] if self.resolved_by else None
3035
3030
3036 @property
3031 @property
3037 def is_todo(self):
3032 def is_todo(self):
3038 return self.comment_type == self.COMMENT_TYPE_TODO
3033 return self.comment_type == self.COMMENT_TYPE_TODO
3039
3034
3040 def get_index_version(self, versions):
3035 def get_index_version(self, versions):
3041 return self.get_index_from_version(
3036 return self.get_index_from_version(
3042 self.pull_request_version_id, versions)
3037 self.pull_request_version_id, versions)
3043
3038
3044 def render(self, mentions=False):
3039 def render(self, mentions=False):
3045 from rhodecode.lib import helpers as h
3040 from rhodecode.lib import helpers as h
3046 return h.render(self.text, renderer=self.renderer, mentions=mentions)
3041 return h.render(self.text, renderer=self.renderer, mentions=mentions)
3047
3042
3048 def __repr__(self):
3043 def __repr__(self):
3049 if self.comment_id:
3044 if self.comment_id:
3050 return '<DB:Comment #%s>' % self.comment_id
3045 return '<DB:Comment #%s>' % self.comment_id
3051 else:
3046 else:
3052 return '<DB:Comment at %#x>' % id(self)
3047 return '<DB:Comment at %#x>' % id(self)
3053
3048
3054
3049
3055 class ChangesetStatus(Base, BaseModel):
3050 class ChangesetStatus(Base, BaseModel):
3056 __tablename__ = 'changeset_statuses'
3051 __tablename__ = 'changeset_statuses'
3057 __table_args__ = (
3052 __table_args__ = (
3058 Index('cs_revision_idx', 'revision'),
3053 Index('cs_revision_idx', 'revision'),
3059 Index('cs_version_idx', 'version'),
3054 Index('cs_version_idx', 'version'),
3060 UniqueConstraint('repo_id', 'revision', 'version'),
3055 UniqueConstraint('repo_id', 'revision', 'version'),
3061 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3056 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3062 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3057 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3063 )
3058 )
3064 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3059 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3065 STATUS_APPROVED = 'approved'
3060 STATUS_APPROVED = 'approved'
3066 STATUS_REJECTED = 'rejected'
3061 STATUS_REJECTED = 'rejected'
3067 STATUS_UNDER_REVIEW = 'under_review'
3062 STATUS_UNDER_REVIEW = 'under_review'
3068
3063
3069 STATUSES = [
3064 STATUSES = [
3070 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3065 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3071 (STATUS_APPROVED, _("Approved")),
3066 (STATUS_APPROVED, _("Approved")),
3072 (STATUS_REJECTED, _("Rejected")),
3067 (STATUS_REJECTED, _("Rejected")),
3073 (STATUS_UNDER_REVIEW, _("Under Review")),
3068 (STATUS_UNDER_REVIEW, _("Under Review")),
3074 ]
3069 ]
3075
3070
3076 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3071 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3077 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3072 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3078 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3073 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3079 revision = Column('revision', String(40), nullable=False)
3074 revision = Column('revision', String(40), nullable=False)
3080 status = Column('status', String(128), nullable=False, default=DEFAULT)
3075 status = Column('status', String(128), nullable=False, default=DEFAULT)
3081 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3076 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3082 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3077 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3083 version = Column('version', Integer(), nullable=False, default=0)
3078 version = Column('version', Integer(), nullable=False, default=0)
3084 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3079 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3085
3080
3086 author = relationship('User', lazy='joined')
3081 author = relationship('User', lazy='joined')
3087 repo = relationship('Repository')
3082 repo = relationship('Repository')
3088 comment = relationship('ChangesetComment', lazy='joined')
3083 comment = relationship('ChangesetComment', lazy='joined')
3089 pull_request = relationship('PullRequest', lazy='joined')
3084 pull_request = relationship('PullRequest', lazy='joined')
3090
3085
3091 def __unicode__(self):
3086 def __unicode__(self):
3092 return u"<%s('%s[v%s]:%s')>" % (
3087 return u"<%s('%s[v%s]:%s')>" % (
3093 self.__class__.__name__,
3088 self.__class__.__name__,
3094 self.status, self.version, self.author
3089 self.status, self.version, self.author
3095 )
3090 )
3096
3091
3097 @classmethod
3092 @classmethod
3098 def get_status_lbl(cls, value):
3093 def get_status_lbl(cls, value):
3099 return dict(cls.STATUSES).get(value)
3094 return dict(cls.STATUSES).get(value)
3100
3095
3101 @property
3096 @property
3102 def status_lbl(self):
3097 def status_lbl(self):
3103 return ChangesetStatus.get_status_lbl(self.status)
3098 return ChangesetStatus.get_status_lbl(self.status)
3104
3099
3105
3100
3106 class _PullRequestBase(BaseModel):
3101 class _PullRequestBase(BaseModel):
3107 """
3102 """
3108 Common attributes of pull request and version entries.
3103 Common attributes of pull request and version entries.
3109 """
3104 """
3110
3105
3111 # .status values
3106 # .status values
3112 STATUS_NEW = u'new'
3107 STATUS_NEW = u'new'
3113 STATUS_OPEN = u'open'
3108 STATUS_OPEN = u'open'
3114 STATUS_CLOSED = u'closed'
3109 STATUS_CLOSED = u'closed'
3115
3110
3116 title = Column('title', Unicode(255), nullable=True)
3111 title = Column('title', Unicode(255), nullable=True)
3117 description = Column(
3112 description = Column(
3118 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3113 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3119 nullable=True)
3114 nullable=True)
3120 # new/open/closed status of pull request (not approve/reject/etc)
3115 # new/open/closed status of pull request (not approve/reject/etc)
3121 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3116 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3122 created_on = Column(
3117 created_on = Column(
3123 'created_on', DateTime(timezone=False), nullable=False,
3118 'created_on', DateTime(timezone=False), nullable=False,
3124 default=datetime.datetime.now)
3119 default=datetime.datetime.now)
3125 updated_on = Column(
3120 updated_on = Column(
3126 'updated_on', DateTime(timezone=False), nullable=False,
3121 'updated_on', DateTime(timezone=False), nullable=False,
3127 default=datetime.datetime.now)
3122 default=datetime.datetime.now)
3128
3123
3129 @declared_attr
3124 @declared_attr
3130 def user_id(cls):
3125 def user_id(cls):
3131 return Column(
3126 return Column(
3132 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3127 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3133 unique=None)
3128 unique=None)
3134
3129
3135 # 500 revisions max
3130 # 500 revisions max
3136 _revisions = Column(
3131 _revisions = Column(
3137 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3132 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3138
3133
3139 @declared_attr
3134 @declared_attr
3140 def source_repo_id(cls):
3135 def source_repo_id(cls):
3141 # TODO: dan: rename column to source_repo_id
3136 # TODO: dan: rename column to source_repo_id
3142 return Column(
3137 return Column(
3143 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3138 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3144 nullable=False)
3139 nullable=False)
3145
3140
3146 source_ref = Column('org_ref', Unicode(255), nullable=False)
3141 source_ref = Column('org_ref', Unicode(255), nullable=False)
3147
3142
3148 @declared_attr
3143 @declared_attr
3149 def target_repo_id(cls):
3144 def target_repo_id(cls):
3150 # TODO: dan: rename column to target_repo_id
3145 # TODO: dan: rename column to target_repo_id
3151 return Column(
3146 return Column(
3152 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3147 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3153 nullable=False)
3148 nullable=False)
3154
3149
3155 target_ref = Column('other_ref', Unicode(255), nullable=False)
3150 target_ref = Column('other_ref', Unicode(255), nullable=False)
3156 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3151 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3157
3152
3158 # TODO: dan: rename column to last_merge_source_rev
3153 # TODO: dan: rename column to last_merge_source_rev
3159 _last_merge_source_rev = Column(
3154 _last_merge_source_rev = Column(
3160 'last_merge_org_rev', String(40), nullable=True)
3155 'last_merge_org_rev', String(40), nullable=True)
3161 # TODO: dan: rename column to last_merge_target_rev
3156 # TODO: dan: rename column to last_merge_target_rev
3162 _last_merge_target_rev = Column(
3157 _last_merge_target_rev = Column(
3163 'last_merge_other_rev', String(40), nullable=True)
3158 'last_merge_other_rev', String(40), nullable=True)
3164 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3159 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3165 merge_rev = Column('merge_rev', String(40), nullable=True)
3160 merge_rev = Column('merge_rev', String(40), nullable=True)
3166
3161
3167 @hybrid_property
3162 @hybrid_property
3168 def revisions(self):
3163 def revisions(self):
3169 return self._revisions.split(':') if self._revisions else []
3164 return self._revisions.split(':') if self._revisions else []
3170
3165
3171 @revisions.setter
3166 @revisions.setter
3172 def revisions(self, val):
3167 def revisions(self, val):
3173 self._revisions = ':'.join(val)
3168 self._revisions = ':'.join(val)
3174
3169
3175 @declared_attr
3170 @declared_attr
3176 def author(cls):
3171 def author(cls):
3177 return relationship('User', lazy='joined')
3172 return relationship('User', lazy='joined')
3178
3173
3179 @declared_attr
3174 @declared_attr
3180 def source_repo(cls):
3175 def source_repo(cls):
3181 return relationship(
3176 return relationship(
3182 'Repository',
3177 'Repository',
3183 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3178 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3184
3179
3185 @property
3180 @property
3186 def source_ref_parts(self):
3181 def source_ref_parts(self):
3187 return self.unicode_to_reference(self.source_ref)
3182 return self.unicode_to_reference(self.source_ref)
3188
3183
3189 @declared_attr
3184 @declared_attr
3190 def target_repo(cls):
3185 def target_repo(cls):
3191 return relationship(
3186 return relationship(
3192 'Repository',
3187 'Repository',
3193 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3188 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3194
3189
3195 @property
3190 @property
3196 def target_ref_parts(self):
3191 def target_ref_parts(self):
3197 return self.unicode_to_reference(self.target_ref)
3192 return self.unicode_to_reference(self.target_ref)
3198
3193
3199 @property
3194 @property
3200 def shadow_merge_ref(self):
3195 def shadow_merge_ref(self):
3201 return self.unicode_to_reference(self._shadow_merge_ref)
3196 return self.unicode_to_reference(self._shadow_merge_ref)
3202
3197
3203 @shadow_merge_ref.setter
3198 @shadow_merge_ref.setter
3204 def shadow_merge_ref(self, ref):
3199 def shadow_merge_ref(self, ref):
3205 self._shadow_merge_ref = self.reference_to_unicode(ref)
3200 self._shadow_merge_ref = self.reference_to_unicode(ref)
3206
3201
3207 def unicode_to_reference(self, raw):
3202 def unicode_to_reference(self, raw):
3208 """
3203 """
3209 Convert a unicode (or string) to a reference object.
3204 Convert a unicode (or string) to a reference object.
3210 If unicode evaluates to False it returns None.
3205 If unicode evaluates to False it returns None.
3211 """
3206 """
3212 if raw:
3207 if raw:
3213 refs = raw.split(':')
3208 refs = raw.split(':')
3214 return Reference(*refs)
3209 return Reference(*refs)
3215 else:
3210 else:
3216 return None
3211 return None
3217
3212
3218 def reference_to_unicode(self, ref):
3213 def reference_to_unicode(self, ref):
3219 """
3214 """
3220 Convert a reference object to unicode.
3215 Convert a reference object to unicode.
3221 If reference is None it returns None.
3216 If reference is None it returns None.
3222 """
3217 """
3223 if ref:
3218 if ref:
3224 return u':'.join(ref)
3219 return u':'.join(ref)
3225 else:
3220 else:
3226 return None
3221 return None
3227
3222
3228 def get_api_data(self):
3223 def get_api_data(self):
3229 from rhodecode.model.pull_request import PullRequestModel
3224 from rhodecode.model.pull_request import PullRequestModel
3230 pull_request = self
3225 pull_request = self
3231 merge_status = PullRequestModel().merge_status(pull_request)
3226 merge_status = PullRequestModel().merge_status(pull_request)
3232
3227
3233 pull_request_url = url(
3228 pull_request_url = url(
3234 'pullrequest_show', repo_name=self.target_repo.repo_name,
3229 'pullrequest_show', repo_name=self.target_repo.repo_name,
3235 pull_request_id=self.pull_request_id, qualified=True)
3230 pull_request_id=self.pull_request_id, qualified=True)
3236
3231
3237 merge_data = {
3232 merge_data = {
3238 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3233 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3239 'reference': (
3234 'reference': (
3240 pull_request.shadow_merge_ref._asdict()
3235 pull_request.shadow_merge_ref._asdict()
3241 if pull_request.shadow_merge_ref else None),
3236 if pull_request.shadow_merge_ref else None),
3242 }
3237 }
3243
3238
3244 data = {
3239 data = {
3245 'pull_request_id': pull_request.pull_request_id,
3240 'pull_request_id': pull_request.pull_request_id,
3246 'url': pull_request_url,
3241 'url': pull_request_url,
3247 'title': pull_request.title,
3242 'title': pull_request.title,
3248 'description': pull_request.description,
3243 'description': pull_request.description,
3249 'status': pull_request.status,
3244 'status': pull_request.status,
3250 'created_on': pull_request.created_on,
3245 'created_on': pull_request.created_on,
3251 'updated_on': pull_request.updated_on,
3246 'updated_on': pull_request.updated_on,
3252 'commit_ids': pull_request.revisions,
3247 'commit_ids': pull_request.revisions,
3253 'review_status': pull_request.calculated_review_status(),
3248 'review_status': pull_request.calculated_review_status(),
3254 'mergeable': {
3249 'mergeable': {
3255 'status': merge_status[0],
3250 'status': merge_status[0],
3256 'message': unicode(merge_status[1]),
3251 'message': unicode(merge_status[1]),
3257 },
3252 },
3258 'source': {
3253 'source': {
3259 'clone_url': pull_request.source_repo.clone_url(),
3254 'clone_url': pull_request.source_repo.clone_url(),
3260 'repository': pull_request.source_repo.repo_name,
3255 'repository': pull_request.source_repo.repo_name,
3261 'reference': {
3256 'reference': {
3262 'name': pull_request.source_ref_parts.name,
3257 'name': pull_request.source_ref_parts.name,
3263 'type': pull_request.source_ref_parts.type,
3258 'type': pull_request.source_ref_parts.type,
3264 'commit_id': pull_request.source_ref_parts.commit_id,
3259 'commit_id': pull_request.source_ref_parts.commit_id,
3265 },
3260 },
3266 },
3261 },
3267 'target': {
3262 'target': {
3268 'clone_url': pull_request.target_repo.clone_url(),
3263 'clone_url': pull_request.target_repo.clone_url(),
3269 'repository': pull_request.target_repo.repo_name,
3264 'repository': pull_request.target_repo.repo_name,
3270 'reference': {
3265 'reference': {
3271 'name': pull_request.target_ref_parts.name,
3266 'name': pull_request.target_ref_parts.name,
3272 'type': pull_request.target_ref_parts.type,
3267 'type': pull_request.target_ref_parts.type,
3273 'commit_id': pull_request.target_ref_parts.commit_id,
3268 'commit_id': pull_request.target_ref_parts.commit_id,
3274 },
3269 },
3275 },
3270 },
3276 'merge': merge_data,
3271 'merge': merge_data,
3277 'author': pull_request.author.get_api_data(include_secrets=False,
3272 'author': pull_request.author.get_api_data(include_secrets=False,
3278 details='basic'),
3273 details='basic'),
3279 'reviewers': [
3274 'reviewers': [
3280 {
3275 {
3281 'user': reviewer.get_api_data(include_secrets=False,
3276 'user': reviewer.get_api_data(include_secrets=False,
3282 details='basic'),
3277 details='basic'),
3283 'reasons': reasons,
3278 'reasons': reasons,
3284 'review_status': st[0][1].status if st else 'not_reviewed',
3279 'review_status': st[0][1].status if st else 'not_reviewed',
3285 }
3280 }
3286 for reviewer, reasons, st in pull_request.reviewers_statuses()
3281 for reviewer, reasons, st in pull_request.reviewers_statuses()
3287 ]
3282 ]
3288 }
3283 }
3289
3284
3290 return data
3285 return data
3291
3286
3292
3287
3293 class PullRequest(Base, _PullRequestBase):
3288 class PullRequest(Base, _PullRequestBase):
3294 __tablename__ = 'pull_requests'
3289 __tablename__ = 'pull_requests'
3295 __table_args__ = (
3290 __table_args__ = (
3296 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3291 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3297 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3292 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3298 )
3293 )
3299
3294
3300 pull_request_id = Column(
3295 pull_request_id = Column(
3301 'pull_request_id', Integer(), nullable=False, primary_key=True)
3296 'pull_request_id', Integer(), nullable=False, primary_key=True)
3302
3297
3303 def __repr__(self):
3298 def __repr__(self):
3304 if self.pull_request_id:
3299 if self.pull_request_id:
3305 return '<DB:PullRequest #%s>' % self.pull_request_id
3300 return '<DB:PullRequest #%s>' % self.pull_request_id
3306 else:
3301 else:
3307 return '<DB:PullRequest at %#x>' % id(self)
3302 return '<DB:PullRequest at %#x>' % id(self)
3308
3303
3309 reviewers = relationship('PullRequestReviewers',
3304 reviewers = relationship('PullRequestReviewers',
3310 cascade="all, delete, delete-orphan")
3305 cascade="all, delete, delete-orphan")
3311 statuses = relationship('ChangesetStatus')
3306 statuses = relationship('ChangesetStatus')
3312 comments = relationship('ChangesetComment',
3307 comments = relationship('ChangesetComment',
3313 cascade="all, delete, delete-orphan")
3308 cascade="all, delete, delete-orphan")
3314 versions = relationship('PullRequestVersion',
3309 versions = relationship('PullRequestVersion',
3315 cascade="all, delete, delete-orphan",
3310 cascade="all, delete, delete-orphan",
3316 lazy='dynamic')
3311 lazy='dynamic')
3317
3312
3318 @classmethod
3313 @classmethod
3319 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3314 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3320 internal_methods=None):
3315 internal_methods=None):
3321
3316
3322 class PullRequestDisplay(object):
3317 class PullRequestDisplay(object):
3323 """
3318 """
3324 Special object wrapper for showing PullRequest data via Versions
3319 Special object wrapper for showing PullRequest data via Versions
3325 It mimics PR object as close as possible. This is read only object
3320 It mimics PR object as close as possible. This is read only object
3326 just for display
3321 just for display
3327 """
3322 """
3328
3323
3329 def __init__(self, attrs, internal=None):
3324 def __init__(self, attrs, internal=None):
3330 self.attrs = attrs
3325 self.attrs = attrs
3331 # internal have priority over the given ones via attrs
3326 # internal have priority over the given ones via attrs
3332 self.internal = internal or ['versions']
3327 self.internal = internal or ['versions']
3333
3328
3334 def __getattr__(self, item):
3329 def __getattr__(self, item):
3335 if item in self.internal:
3330 if item in self.internal:
3336 return getattr(self, item)
3331 return getattr(self, item)
3337 try:
3332 try:
3338 return self.attrs[item]
3333 return self.attrs[item]
3339 except KeyError:
3334 except KeyError:
3340 raise AttributeError(
3335 raise AttributeError(
3341 '%s object has no attribute %s' % (self, item))
3336 '%s object has no attribute %s' % (self, item))
3342
3337
3343 def __repr__(self):
3338 def __repr__(self):
3344 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3339 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3345
3340
3346 def versions(self):
3341 def versions(self):
3347 return pull_request_obj.versions.order_by(
3342 return pull_request_obj.versions.order_by(
3348 PullRequestVersion.pull_request_version_id).all()
3343 PullRequestVersion.pull_request_version_id).all()
3349
3344
3350 def is_closed(self):
3345 def is_closed(self):
3351 return pull_request_obj.is_closed()
3346 return pull_request_obj.is_closed()
3352
3347
3353 @property
3348 @property
3354 def pull_request_version_id(self):
3349 def pull_request_version_id(self):
3355 return getattr(pull_request_obj, 'pull_request_version_id', None)
3350 return getattr(pull_request_obj, 'pull_request_version_id', None)
3356
3351
3357 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3352 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3358
3353
3359 attrs.author = StrictAttributeDict(
3354 attrs.author = StrictAttributeDict(
3360 pull_request_obj.author.get_api_data())
3355 pull_request_obj.author.get_api_data())
3361 if pull_request_obj.target_repo:
3356 if pull_request_obj.target_repo:
3362 attrs.target_repo = StrictAttributeDict(
3357 attrs.target_repo = StrictAttributeDict(
3363 pull_request_obj.target_repo.get_api_data())
3358 pull_request_obj.target_repo.get_api_data())
3364 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3359 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3365
3360
3366 if pull_request_obj.source_repo:
3361 if pull_request_obj.source_repo:
3367 attrs.source_repo = StrictAttributeDict(
3362 attrs.source_repo = StrictAttributeDict(
3368 pull_request_obj.source_repo.get_api_data())
3363 pull_request_obj.source_repo.get_api_data())
3369 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3364 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3370
3365
3371 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3366 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3372 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3367 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3373 attrs.revisions = pull_request_obj.revisions
3368 attrs.revisions = pull_request_obj.revisions
3374
3369
3375 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3370 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3376
3371
3377 return PullRequestDisplay(attrs, internal=internal_methods)
3372 return PullRequestDisplay(attrs, internal=internal_methods)
3378
3373
3379 def is_closed(self):
3374 def is_closed(self):
3380 return self.status == self.STATUS_CLOSED
3375 return self.status == self.STATUS_CLOSED
3381
3376
3382 def __json__(self):
3377 def __json__(self):
3383 return {
3378 return {
3384 'revisions': self.revisions,
3379 'revisions': self.revisions,
3385 }
3380 }
3386
3381
3387 def calculated_review_status(self):
3382 def calculated_review_status(self):
3388 from rhodecode.model.changeset_status import ChangesetStatusModel
3383 from rhodecode.model.changeset_status import ChangesetStatusModel
3389 return ChangesetStatusModel().calculated_review_status(self)
3384 return ChangesetStatusModel().calculated_review_status(self)
3390
3385
3391 def reviewers_statuses(self):
3386 def reviewers_statuses(self):
3392 from rhodecode.model.changeset_status import ChangesetStatusModel
3387 from rhodecode.model.changeset_status import ChangesetStatusModel
3393 return ChangesetStatusModel().reviewers_statuses(self)
3388 return ChangesetStatusModel().reviewers_statuses(self)
3394
3389
3395 @property
3390 @property
3396 def workspace_id(self):
3391 def workspace_id(self):
3397 from rhodecode.model.pull_request import PullRequestModel
3392 from rhodecode.model.pull_request import PullRequestModel
3398 return PullRequestModel()._workspace_id(self)
3393 return PullRequestModel()._workspace_id(self)
3399
3394
3400 def get_shadow_repo(self):
3395 def get_shadow_repo(self):
3401 workspace_id = self.workspace_id
3396 workspace_id = self.workspace_id
3402 vcs_obj = self.target_repo.scm_instance()
3397 vcs_obj = self.target_repo.scm_instance()
3403 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3398 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3404 workspace_id)
3399 workspace_id)
3405 return vcs_obj._get_shadow_instance(shadow_repository_path)
3400 return vcs_obj._get_shadow_instance(shadow_repository_path)
3406
3401
3407
3402
3408 class PullRequestVersion(Base, _PullRequestBase):
3403 class PullRequestVersion(Base, _PullRequestBase):
3409 __tablename__ = 'pull_request_versions'
3404 __tablename__ = 'pull_request_versions'
3410 __table_args__ = (
3405 __table_args__ = (
3411 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3406 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3412 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3407 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3413 )
3408 )
3414
3409
3415 pull_request_version_id = Column(
3410 pull_request_version_id = Column(
3416 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3411 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3417 pull_request_id = Column(
3412 pull_request_id = Column(
3418 'pull_request_id', Integer(),
3413 'pull_request_id', Integer(),
3419 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3414 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3420 pull_request = relationship('PullRequest')
3415 pull_request = relationship('PullRequest')
3421
3416
3422 def __repr__(self):
3417 def __repr__(self):
3423 if self.pull_request_version_id:
3418 if self.pull_request_version_id:
3424 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3419 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3425 else:
3420 else:
3426 return '<DB:PullRequestVersion at %#x>' % id(self)
3421 return '<DB:PullRequestVersion at %#x>' % id(self)
3427
3422
3428 @property
3423 @property
3429 def reviewers(self):
3424 def reviewers(self):
3430 return self.pull_request.reviewers
3425 return self.pull_request.reviewers
3431
3426
3432 @property
3427 @property
3433 def versions(self):
3428 def versions(self):
3434 return self.pull_request.versions
3429 return self.pull_request.versions
3435
3430
3436 def is_closed(self):
3431 def is_closed(self):
3437 # calculate from original
3432 # calculate from original
3438 return self.pull_request.status == self.STATUS_CLOSED
3433 return self.pull_request.status == self.STATUS_CLOSED
3439
3434
3440 def calculated_review_status(self):
3435 def calculated_review_status(self):
3441 return self.pull_request.calculated_review_status()
3436 return self.pull_request.calculated_review_status()
3442
3437
3443 def reviewers_statuses(self):
3438 def reviewers_statuses(self):
3444 return self.pull_request.reviewers_statuses()
3439 return self.pull_request.reviewers_statuses()
3445
3440
3446
3441
3447 class PullRequestReviewers(Base, BaseModel):
3442 class PullRequestReviewers(Base, BaseModel):
3448 __tablename__ = 'pull_request_reviewers'
3443 __tablename__ = 'pull_request_reviewers'
3449 __table_args__ = (
3444 __table_args__ = (
3450 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3445 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3451 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3446 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3452 )
3447 )
3453
3448
3454 def __init__(self, user=None, pull_request=None, reasons=None):
3449 def __init__(self, user=None, pull_request=None, reasons=None):
3455 self.user = user
3450 self.user = user
3456 self.pull_request = pull_request
3451 self.pull_request = pull_request
3457 self.reasons = reasons or []
3452 self.reasons = reasons or []
3458
3453
3459 @hybrid_property
3454 @hybrid_property
3460 def reasons(self):
3455 def reasons(self):
3461 if not self._reasons:
3456 if not self._reasons:
3462 return []
3457 return []
3463 return self._reasons
3458 return self._reasons
3464
3459
3465 @reasons.setter
3460 @reasons.setter
3466 def reasons(self, val):
3461 def reasons(self, val):
3467 val = val or []
3462 val = val or []
3468 if any(not isinstance(x, basestring) for x in val):
3463 if any(not isinstance(x, basestring) for x in val):
3469 raise Exception('invalid reasons type, must be list of strings')
3464 raise Exception('invalid reasons type, must be list of strings')
3470 self._reasons = val
3465 self._reasons = val
3471
3466
3472 pull_requests_reviewers_id = Column(
3467 pull_requests_reviewers_id = Column(
3473 'pull_requests_reviewers_id', Integer(), nullable=False,
3468 'pull_requests_reviewers_id', Integer(), nullable=False,
3474 primary_key=True)
3469 primary_key=True)
3475 pull_request_id = Column(
3470 pull_request_id = Column(
3476 "pull_request_id", Integer(),
3471 "pull_request_id", Integer(),
3477 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3472 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3478 user_id = Column(
3473 user_id = Column(
3479 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3474 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3480 _reasons = Column(
3475 _reasons = Column(
3481 'reason', MutationList.as_mutable(
3476 'reason', MutationList.as_mutable(
3482 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3477 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3483
3478
3484 user = relationship('User')
3479 user = relationship('User')
3485 pull_request = relationship('PullRequest')
3480 pull_request = relationship('PullRequest')
3486
3481
3487
3482
3488 class Notification(Base, BaseModel):
3483 class Notification(Base, BaseModel):
3489 __tablename__ = 'notifications'
3484 __tablename__ = 'notifications'
3490 __table_args__ = (
3485 __table_args__ = (
3491 Index('notification_type_idx', 'type'),
3486 Index('notification_type_idx', 'type'),
3492 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3487 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3493 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3488 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3494 )
3489 )
3495
3490
3496 TYPE_CHANGESET_COMMENT = u'cs_comment'
3491 TYPE_CHANGESET_COMMENT = u'cs_comment'
3497 TYPE_MESSAGE = u'message'
3492 TYPE_MESSAGE = u'message'
3498 TYPE_MENTION = u'mention'
3493 TYPE_MENTION = u'mention'
3499 TYPE_REGISTRATION = u'registration'
3494 TYPE_REGISTRATION = u'registration'
3500 TYPE_PULL_REQUEST = u'pull_request'
3495 TYPE_PULL_REQUEST = u'pull_request'
3501 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3496 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3502
3497
3503 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3498 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3504 subject = Column('subject', Unicode(512), nullable=True)
3499 subject = Column('subject', Unicode(512), nullable=True)
3505 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3500 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3506 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3501 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3507 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3502 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3508 type_ = Column('type', Unicode(255))
3503 type_ = Column('type', Unicode(255))
3509
3504
3510 created_by_user = relationship('User')
3505 created_by_user = relationship('User')
3511 notifications_to_users = relationship('UserNotification', lazy='joined',
3506 notifications_to_users = relationship('UserNotification', lazy='joined',
3512 cascade="all, delete, delete-orphan")
3507 cascade="all, delete, delete-orphan")
3513
3508
3514 @property
3509 @property
3515 def recipients(self):
3510 def recipients(self):
3516 return [x.user for x in UserNotification.query()\
3511 return [x.user for x in UserNotification.query()\
3517 .filter(UserNotification.notification == self)\
3512 .filter(UserNotification.notification == self)\
3518 .order_by(UserNotification.user_id.asc()).all()]
3513 .order_by(UserNotification.user_id.asc()).all()]
3519
3514
3520 @classmethod
3515 @classmethod
3521 def create(cls, created_by, subject, body, recipients, type_=None):
3516 def create(cls, created_by, subject, body, recipients, type_=None):
3522 if type_ is None:
3517 if type_ is None:
3523 type_ = Notification.TYPE_MESSAGE
3518 type_ = Notification.TYPE_MESSAGE
3524
3519
3525 notification = cls()
3520 notification = cls()
3526 notification.created_by_user = created_by
3521 notification.created_by_user = created_by
3527 notification.subject = subject
3522 notification.subject = subject
3528 notification.body = body
3523 notification.body = body
3529 notification.type_ = type_
3524 notification.type_ = type_
3530 notification.created_on = datetime.datetime.now()
3525 notification.created_on = datetime.datetime.now()
3531
3526
3532 for u in recipients:
3527 for u in recipients:
3533 assoc = UserNotification()
3528 assoc = UserNotification()
3534 assoc.notification = notification
3529 assoc.notification = notification
3535
3530
3536 # if created_by is inside recipients mark his notification
3531 # if created_by is inside recipients mark his notification
3537 # as read
3532 # as read
3538 if u.user_id == created_by.user_id:
3533 if u.user_id == created_by.user_id:
3539 assoc.read = True
3534 assoc.read = True
3540
3535
3541 u.notifications.append(assoc)
3536 u.notifications.append(assoc)
3542 Session().add(notification)
3537 Session().add(notification)
3543
3538
3544 return notification
3539 return notification
3545
3540
3546 @property
3541 @property
3547 def description(self):
3542 def description(self):
3548 from rhodecode.model.notification import NotificationModel
3543 from rhodecode.model.notification import NotificationModel
3549 return NotificationModel().make_description(self)
3544 return NotificationModel().make_description(self)
3550
3545
3551
3546
3552 class UserNotification(Base, BaseModel):
3547 class UserNotification(Base, BaseModel):
3553 __tablename__ = 'user_to_notification'
3548 __tablename__ = 'user_to_notification'
3554 __table_args__ = (
3549 __table_args__ = (
3555 UniqueConstraint('user_id', 'notification_id'),
3550 UniqueConstraint('user_id', 'notification_id'),
3556 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3551 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3557 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3552 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3558 )
3553 )
3559 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3554 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3560 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3555 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3561 read = Column('read', Boolean, default=False)
3556 read = Column('read', Boolean, default=False)
3562 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3557 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3563
3558
3564 user = relationship('User', lazy="joined")
3559 user = relationship('User', lazy="joined")
3565 notification = relationship('Notification', lazy="joined",
3560 notification = relationship('Notification', lazy="joined",
3566 order_by=lambda: Notification.created_on.desc(),)
3561 order_by=lambda: Notification.created_on.desc(),)
3567
3562
3568 def mark_as_read(self):
3563 def mark_as_read(self):
3569 self.read = True
3564 self.read = True
3570 Session().add(self)
3565 Session().add(self)
3571
3566
3572
3567
3573 class Gist(Base, BaseModel):
3568 class Gist(Base, BaseModel):
3574 __tablename__ = 'gists'
3569 __tablename__ = 'gists'
3575 __table_args__ = (
3570 __table_args__ = (
3576 Index('g_gist_access_id_idx', 'gist_access_id'),
3571 Index('g_gist_access_id_idx', 'gist_access_id'),
3577 Index('g_created_on_idx', 'created_on'),
3572 Index('g_created_on_idx', 'created_on'),
3578 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3573 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3579 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3574 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3580 )
3575 )
3581 GIST_PUBLIC = u'public'
3576 GIST_PUBLIC = u'public'
3582 GIST_PRIVATE = u'private'
3577 GIST_PRIVATE = u'private'
3583 DEFAULT_FILENAME = u'gistfile1.txt'
3578 DEFAULT_FILENAME = u'gistfile1.txt'
3584
3579
3585 ACL_LEVEL_PUBLIC = u'acl_public'
3580 ACL_LEVEL_PUBLIC = u'acl_public'
3586 ACL_LEVEL_PRIVATE = u'acl_private'
3581 ACL_LEVEL_PRIVATE = u'acl_private'
3587
3582
3588 gist_id = Column('gist_id', Integer(), primary_key=True)
3583 gist_id = Column('gist_id', Integer(), primary_key=True)
3589 gist_access_id = Column('gist_access_id', Unicode(250))
3584 gist_access_id = Column('gist_access_id', Unicode(250))
3590 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3585 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3591 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3586 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3592 gist_expires = Column('gist_expires', Float(53), nullable=False)
3587 gist_expires = Column('gist_expires', Float(53), nullable=False)
3593 gist_type = Column('gist_type', Unicode(128), nullable=False)
3588 gist_type = Column('gist_type', Unicode(128), nullable=False)
3594 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3589 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3595 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3590 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3596 acl_level = Column('acl_level', Unicode(128), nullable=True)
3591 acl_level = Column('acl_level', Unicode(128), nullable=True)
3597
3592
3598 owner = relationship('User')
3593 owner = relationship('User')
3599
3594
3600 def __repr__(self):
3595 def __repr__(self):
3601 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3596 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3602
3597
3603 @classmethod
3598 @classmethod
3604 def get_or_404(cls, id_):
3599 def get_or_404(cls, id_):
3605 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3600 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3606 if not res:
3601 if not res:
3607 raise HTTPNotFound
3602 raise HTTPNotFound
3608 return res
3603 return res
3609
3604
3610 @classmethod
3605 @classmethod
3611 def get_by_access_id(cls, gist_access_id):
3606 def get_by_access_id(cls, gist_access_id):
3612 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3607 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3613
3608
3614 def gist_url(self):
3609 def gist_url(self):
3615 import rhodecode
3610 import rhodecode
3616 alias_url = rhodecode.CONFIG.get('gist_alias_url')
3611 alias_url = rhodecode.CONFIG.get('gist_alias_url')
3617 if alias_url:
3612 if alias_url:
3618 return alias_url.replace('{gistid}', self.gist_access_id)
3613 return alias_url.replace('{gistid}', self.gist_access_id)
3619
3614
3620 return url('gist', gist_id=self.gist_access_id, qualified=True)
3615 return url('gist', gist_id=self.gist_access_id, qualified=True)
3621
3616
3622 @classmethod
3617 @classmethod
3623 def base_path(cls):
3618 def base_path(cls):
3624 """
3619 """
3625 Returns base path when all gists are stored
3620 Returns base path when all gists are stored
3626
3621
3627 :param cls:
3622 :param cls:
3628 """
3623 """
3629 from rhodecode.model.gist import GIST_STORE_LOC
3624 from rhodecode.model.gist import GIST_STORE_LOC
3630 q = Session().query(RhodeCodeUi)\
3625 q = Session().query(RhodeCodeUi)\
3631 .filter(RhodeCodeUi.ui_key == URL_SEP)
3626 .filter(RhodeCodeUi.ui_key == URL_SEP)
3632 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3627 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3633 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3628 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3634
3629
3635 def get_api_data(self):
3630 def get_api_data(self):
3636 """
3631 """
3637 Common function for generating gist related data for API
3632 Common function for generating gist related data for API
3638 """
3633 """
3639 gist = self
3634 gist = self
3640 data = {
3635 data = {
3641 'gist_id': gist.gist_id,
3636 'gist_id': gist.gist_id,
3642 'type': gist.gist_type,
3637 'type': gist.gist_type,
3643 'access_id': gist.gist_access_id,
3638 'access_id': gist.gist_access_id,
3644 'description': gist.gist_description,
3639 'description': gist.gist_description,
3645 'url': gist.gist_url(),
3640 'url': gist.gist_url(),
3646 'expires': gist.gist_expires,
3641 'expires': gist.gist_expires,
3647 'created_on': gist.created_on,
3642 'created_on': gist.created_on,
3648 'modified_at': gist.modified_at,
3643 'modified_at': gist.modified_at,
3649 'content': None,
3644 'content': None,
3650 'acl_level': gist.acl_level,
3645 'acl_level': gist.acl_level,
3651 }
3646 }
3652 return data
3647 return data
3653
3648
3654 def __json__(self):
3649 def __json__(self):
3655 data = dict(
3650 data = dict(
3656 )
3651 )
3657 data.update(self.get_api_data())
3652 data.update(self.get_api_data())
3658 return data
3653 return data
3659 # SCM functions
3654 # SCM functions
3660
3655
3661 def scm_instance(self, **kwargs):
3656 def scm_instance(self, **kwargs):
3662 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3657 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3663 return get_vcs_instance(
3658 return get_vcs_instance(
3664 repo_path=safe_str(full_repo_path), create=False)
3659 repo_path=safe_str(full_repo_path), create=False)
3665
3660
3666
3661
3667 class ExternalIdentity(Base, BaseModel):
3662 class ExternalIdentity(Base, BaseModel):
3668 __tablename__ = 'external_identities'
3663 __tablename__ = 'external_identities'
3669 __table_args__ = (
3664 __table_args__ = (
3670 Index('local_user_id_idx', 'local_user_id'),
3665 Index('local_user_id_idx', 'local_user_id'),
3671 Index('external_id_idx', 'external_id'),
3666 Index('external_id_idx', 'external_id'),
3672 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3667 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3673 'mysql_charset': 'utf8'})
3668 'mysql_charset': 'utf8'})
3674
3669
3675 external_id = Column('external_id', Unicode(255), default=u'',
3670 external_id = Column('external_id', Unicode(255), default=u'',
3676 primary_key=True)
3671 primary_key=True)
3677 external_username = Column('external_username', Unicode(1024), default=u'')
3672 external_username = Column('external_username', Unicode(1024), default=u'')
3678 local_user_id = Column('local_user_id', Integer(),
3673 local_user_id = Column('local_user_id', Integer(),
3679 ForeignKey('users.user_id'), primary_key=True)
3674 ForeignKey('users.user_id'), primary_key=True)
3680 provider_name = Column('provider_name', Unicode(255), default=u'',
3675 provider_name = Column('provider_name', Unicode(255), default=u'',
3681 primary_key=True)
3676 primary_key=True)
3682 access_token = Column('access_token', String(1024), default=u'')
3677 access_token = Column('access_token', String(1024), default=u'')
3683 alt_token = Column('alt_token', String(1024), default=u'')
3678 alt_token = Column('alt_token', String(1024), default=u'')
3684 token_secret = Column('token_secret', String(1024), default=u'')
3679 token_secret = Column('token_secret', String(1024), default=u'')
3685
3680
3686 @classmethod
3681 @classmethod
3687 def by_external_id_and_provider(cls, external_id, provider_name,
3682 def by_external_id_and_provider(cls, external_id, provider_name,
3688 local_user_id=None):
3683 local_user_id=None):
3689 """
3684 """
3690 Returns ExternalIdentity instance based on search params
3685 Returns ExternalIdentity instance based on search params
3691
3686
3692 :param external_id:
3687 :param external_id:
3693 :param provider_name:
3688 :param provider_name:
3694 :return: ExternalIdentity
3689 :return: ExternalIdentity
3695 """
3690 """
3696 query = cls.query()
3691 query = cls.query()
3697 query = query.filter(cls.external_id == external_id)
3692 query = query.filter(cls.external_id == external_id)
3698 query = query.filter(cls.provider_name == provider_name)
3693 query = query.filter(cls.provider_name == provider_name)
3699 if local_user_id:
3694 if local_user_id:
3700 query = query.filter(cls.local_user_id == local_user_id)
3695 query = query.filter(cls.local_user_id == local_user_id)
3701 return query.first()
3696 return query.first()
3702
3697
3703 @classmethod
3698 @classmethod
3704 def user_by_external_id_and_provider(cls, external_id, provider_name):
3699 def user_by_external_id_and_provider(cls, external_id, provider_name):
3705 """
3700 """
3706 Returns User instance based on search params
3701 Returns User instance based on search params
3707
3702
3708 :param external_id:
3703 :param external_id:
3709 :param provider_name:
3704 :param provider_name:
3710 :return: User
3705 :return: User
3711 """
3706 """
3712 query = User.query()
3707 query = User.query()
3713 query = query.filter(cls.external_id == external_id)
3708 query = query.filter(cls.external_id == external_id)
3714 query = query.filter(cls.provider_name == provider_name)
3709 query = query.filter(cls.provider_name == provider_name)
3715 query = query.filter(User.user_id == cls.local_user_id)
3710 query = query.filter(User.user_id == cls.local_user_id)
3716 return query.first()
3711 return query.first()
3717
3712
3718 @classmethod
3713 @classmethod
3719 def by_local_user_id(cls, local_user_id):
3714 def by_local_user_id(cls, local_user_id):
3720 """
3715 """
3721 Returns all tokens for user
3716 Returns all tokens for user
3722
3717
3723 :param local_user_id:
3718 :param local_user_id:
3724 :return: ExternalIdentity
3719 :return: ExternalIdentity
3725 """
3720 """
3726 query = cls.query()
3721 query = cls.query()
3727 query = query.filter(cls.local_user_id == local_user_id)
3722 query = query.filter(cls.local_user_id == local_user_id)
3728 return query
3723 return query
3729
3724
3730
3725
3731 class Integration(Base, BaseModel):
3726 class Integration(Base, BaseModel):
3732 __tablename__ = 'integrations'
3727 __tablename__ = 'integrations'
3733 __table_args__ = (
3728 __table_args__ = (
3734 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3729 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3735 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3730 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3736 )
3731 )
3737
3732
3738 integration_id = Column('integration_id', Integer(), primary_key=True)
3733 integration_id = Column('integration_id', Integer(), primary_key=True)
3739 integration_type = Column('integration_type', String(255))
3734 integration_type = Column('integration_type', String(255))
3740 enabled = Column('enabled', Boolean(), nullable=False)
3735 enabled = Column('enabled', Boolean(), nullable=False)
3741 name = Column('name', String(255), nullable=False)
3736 name = Column('name', String(255), nullable=False)
3742 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
3737 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
3743 default=False)
3738 default=False)
3744
3739
3745 settings = Column(
3740 settings = Column(
3746 'settings_json', MutationObj.as_mutable(
3741 'settings_json', MutationObj.as_mutable(
3747 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3742 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3748 repo_id = Column(
3743 repo_id = Column(
3749 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
3744 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
3750 nullable=True, unique=None, default=None)
3745 nullable=True, unique=None, default=None)
3751 repo = relationship('Repository', lazy='joined')
3746 repo = relationship('Repository', lazy='joined')
3752
3747
3753 repo_group_id = Column(
3748 repo_group_id = Column(
3754 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
3749 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
3755 nullable=True, unique=None, default=None)
3750 nullable=True, unique=None, default=None)
3756 repo_group = relationship('RepoGroup', lazy='joined')
3751 repo_group = relationship('RepoGroup', lazy='joined')
3757
3752
3758 @property
3753 @property
3759 def scope(self):
3754 def scope(self):
3760 if self.repo:
3755 if self.repo:
3761 return repr(self.repo)
3756 return repr(self.repo)
3762 if self.repo_group:
3757 if self.repo_group:
3763 if self.child_repos_only:
3758 if self.child_repos_only:
3764 return repr(self.repo_group) + ' (child repos only)'
3759 return repr(self.repo_group) + ' (child repos only)'
3765 else:
3760 else:
3766 return repr(self.repo_group) + ' (recursive)'
3761 return repr(self.repo_group) + ' (recursive)'
3767 if self.child_repos_only:
3762 if self.child_repos_only:
3768 return 'root_repos'
3763 return 'root_repos'
3769 return 'global'
3764 return 'global'
3770
3765
3771 def __repr__(self):
3766 def __repr__(self):
3772 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
3767 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
3773
3768
3774
3769
3775 class RepoReviewRuleUser(Base, BaseModel):
3770 class RepoReviewRuleUser(Base, BaseModel):
3776 __tablename__ = 'repo_review_rules_users'
3771 __tablename__ = 'repo_review_rules_users'
3777 __table_args__ = (
3772 __table_args__ = (
3778 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3773 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3779 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3774 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3780 )
3775 )
3781 repo_review_rule_user_id = Column(
3776 repo_review_rule_user_id = Column(
3782 'repo_review_rule_user_id', Integer(), primary_key=True)
3777 'repo_review_rule_user_id', Integer(), primary_key=True)
3783 repo_review_rule_id = Column("repo_review_rule_id",
3778 repo_review_rule_id = Column("repo_review_rule_id",
3784 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3779 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3785 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
3780 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'),
3786 nullable=False)
3781 nullable=False)
3787 user = relationship('User')
3782 user = relationship('User')
3788
3783
3789
3784
3790 class RepoReviewRuleUserGroup(Base, BaseModel):
3785 class RepoReviewRuleUserGroup(Base, BaseModel):
3791 __tablename__ = 'repo_review_rules_users_groups'
3786 __tablename__ = 'repo_review_rules_users_groups'
3792 __table_args__ = (
3787 __table_args__ = (
3793 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3788 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3794 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3789 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3795 )
3790 )
3796 repo_review_rule_users_group_id = Column(
3791 repo_review_rule_users_group_id = Column(
3797 'repo_review_rule_users_group_id', Integer(), primary_key=True)
3792 'repo_review_rule_users_group_id', Integer(), primary_key=True)
3798 repo_review_rule_id = Column("repo_review_rule_id",
3793 repo_review_rule_id = Column("repo_review_rule_id",
3799 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3794 Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
3800 users_group_id = Column("users_group_id", Integer(),
3795 users_group_id = Column("users_group_id", Integer(),
3801 ForeignKey('users_groups.users_group_id'), nullable=False)
3796 ForeignKey('users_groups.users_group_id'), nullable=False)
3802 users_group = relationship('UserGroup')
3797 users_group = relationship('UserGroup')
3803
3798
3804
3799
3805 class RepoReviewRule(Base, BaseModel):
3800 class RepoReviewRule(Base, BaseModel):
3806 __tablename__ = 'repo_review_rules'
3801 __tablename__ = 'repo_review_rules'
3807 __table_args__ = (
3802 __table_args__ = (
3808 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3803 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3809 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3804 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
3810 )
3805 )
3811
3806
3812 repo_review_rule_id = Column(
3807 repo_review_rule_id = Column(
3813 'repo_review_rule_id', Integer(), primary_key=True)
3808 'repo_review_rule_id', Integer(), primary_key=True)
3814 repo_id = Column(
3809 repo_id = Column(
3815 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
3810 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
3816 repo = relationship('Repository', backref='review_rules')
3811 repo = relationship('Repository', backref='review_rules')
3817
3812
3818 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3813 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3819 default=u'*') # glob
3814 default=u'*') # glob
3820 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3815 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'),
3821 default=u'*') # glob
3816 default=u'*') # glob
3822
3817
3823 use_authors_for_review = Column("use_authors_for_review", Boolean(),
3818 use_authors_for_review = Column("use_authors_for_review", Boolean(),
3824 nullable=False, default=False)
3819 nullable=False, default=False)
3825 rule_users = relationship('RepoReviewRuleUser')
3820 rule_users = relationship('RepoReviewRuleUser')
3826 rule_user_groups = relationship('RepoReviewRuleUserGroup')
3821 rule_user_groups = relationship('RepoReviewRuleUserGroup')
3827
3822
3828 @hybrid_property
3823 @hybrid_property
3829 def branch_pattern(self):
3824 def branch_pattern(self):
3830 return self._branch_pattern or '*'
3825 return self._branch_pattern or '*'
3831
3826
3832 def _validate_glob(self, value):
3827 def _validate_glob(self, value):
3833 re.compile('^' + glob2re(value) + '$')
3828 re.compile('^' + glob2re(value) + '$')
3834
3829
3835 @branch_pattern.setter
3830 @branch_pattern.setter
3836 def branch_pattern(self, value):
3831 def branch_pattern(self, value):
3837 self._validate_glob(value)
3832 self._validate_glob(value)
3838 self._branch_pattern = value or '*'
3833 self._branch_pattern = value or '*'
3839
3834
3840 @hybrid_property
3835 @hybrid_property
3841 def file_pattern(self):
3836 def file_pattern(self):
3842 return self._file_pattern or '*'
3837 return self._file_pattern or '*'
3843
3838
3844 @file_pattern.setter
3839 @file_pattern.setter
3845 def file_pattern(self, value):
3840 def file_pattern(self, value):
3846 self._validate_glob(value)
3841 self._validate_glob(value)
3847 self._file_pattern = value or '*'
3842 self._file_pattern = value or '*'
3848
3843
3849 def matches(self, branch, files_changed):
3844 def matches(self, branch, files_changed):
3850 """
3845 """
3851 Check if this review rule matches a branch/files in a pull request
3846 Check if this review rule matches a branch/files in a pull request
3852
3847
3853 :param branch: branch name for the commit
3848 :param branch: branch name for the commit
3854 :param files_changed: list of file paths changed in the pull request
3849 :param files_changed: list of file paths changed in the pull request
3855 """
3850 """
3856
3851
3857 branch = branch or ''
3852 branch = branch or ''
3858 files_changed = files_changed or []
3853 files_changed = files_changed or []
3859
3854
3860 branch_matches = True
3855 branch_matches = True
3861 if branch:
3856 if branch:
3862 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
3857 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
3863 branch_matches = bool(branch_regex.search(branch))
3858 branch_matches = bool(branch_regex.search(branch))
3864
3859
3865 files_matches = True
3860 files_matches = True
3866 if self.file_pattern != '*':
3861 if self.file_pattern != '*':
3867 files_matches = False
3862 files_matches = False
3868 file_regex = re.compile(glob2re(self.file_pattern))
3863 file_regex = re.compile(glob2re(self.file_pattern))
3869 for filename in files_changed:
3864 for filename in files_changed:
3870 if file_regex.search(filename):
3865 if file_regex.search(filename):
3871 files_matches = True
3866 files_matches = True
3872 break
3867 break
3873
3868
3874 return branch_matches and files_matches
3869 return branch_matches and files_matches
3875
3870
3876 @property
3871 @property
3877 def review_users(self):
3872 def review_users(self):
3878 """ Returns the users which this rule applies to """
3873 """ Returns the users which this rule applies to """
3879
3874
3880 users = set()
3875 users = set()
3881 users |= set([
3876 users |= set([
3882 rule_user.user for rule_user in self.rule_users
3877 rule_user.user for rule_user in self.rule_users
3883 if rule_user.user.active])
3878 if rule_user.user.active])
3884 users |= set(
3879 users |= set(
3885 member.user
3880 member.user
3886 for rule_user_group in self.rule_user_groups
3881 for rule_user_group in self.rule_user_groups
3887 for member in rule_user_group.users_group.members
3882 for member in rule_user_group.users_group.members
3888 if member.user.active
3883 if member.user.active
3889 )
3884 )
3890 return users
3885 return users
3891
3886
3892 def __repr__(self):
3887 def __repr__(self):
3893 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
3888 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
3894 self.repo_review_rule_id, self.repo)
3889 self.repo_review_rule_id, self.repo)
3895
3890
3896
3891
3897 class DbMigrateVersion(Base, BaseModel):
3892 class DbMigrateVersion(Base, BaseModel):
3898 __tablename__ = 'db_migrate_version'
3893 __tablename__ = 'db_migrate_version'
3899 __table_args__ = (
3894 __table_args__ = (
3900 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3895 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3901 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3896 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3902 )
3897 )
3903 repository_id = Column('repository_id', String(250), primary_key=True)
3898 repository_id = Column('repository_id', String(250), primary_key=True)
3904 repository_path = Column('repository_path', Text)
3899 repository_path = Column('repository_path', Text)
3905 version = Column('version', Integer)
3900 version = Column('version', Integer)
3906
3901
3907
3902
3908 class DbSession(Base, BaseModel):
3903 class DbSession(Base, BaseModel):
3909 __tablename__ = 'db_session'
3904 __tablename__ = 'db_session'
3910 __table_args__ = (
3905 __table_args__ = (
3911 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3906 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3912 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3907 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3913 )
3908 )
3914
3909
3915 def __repr__(self):
3910 def __repr__(self):
3916 return '<DB:DbSession({})>'.format(self.id)
3911 return '<DB:DbSession({})>'.format(self.id)
3917
3912
3918 id = Column('id', Integer())
3913 id = Column('id', Integer())
3919 namespace = Column('namespace', String(255), primary_key=True)
3914 namespace = Column('namespace', String(255), primary_key=True)
3920 accessed = Column('accessed', DateTime, nullable=False)
3915 accessed = Column('accessed', DateTime, nullable=False)
3921 created = Column('created', DateTime, nullable=False)
3916 created = Column('created', DateTime, nullable=False)
3922 data = Column('data', PickleType, nullable=False)
3917 data = Column('data', PickleType, nullable=False)
@@ -1,608 +1,608 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 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 from hashlib import sha1
22 from hashlib import sha1
23
23
24 import pytest
24 import pytest
25 from mock import patch
25 from mock import patch
26
26
27 from rhodecode.lib import auth
27 from rhodecode.lib import auth
28 from rhodecode.lib.utils2 import md5
28 from rhodecode.lib.utils2 import md5
29 from rhodecode.model.auth_token import AuthTokenModel
29 from rhodecode.model.auth_token import AuthTokenModel
30 from rhodecode.model.db import User
30 from rhodecode.model.db import User
31 from rhodecode.model.repo import RepoModel
31 from rhodecode.model.repo import RepoModel
32 from rhodecode.model.user import UserModel
32 from rhodecode.model.user import UserModel
33 from rhodecode.model.user_group import UserGroupModel
33 from rhodecode.model.user_group import UserGroupModel
34
34
35
35
36 def test_perm_origin_dict():
36 def test_perm_origin_dict():
37 pod = auth.PermOriginDict()
37 pod = auth.PermOriginDict()
38 pod['thing'] = 'read', 'default'
38 pod['thing'] = 'read', 'default'
39 assert pod['thing'] == 'read'
39 assert pod['thing'] == 'read'
40
40
41 assert pod.perm_origin_stack == {
41 assert pod.perm_origin_stack == {
42 'thing': [('read', 'default')]}
42 'thing': [('read', 'default')]}
43
43
44 pod['thing'] = 'write', 'admin'
44 pod['thing'] = 'write', 'admin'
45 assert pod['thing'] == 'write'
45 assert pod['thing'] == 'write'
46
46
47 assert pod.perm_origin_stack == {
47 assert pod.perm_origin_stack == {
48 'thing': [('read', 'default'), ('write', 'admin')]}
48 'thing': [('read', 'default'), ('write', 'admin')]}
49
49
50 pod['other'] = 'write', 'default'
50 pod['other'] = 'write', 'default'
51
51
52 assert pod.perm_origin_stack == {
52 assert pod.perm_origin_stack == {
53 'other': [('write', 'default')],
53 'other': [('write', 'default')],
54 'thing': [('read', 'default'), ('write', 'admin')]}
54 'thing': [('read', 'default'), ('write', 'admin')]}
55
55
56 pod['other'] = 'none', 'override'
56 pod['other'] = 'none', 'override'
57
57
58 assert pod.perm_origin_stack == {
58 assert pod.perm_origin_stack == {
59 'other': [('write', 'default'), ('none', 'override')],
59 'other': [('write', 'default'), ('none', 'override')],
60 'thing': [('read', 'default'), ('write', 'admin')]}
60 'thing': [('read', 'default'), ('write', 'admin')]}
61
61
62 with pytest.raises(ValueError):
62 with pytest.raises(ValueError):
63 pod['thing'] = 'read'
63 pod['thing'] = 'read'
64
64
65
65
66 def test_cached_perms_data(user_regular, backend_random):
66 def test_cached_perms_data(user_regular, backend_random):
67 permissions = get_permissions(user_regular)
67 permissions = get_permissions(user_regular)
68 repo_name = backend_random.repo.repo_name
68 repo_name = backend_random.repo.repo_name
69 expected_global_permissions = {
69 expected_global_permissions = {
70 'repository.read', 'group.read', 'usergroup.read'}
70 'repository.read', 'group.read', 'usergroup.read'}
71 assert expected_global_permissions.issubset(permissions['global'])
71 assert expected_global_permissions.issubset(permissions['global'])
72 assert permissions['repositories'][repo_name] == 'repository.read'
72 assert permissions['repositories'][repo_name] == 'repository.read'
73
73
74
74
75 def test_cached_perms_data_with_admin_user(user_regular, backend_random):
75 def test_cached_perms_data_with_admin_user(user_regular, backend_random):
76 permissions = get_permissions(user_regular, user_is_admin=True)
76 permissions = get_permissions(user_regular, user_is_admin=True)
77 repo_name = backend_random.repo.repo_name
77 repo_name = backend_random.repo.repo_name
78 assert 'hg.admin' in permissions['global']
78 assert 'hg.admin' in permissions['global']
79 assert permissions['repositories'][repo_name] == 'repository.admin'
79 assert permissions['repositories'][repo_name] == 'repository.admin'
80
80
81
81
82 def test_cached_perms_data_user_group_global_permissions(user_util):
82 def test_cached_perms_data_user_group_global_permissions(user_util):
83 user, user_group = user_util.create_user_with_group()
83 user, user_group = user_util.create_user_with_group()
84 user_group.inherit_default_permissions = False
84 user_group.inherit_default_permissions = False
85
85
86 granted_permission = 'repository.write'
86 granted_permission = 'repository.write'
87 UserGroupModel().grant_perm(user_group, granted_permission)
87 UserGroupModel().grant_perm(user_group, granted_permission)
88
88
89 permissions = get_permissions(user)
89 permissions = get_permissions(user)
90 assert granted_permission in permissions['global']
90 assert granted_permission in permissions['global']
91
91
92
92
93 @pytest.mark.xfail(reason="Not implemented, see TODO note")
93 @pytest.mark.xfail(reason="Not implemented, see TODO note")
94 def test_cached_perms_data_user_group_global_permissions_(user_util):
94 def test_cached_perms_data_user_group_global_permissions_(user_util):
95 user, user_group = user_util.create_user_with_group()
95 user, user_group = user_util.create_user_with_group()
96
96
97 granted_permission = 'repository.write'
97 granted_permission = 'repository.write'
98 UserGroupModel().grant_perm(user_group, granted_permission)
98 UserGroupModel().grant_perm(user_group, granted_permission)
99
99
100 permissions = get_permissions(user)
100 permissions = get_permissions(user)
101 assert granted_permission in permissions['global']
101 assert granted_permission in permissions['global']
102
102
103
103
104 def test_cached_perms_data_user_global_permissions(user_util):
104 def test_cached_perms_data_user_global_permissions(user_util):
105 user = user_util.create_user()
105 user = user_util.create_user()
106 UserModel().grant_perm(user, 'repository.none')
106 UserModel().grant_perm(user, 'repository.none')
107
107
108 permissions = get_permissions(user, user_inherit_default_permissions=True)
108 permissions = get_permissions(user, user_inherit_default_permissions=True)
109 assert 'repository.read' in permissions['global']
109 assert 'repository.read' in permissions['global']
110
110
111
111
112 def test_cached_perms_data_repository_permissions_on_private_repository(
112 def test_cached_perms_data_repository_permissions_on_private_repository(
113 backend_random, user_util):
113 backend_random, user_util):
114 user, user_group = user_util.create_user_with_group()
114 user, user_group = user_util.create_user_with_group()
115
115
116 repo = backend_random.create_repo()
116 repo = backend_random.create_repo()
117 repo.private = True
117 repo.private = True
118
118
119 granted_permission = 'repository.write'
119 granted_permission = 'repository.write'
120 RepoModel().grant_user_group_permission(
120 RepoModel().grant_user_group_permission(
121 repo, user_group.users_group_name, granted_permission)
121 repo, user_group.users_group_name, granted_permission)
122
122
123 permissions = get_permissions(user)
123 permissions = get_permissions(user)
124 assert permissions['repositories'][repo.repo_name] == granted_permission
124 assert permissions['repositories'][repo.repo_name] == granted_permission
125
125
126
126
127 def test_cached_perms_data_repository_permissions_for_owner(
127 def test_cached_perms_data_repository_permissions_for_owner(
128 backend_random, user_util):
128 backend_random, user_util):
129 user = user_util.create_user()
129 user = user_util.create_user()
130
130
131 repo = backend_random.create_repo()
131 repo = backend_random.create_repo()
132 repo.user_id = user.user_id
132 repo.user_id = user.user_id
133
133
134 permissions = get_permissions(user)
134 permissions = get_permissions(user)
135 assert permissions['repositories'][repo.repo_name] == 'repository.admin'
135 assert permissions['repositories'][repo.repo_name] == 'repository.admin'
136
136
137 # TODO: johbo: Make cleanup in UserUtility smarter, then remove this hack
137 # TODO: johbo: Make cleanup in UserUtility smarter, then remove this hack
138 repo.user_id = User.get_default_user().user_id
138 repo.user_id = User.get_default_user().user_id
139
139
140
140
141 def test_cached_perms_data_repository_permissions_not_inheriting_defaults(
141 def test_cached_perms_data_repository_permissions_not_inheriting_defaults(
142 backend_random, user_util):
142 backend_random, user_util):
143 user = user_util.create_user()
143 user = user_util.create_user()
144 repo = backend_random.create_repo()
144 repo = backend_random.create_repo()
145
145
146 # Don't inherit default object permissions
146 # Don't inherit default object permissions
147 UserModel().grant_perm(user, 'hg.inherit_default_perms.false')
147 UserModel().grant_perm(user, 'hg.inherit_default_perms.false')
148
148
149 permissions = get_permissions(user)
149 permissions = get_permissions(user)
150 assert permissions['repositories'][repo.repo_name] == 'repository.none'
150 assert permissions['repositories'][repo.repo_name] == 'repository.none'
151
151
152
152
153 def test_cached_perms_data_default_permissions_on_repository_group(user_util):
153 def test_cached_perms_data_default_permissions_on_repository_group(user_util):
154 # Have a repository group with default permissions set
154 # Have a repository group with default permissions set
155 repo_group = user_util.create_repo_group()
155 repo_group = user_util.create_repo_group()
156 default_user = User.get_default_user()
156 default_user = User.get_default_user()
157 user_util.grant_user_permission_to_repo_group(
157 user_util.grant_user_permission_to_repo_group(
158 repo_group, default_user, 'repository.write')
158 repo_group, default_user, 'repository.write')
159 user = user_util.create_user()
159 user = user_util.create_user()
160
160
161 permissions = get_permissions(user)
161 permissions = get_permissions(user)
162 assert permissions['repositories_groups'][repo_group.group_name] == \
162 assert permissions['repositories_groups'][repo_group.group_name] == \
163 'repository.write'
163 'repository.write'
164
164
165
165
166 def test_cached_perms_data_default_permissions_on_repository_group_owner(
166 def test_cached_perms_data_default_permissions_on_repository_group_owner(
167 user_util):
167 user_util):
168 # Have a repository group
168 # Have a repository group
169 repo_group = user_util.create_repo_group()
169 repo_group = user_util.create_repo_group()
170 default_user = User.get_default_user()
170 default_user = User.get_default_user()
171
171
172 # Add a permission for the default user to hit the code path
172 # Add a permission for the default user to hit the code path
173 user_util.grant_user_permission_to_repo_group(
173 user_util.grant_user_permission_to_repo_group(
174 repo_group, default_user, 'repository.write')
174 repo_group, default_user, 'repository.write')
175
175
176 # Have an owner of the group
176 # Have an owner of the group
177 user = user_util.create_user()
177 user = user_util.create_user()
178 repo_group.user_id = user.user_id
178 repo_group.user_id = user.user_id
179
179
180 permissions = get_permissions(user)
180 permissions = get_permissions(user)
181 assert permissions['repositories_groups'][repo_group.group_name] == \
181 assert permissions['repositories_groups'][repo_group.group_name] == \
182 'group.admin'
182 'group.admin'
183
183
184
184
185 def test_cached_perms_data_default_permissions_on_repository_group_no_inherit(
185 def test_cached_perms_data_default_permissions_on_repository_group_no_inherit(
186 user_util):
186 user_util):
187 # Have a repository group
187 # Have a repository group
188 repo_group = user_util.create_repo_group()
188 repo_group = user_util.create_repo_group()
189 default_user = User.get_default_user()
189 default_user = User.get_default_user()
190
190
191 # Add a permission for the default user to hit the code path
191 # Add a permission for the default user to hit the code path
192 user_util.grant_user_permission_to_repo_group(
192 user_util.grant_user_permission_to_repo_group(
193 repo_group, default_user, 'repository.write')
193 repo_group, default_user, 'repository.write')
194
194
195 # Don't inherit default object permissions
195 # Don't inherit default object permissions
196 user = user_util.create_user()
196 user = user_util.create_user()
197 UserModel().grant_perm(user, 'hg.inherit_default_perms.false')
197 UserModel().grant_perm(user, 'hg.inherit_default_perms.false')
198
198
199 permissions = get_permissions(user)
199 permissions = get_permissions(user)
200 assert permissions['repositories_groups'][repo_group.group_name] == \
200 assert permissions['repositories_groups'][repo_group.group_name] == \
201 'group.none'
201 'group.none'
202
202
203
203
204 def test_cached_perms_data_repository_permissions_from_user_group(
204 def test_cached_perms_data_repository_permissions_from_user_group(
205 user_util, backend_random):
205 user_util, backend_random):
206 user, user_group = user_util.create_user_with_group()
206 user, user_group = user_util.create_user_with_group()
207
207
208 # Needs a second user group to make sure that we select the right
208 # Needs a second user group to make sure that we select the right
209 # permissions.
209 # permissions.
210 user_group2 = user_util.create_user_group()
210 user_group2 = user_util.create_user_group()
211 UserGroupModel().add_user_to_group(user_group2, user)
211 UserGroupModel().add_user_to_group(user_group2, user)
212
212
213 repo = backend_random.create_repo()
213 repo = backend_random.create_repo()
214
214
215 RepoModel().grant_user_group_permission(
215 RepoModel().grant_user_group_permission(
216 repo, user_group.users_group_name, 'repository.read')
216 repo, user_group.users_group_name, 'repository.read')
217 RepoModel().grant_user_group_permission(
217 RepoModel().grant_user_group_permission(
218 repo, user_group2.users_group_name, 'repository.write')
218 repo, user_group2.users_group_name, 'repository.write')
219
219
220 permissions = get_permissions(user)
220 permissions = get_permissions(user)
221 assert permissions['repositories'][repo.repo_name] == 'repository.write'
221 assert permissions['repositories'][repo.repo_name] == 'repository.write'
222
222
223
223
224 def test_cached_perms_data_repository_permissions_from_user_group_owner(
224 def test_cached_perms_data_repository_permissions_from_user_group_owner(
225 user_util, backend_random):
225 user_util, backend_random):
226 user, user_group = user_util.create_user_with_group()
226 user, user_group = user_util.create_user_with_group()
227
227
228 repo = backend_random.create_repo()
228 repo = backend_random.create_repo()
229 repo.user_id = user.user_id
229 repo.user_id = user.user_id
230
230
231 RepoModel().grant_user_group_permission(
231 RepoModel().grant_user_group_permission(
232 repo, user_group.users_group_name, 'repository.write')
232 repo, user_group.users_group_name, 'repository.write')
233
233
234 permissions = get_permissions(user)
234 permissions = get_permissions(user)
235 assert permissions['repositories'][repo.repo_name] == 'repository.admin'
235 assert permissions['repositories'][repo.repo_name] == 'repository.admin'
236
236
237
237
238 def test_cached_perms_data_user_repository_permissions(
238 def test_cached_perms_data_user_repository_permissions(
239 user_util, backend_random):
239 user_util, backend_random):
240 user = user_util.create_user()
240 user = user_util.create_user()
241 repo = backend_random.create_repo()
241 repo = backend_random.create_repo()
242 granted_permission = 'repository.write'
242 granted_permission = 'repository.write'
243 RepoModel().grant_user_permission(repo, user, granted_permission)
243 RepoModel().grant_user_permission(repo, user, granted_permission)
244
244
245 permissions = get_permissions(user)
245 permissions = get_permissions(user)
246 assert permissions['repositories'][repo.repo_name] == granted_permission
246 assert permissions['repositories'][repo.repo_name] == granted_permission
247
247
248
248
249 def test_cached_perms_data_user_repository_permissions_explicit(
249 def test_cached_perms_data_user_repository_permissions_explicit(
250 user_util, backend_random):
250 user_util, backend_random):
251 user = user_util.create_user()
251 user = user_util.create_user()
252 repo = backend_random.create_repo()
252 repo = backend_random.create_repo()
253 granted_permission = 'repository.none'
253 granted_permission = 'repository.none'
254 RepoModel().grant_user_permission(repo, user, granted_permission)
254 RepoModel().grant_user_permission(repo, user, granted_permission)
255
255
256 permissions = get_permissions(user, explicit=True)
256 permissions = get_permissions(user, explicit=True)
257 assert permissions['repositories'][repo.repo_name] == granted_permission
257 assert permissions['repositories'][repo.repo_name] == granted_permission
258
258
259
259
260 def test_cached_perms_data_user_repository_permissions_owner(
260 def test_cached_perms_data_user_repository_permissions_owner(
261 user_util, backend_random):
261 user_util, backend_random):
262 user = user_util.create_user()
262 user = user_util.create_user()
263 repo = backend_random.create_repo()
263 repo = backend_random.create_repo()
264 repo.user_id = user.user_id
264 repo.user_id = user.user_id
265 RepoModel().grant_user_permission(repo, user, 'repository.write')
265 RepoModel().grant_user_permission(repo, user, 'repository.write')
266
266
267 permissions = get_permissions(user)
267 permissions = get_permissions(user)
268 assert permissions['repositories'][repo.repo_name] == 'repository.admin'
268 assert permissions['repositories'][repo.repo_name] == 'repository.admin'
269
269
270
270
271 def test_cached_perms_data_repository_groups_permissions_inherited(
271 def test_cached_perms_data_repository_groups_permissions_inherited(
272 user_util, backend_random):
272 user_util, backend_random):
273 user, user_group = user_util.create_user_with_group()
273 user, user_group = user_util.create_user_with_group()
274
274
275 # Needs a second group to hit the last condition
275 # Needs a second group to hit the last condition
276 user_group2 = user_util.create_user_group()
276 user_group2 = user_util.create_user_group()
277 UserGroupModel().add_user_to_group(user_group2, user)
277 UserGroupModel().add_user_to_group(user_group2, user)
278
278
279 repo_group = user_util.create_repo_group()
279 repo_group = user_util.create_repo_group()
280
280
281 user_util.grant_user_group_permission_to_repo_group(
281 user_util.grant_user_group_permission_to_repo_group(
282 repo_group, user_group, 'group.read')
282 repo_group, user_group, 'group.read')
283 user_util.grant_user_group_permission_to_repo_group(
283 user_util.grant_user_group_permission_to_repo_group(
284 repo_group, user_group2, 'group.write')
284 repo_group, user_group2, 'group.write')
285
285
286 permissions = get_permissions(user)
286 permissions = get_permissions(user)
287 assert permissions['repositories_groups'][repo_group.group_name] == \
287 assert permissions['repositories_groups'][repo_group.group_name] == \
288 'group.write'
288 'group.write'
289
289
290
290
291 def test_cached_perms_data_repository_groups_permissions_inherited_owner(
291 def test_cached_perms_data_repository_groups_permissions_inherited_owner(
292 user_util, backend_random):
292 user_util, backend_random):
293 user, user_group = user_util.create_user_with_group()
293 user, user_group = user_util.create_user_with_group()
294 repo_group = user_util.create_repo_group()
294 repo_group = user_util.create_repo_group()
295 repo_group.user_id = user.user_id
295 repo_group.user_id = user.user_id
296
296
297 granted_permission = 'group.write'
297 granted_permission = 'group.write'
298 user_util.grant_user_group_permission_to_repo_group(
298 user_util.grant_user_group_permission_to_repo_group(
299 repo_group, user_group, granted_permission)
299 repo_group, user_group, granted_permission)
300
300
301 permissions = get_permissions(user)
301 permissions = get_permissions(user)
302 assert permissions['repositories_groups'][repo_group.group_name] == \
302 assert permissions['repositories_groups'][repo_group.group_name] == \
303 'group.admin'
303 'group.admin'
304
304
305
305
306 def test_cached_perms_data_repository_groups_permissions(
306 def test_cached_perms_data_repository_groups_permissions(
307 user_util, backend_random):
307 user_util, backend_random):
308 user = user_util.create_user()
308 user = user_util.create_user()
309
309
310 repo_group = user_util.create_repo_group()
310 repo_group = user_util.create_repo_group()
311
311
312 granted_permission = 'group.write'
312 granted_permission = 'group.write'
313 user_util.grant_user_permission_to_repo_group(
313 user_util.grant_user_permission_to_repo_group(
314 repo_group, user, granted_permission)
314 repo_group, user, granted_permission)
315
315
316 permissions = get_permissions(user)
316 permissions = get_permissions(user)
317 assert permissions['repositories_groups'][repo_group.group_name] == \
317 assert permissions['repositories_groups'][repo_group.group_name] == \
318 'group.write'
318 'group.write'
319
319
320
320
321 def test_cached_perms_data_repository_groups_permissions_explicit(
321 def test_cached_perms_data_repository_groups_permissions_explicit(
322 user_util, backend_random):
322 user_util, backend_random):
323 user = user_util.create_user()
323 user = user_util.create_user()
324
324
325 repo_group = user_util.create_repo_group()
325 repo_group = user_util.create_repo_group()
326
326
327 granted_permission = 'group.none'
327 granted_permission = 'group.none'
328 user_util.grant_user_permission_to_repo_group(
328 user_util.grant_user_permission_to_repo_group(
329 repo_group, user, granted_permission)
329 repo_group, user, granted_permission)
330
330
331 permissions = get_permissions(user, explicit=True)
331 permissions = get_permissions(user, explicit=True)
332 assert permissions['repositories_groups'][repo_group.group_name] == \
332 assert permissions['repositories_groups'][repo_group.group_name] == \
333 'group.none'
333 'group.none'
334
334
335
335
336 def test_cached_perms_data_repository_groups_permissions_owner(
336 def test_cached_perms_data_repository_groups_permissions_owner(
337 user_util, backend_random):
337 user_util, backend_random):
338 user = user_util.create_user()
338 user = user_util.create_user()
339
339
340 repo_group = user_util.create_repo_group()
340 repo_group = user_util.create_repo_group()
341 repo_group.user_id = user.user_id
341 repo_group.user_id = user.user_id
342
342
343 granted_permission = 'group.write'
343 granted_permission = 'group.write'
344 user_util.grant_user_permission_to_repo_group(
344 user_util.grant_user_permission_to_repo_group(
345 repo_group, user, granted_permission)
345 repo_group, user, granted_permission)
346
346
347 permissions = get_permissions(user)
347 permissions = get_permissions(user)
348 assert permissions['repositories_groups'][repo_group.group_name] == \
348 assert permissions['repositories_groups'][repo_group.group_name] == \
349 'group.admin'
349 'group.admin'
350
350
351
351
352 def test_cached_perms_data_user_group_permissions_inherited(
352 def test_cached_perms_data_user_group_permissions_inherited(
353 user_util, backend_random):
353 user_util, backend_random):
354 user, user_group = user_util.create_user_with_group()
354 user, user_group = user_util.create_user_with_group()
355 user_group2 = user_util.create_user_group()
355 user_group2 = user_util.create_user_group()
356 UserGroupModel().add_user_to_group(user_group2, user)
356 UserGroupModel().add_user_to_group(user_group2, user)
357
357
358 target_user_group = user_util.create_user_group()
358 target_user_group = user_util.create_user_group()
359
359
360 user_util.grant_user_group_permission_to_user_group(
360 user_util.grant_user_group_permission_to_user_group(
361 target_user_group, user_group, 'usergroup.read')
361 target_user_group, user_group, 'usergroup.read')
362 user_util.grant_user_group_permission_to_user_group(
362 user_util.grant_user_group_permission_to_user_group(
363 target_user_group, user_group2, 'usergroup.write')
363 target_user_group, user_group2, 'usergroup.write')
364
364
365 permissions = get_permissions(user)
365 permissions = get_permissions(user)
366 assert permissions['user_groups'][target_user_group.users_group_name] == \
366 assert permissions['user_groups'][target_user_group.users_group_name] == \
367 'usergroup.write'
367 'usergroup.write'
368
368
369
369
370 def test_cached_perms_data_user_group_permissions(
370 def test_cached_perms_data_user_group_permissions(
371 user_util, backend_random):
371 user_util, backend_random):
372 user = user_util.create_user()
372 user = user_util.create_user()
373 user_group = user_util.create_user_group()
373 user_group = user_util.create_user_group()
374 UserGroupModel().grant_user_permission(user_group, user, 'usergroup.write')
374 UserGroupModel().grant_user_permission(user_group, user, 'usergroup.write')
375
375
376 permissions = get_permissions(user)
376 permissions = get_permissions(user)
377 assert permissions['user_groups'][user_group.users_group_name] == \
377 assert permissions['user_groups'][user_group.users_group_name] == \
378 'usergroup.write'
378 'usergroup.write'
379
379
380
380
381 def test_cached_perms_data_user_group_permissions_explicit(
381 def test_cached_perms_data_user_group_permissions_explicit(
382 user_util, backend_random):
382 user_util, backend_random):
383 user = user_util.create_user()
383 user = user_util.create_user()
384 user_group = user_util.create_user_group()
384 user_group = user_util.create_user_group()
385 UserGroupModel().grant_user_permission(user_group, user, 'usergroup.none')
385 UserGroupModel().grant_user_permission(user_group, user, 'usergroup.none')
386
386
387 permissions = get_permissions(user, explicit=True)
387 permissions = get_permissions(user, explicit=True)
388 assert permissions['user_groups'][user_group.users_group_name] == \
388 assert permissions['user_groups'][user_group.users_group_name] == \
389 'usergroup.none'
389 'usergroup.none'
390
390
391
391
392 def test_cached_perms_data_user_group_permissions_not_inheriting_defaults(
392 def test_cached_perms_data_user_group_permissions_not_inheriting_defaults(
393 user_util, backend_random):
393 user_util, backend_random):
394 user = user_util.create_user()
394 user = user_util.create_user()
395 user_group = user_util.create_user_group()
395 user_group = user_util.create_user_group()
396
396
397 # Don't inherit default object permissions
397 # Don't inherit default object permissions
398 UserModel().grant_perm(user, 'hg.inherit_default_perms.false')
398 UserModel().grant_perm(user, 'hg.inherit_default_perms.false')
399
399
400 permissions = get_permissions(user)
400 permissions = get_permissions(user)
401 assert permissions['user_groups'][user_group.users_group_name] == \
401 assert permissions['user_groups'][user_group.users_group_name] == \
402 'usergroup.none'
402 'usergroup.none'
403
403
404
404
405 def test_permission_calculator_admin_permissions(
405 def test_permission_calculator_admin_permissions(
406 user_util, backend_random):
406 user_util, backend_random):
407 user = user_util.create_user()
407 user = user_util.create_user()
408 user_group = user_util.create_user_group()
408 user_group = user_util.create_user_group()
409 repo = backend_random.repo
409 repo = backend_random.repo
410 repo_group = user_util.create_repo_group()
410 repo_group = user_util.create_repo_group()
411
411
412 calculator = auth.PermissionCalculator(
412 calculator = auth.PermissionCalculator(
413 user.user_id, {}, False, False, True, 'higherwin')
413 user.user_id, {}, False, False, True, 'higherwin')
414 permissions = calculator._admin_permissions()
414 permissions = calculator._admin_permissions()
415
415
416 assert permissions['repositories_groups'][repo_group.group_name] == \
416 assert permissions['repositories_groups'][repo_group.group_name] == \
417 'group.admin'
417 'group.admin'
418 assert permissions['user_groups'][user_group.users_group_name] == \
418 assert permissions['user_groups'][user_group.users_group_name] == \
419 'usergroup.admin'
419 'usergroup.admin'
420 assert permissions['repositories'][repo.repo_name] == 'repository.admin'
420 assert permissions['repositories'][repo.repo_name] == 'repository.admin'
421 assert 'hg.admin' in permissions['global']
421 assert 'hg.admin' in permissions['global']
422
422
423
423
424 def test_permission_calculator_repository_permissions_robustness_from_group(
424 def test_permission_calculator_repository_permissions_robustness_from_group(
425 user_util, backend_random):
425 user_util, backend_random):
426 user, user_group = user_util.create_user_with_group()
426 user, user_group = user_util.create_user_with_group()
427
427
428 RepoModel().grant_user_group_permission(
428 RepoModel().grant_user_group_permission(
429 backend_random.repo, user_group.users_group_name, 'repository.write')
429 backend_random.repo, user_group.users_group_name, 'repository.write')
430
430
431 calculator = auth.PermissionCalculator(
431 calculator = auth.PermissionCalculator(
432 user.user_id, {}, False, False, False, 'higherwin')
432 user.user_id, {}, False, False, False, 'higherwin')
433 calculator._calculate_repository_permissions()
433 calculator._calculate_repository_permissions()
434
434
435
435
436 def test_permission_calculator_repository_permissions_robustness_from_user(
436 def test_permission_calculator_repository_permissions_robustness_from_user(
437 user_util, backend_random):
437 user_util, backend_random):
438 user = user_util.create_user()
438 user = user_util.create_user()
439
439
440 RepoModel().grant_user_permission(
440 RepoModel().grant_user_permission(
441 backend_random.repo, user, 'repository.write')
441 backend_random.repo, user, 'repository.write')
442
442
443 calculator = auth.PermissionCalculator(
443 calculator = auth.PermissionCalculator(
444 user.user_id, {}, False, False, False, 'higherwin')
444 user.user_id, {}, False, False, False, 'higherwin')
445 calculator._calculate_repository_permissions()
445 calculator._calculate_repository_permissions()
446
446
447
447
448 def test_permission_calculator_repo_group_permissions_robustness_from_group(
448 def test_permission_calculator_repo_group_permissions_robustness_from_group(
449 user_util, backend_random):
449 user_util, backend_random):
450 user, user_group = user_util.create_user_with_group()
450 user, user_group = user_util.create_user_with_group()
451 repo_group = user_util.create_repo_group()
451 repo_group = user_util.create_repo_group()
452
452
453 user_util.grant_user_group_permission_to_repo_group(
453 user_util.grant_user_group_permission_to_repo_group(
454 repo_group, user_group, 'group.write')
454 repo_group, user_group, 'group.write')
455
455
456 calculator = auth.PermissionCalculator(
456 calculator = auth.PermissionCalculator(
457 user.user_id, {}, False, False, False, 'higherwin')
457 user.user_id, {}, False, False, False, 'higherwin')
458 calculator._calculate_repository_group_permissions()
458 calculator._calculate_repository_group_permissions()
459
459
460
460
461 def test_permission_calculator_repo_group_permissions_robustness_from_user(
461 def test_permission_calculator_repo_group_permissions_robustness_from_user(
462 user_util, backend_random):
462 user_util, backend_random):
463 user = user_util.create_user()
463 user = user_util.create_user()
464 repo_group = user_util.create_repo_group()
464 repo_group = user_util.create_repo_group()
465
465
466 user_util.grant_user_permission_to_repo_group(
466 user_util.grant_user_permission_to_repo_group(
467 repo_group, user, 'group.write')
467 repo_group, user, 'group.write')
468
468
469 calculator = auth.PermissionCalculator(
469 calculator = auth.PermissionCalculator(
470 user.user_id, {}, False, False, False, 'higherwin')
470 user.user_id, {}, False, False, False, 'higherwin')
471 calculator._calculate_repository_group_permissions()
471 calculator._calculate_repository_group_permissions()
472
472
473
473
474 def test_permission_calculator_user_group_permissions_robustness_from_group(
474 def test_permission_calculator_user_group_permissions_robustness_from_group(
475 user_util, backend_random):
475 user_util, backend_random):
476 user, user_group = user_util.create_user_with_group()
476 user, user_group = user_util.create_user_with_group()
477 target_user_group = user_util.create_user_group()
477 target_user_group = user_util.create_user_group()
478
478
479 user_util.grant_user_group_permission_to_user_group(
479 user_util.grant_user_group_permission_to_user_group(
480 target_user_group, user_group, 'usergroup.write')
480 target_user_group, user_group, 'usergroup.write')
481
481
482 calculator = auth.PermissionCalculator(
482 calculator = auth.PermissionCalculator(
483 user.user_id, {}, False, False, False, 'higherwin')
483 user.user_id, {}, False, False, False, 'higherwin')
484 calculator._calculate_user_group_permissions()
484 calculator._calculate_user_group_permissions()
485
485
486
486
487 def test_permission_calculator_user_group_permissions_robustness_from_user(
487 def test_permission_calculator_user_group_permissions_robustness_from_user(
488 user_util, backend_random):
488 user_util, backend_random):
489 user = user_util.create_user()
489 user = user_util.create_user()
490 target_user_group = user_util.create_user_group()
490 target_user_group = user_util.create_user_group()
491
491
492 user_util.grant_user_permission_to_user_group(
492 user_util.grant_user_permission_to_user_group(
493 target_user_group, user, 'usergroup.write')
493 target_user_group, user, 'usergroup.write')
494
494
495 calculator = auth.PermissionCalculator(
495 calculator = auth.PermissionCalculator(
496 user.user_id, {}, False, False, False, 'higherwin')
496 user.user_id, {}, False, False, False, 'higherwin')
497 calculator._calculate_user_group_permissions()
497 calculator._calculate_user_group_permissions()
498
498
499
499
500 @pytest.mark.parametrize("algo, new_permission, old_permission, expected", [
500 @pytest.mark.parametrize("algo, new_permission, old_permission, expected", [
501 ('higherwin', 'repository.none', 'repository.none', 'repository.none'),
501 ('higherwin', 'repository.none', 'repository.none', 'repository.none'),
502 ('higherwin', 'repository.read', 'repository.none', 'repository.read'),
502 ('higherwin', 'repository.read', 'repository.none', 'repository.read'),
503 ('lowerwin', 'repository.write', 'repository.write', 'repository.write'),
503 ('lowerwin', 'repository.write', 'repository.write', 'repository.write'),
504 ('lowerwin', 'repository.read', 'repository.write', 'repository.read'),
504 ('lowerwin', 'repository.read', 'repository.write', 'repository.read'),
505 ])
505 ])
506 def test_permission_calculator_choose_permission(
506 def test_permission_calculator_choose_permission(
507 user_regular, algo, new_permission, old_permission, expected):
507 user_regular, algo, new_permission, old_permission, expected):
508 calculator = auth.PermissionCalculator(
508 calculator = auth.PermissionCalculator(
509 user_regular.user_id, {}, False, False, False, algo)
509 user_regular.user_id, {}, False, False, False, algo)
510 result = calculator._choose_permission(new_permission, old_permission)
510 result = calculator._choose_permission(new_permission, old_permission)
511 assert result == expected
511 assert result == expected
512
512
513
513
514 def test_permission_calculator_choose_permission_raises_on_wrong_algo(
514 def test_permission_calculator_choose_permission_raises_on_wrong_algo(
515 user_regular):
515 user_regular):
516 calculator = auth.PermissionCalculator(
516 calculator = auth.PermissionCalculator(
517 user_regular.user_id, {}, False, False, False, 'invalid')
517 user_regular.user_id, {}, False, False, False, 'invalid')
518 result = calculator._choose_permission(
518 result = calculator._choose_permission(
519 'repository.read', 'repository.read')
519 'repository.read', 'repository.read')
520 # TODO: johbo: This documents the existing behavior. Think of an
520 # TODO: johbo: This documents the existing behavior. Think of an
521 # improvement.
521 # improvement.
522 assert result is None
522 assert result is None
523
523
524
524
525 def test_auth_user_get_cookie_store_for_normal_user(user_util):
525 def test_auth_user_get_cookie_store_for_normal_user(user_util):
526 user = user_util.create_user()
526 user = user_util.create_user()
527 auth_user = auth.AuthUser(user_id=user.user_id)
527 auth_user = auth.AuthUser(user_id=user.user_id)
528 expected_data = {
528 expected_data = {
529 'username': user.username,
529 'username': user.username,
530 'user_id': user.user_id,
530 'user_id': user.user_id,
531 'password': md5(user.password),
531 'password': md5(user.password),
532 'is_authenticated': False
532 'is_authenticated': False
533 }
533 }
534 assert auth_user.get_cookie_store() == expected_data
534 assert auth_user.get_cookie_store() == expected_data
535
535
536
536
537 def test_auth_user_get_cookie_store_for_default_user():
537 def test_auth_user_get_cookie_store_for_default_user():
538 default_user = User.get_default_user()
538 default_user = User.get_default_user()
539 auth_user = auth.AuthUser()
539 auth_user = auth.AuthUser()
540 expected_data = {
540 expected_data = {
541 'username': User.DEFAULT_USER,
541 'username': User.DEFAULT_USER,
542 'user_id': default_user.user_id,
542 'user_id': default_user.user_id,
543 'password': md5(default_user.password),
543 'password': md5(default_user.password),
544 'is_authenticated': True
544 'is_authenticated': True
545 }
545 }
546 assert auth_user.get_cookie_store() == expected_data
546 assert auth_user.get_cookie_store() == expected_data
547
547
548
548
549 def get_permissions(user, **kwargs):
549 def get_permissions(user, **kwargs):
550 """
550 """
551 Utility filling in useful defaults into the call to `_cached_perms_data`.
551 Utility filling in useful defaults into the call to `_cached_perms_data`.
552
552
553 Fill in `**kwargs` if specific values are needed for a test.
553 Fill in `**kwargs` if specific values are needed for a test.
554 """
554 """
555 call_args = {
555 call_args = {
556 'user_id': user.user_id,
556 'user_id': user.user_id,
557 'scope': {},
557 'scope': {},
558 'user_is_admin': False,
558 'user_is_admin': False,
559 'user_inherit_default_permissions': False,
559 'user_inherit_default_permissions': False,
560 'explicit': False,
560 'explicit': False,
561 'algo': 'higherwin',
561 'algo': 'higherwin',
562 }
562 }
563 call_args.update(kwargs)
563 call_args.update(kwargs)
564 permissions = auth._cached_perms_data(**call_args)
564 permissions = auth._cached_perms_data(**call_args)
565 return permissions
565 return permissions
566
566
567
567
568 class TestGenerateAuthToken(object):
568 class TestGenerateAuthToken(object):
569 def test_salt_is_used_when_specified(self):
569 def test_salt_is_used_when_specified(self):
570 salt = 'abcde'
570 salt = 'abcde'
571 user_name = 'test_user'
571 user_name = 'test_user'
572 result = auth.generate_auth_token(user_name, salt)
572 result = auth.generate_auth_token(user_name, salt)
573 expected_result = sha1(user_name + salt).hexdigest()
573 expected_result = sha1(user_name + salt).hexdigest()
574 assert result == expected_result
574 assert result == expected_result
575
575
576 def test_salt_is_geneated_when_not_specified(self):
576 def test_salt_is_geneated_when_not_specified(self):
577 user_name = 'test_user'
577 user_name = 'test_user'
578 random_salt = os.urandom(16)
578 random_salt = os.urandom(16)
579 with patch.object(auth, 'os') as os_mock:
579 with patch.object(auth, 'os') as os_mock:
580 os_mock.urandom.return_value = random_salt
580 os_mock.urandom.return_value = random_salt
581 result = auth.generate_auth_token(user_name)
581 result = auth.generate_auth_token(user_name)
582 expected_result = sha1(user_name + random_salt).hexdigest()
582 expected_result = sha1(user_name + random_salt).hexdigest()
583 assert result == expected_result
583 assert result == expected_result
584
584
585
585
586 @pytest.mark.parametrize("test_token, test_roles, auth_result, expected_tokens", [
586 @pytest.mark.parametrize("test_token, test_roles, auth_result, expected_tokens", [
587 ('', None, False,
587 ('', None, False,
588 []),
588 []),
589 ('wrongtoken', None, False,
589 ('wrongtoken', None, False,
590 []),
590 []),
591 ('abracadabra_vcs', [AuthTokenModel.cls.ROLE_API], False,
591 ('abracadabra_vcs', [AuthTokenModel.cls.ROLE_API], False,
592 [('abracadabra_api', AuthTokenModel.cls.ROLE_API, -1)]),
592 [('abracadabra_api', AuthTokenModel.cls.ROLE_API, -1)]),
593 ('abracadabra_api', [AuthTokenModel.cls.ROLE_API], True,
593 ('abracadabra_api', [AuthTokenModel.cls.ROLE_API], True,
594 [('abracadabra_api', AuthTokenModel.cls.ROLE_API, -1)]),
594 [('abracadabra_api', AuthTokenModel.cls.ROLE_API, -1)]),
595 ('abracadabra_api', [AuthTokenModel.cls.ROLE_API], True,
595 ('abracadabra_api', [AuthTokenModel.cls.ROLE_API], True,
596 [('abracadabra_api', AuthTokenModel.cls.ROLE_API, -1),
596 [('abracadabra_api', AuthTokenModel.cls.ROLE_API, -1),
597 ('abracadabra_http', AuthTokenModel.cls.ROLE_HTTP, -1)]),
597 ('abracadabra_http', AuthTokenModel.cls.ROLE_HTTP, -1)]),
598 ])
598 ])
599 def test_auth_by_token(test_token, test_roles, auth_result, expected_tokens,
599 def test_auth_by_token(test_token, test_roles, auth_result, expected_tokens,
600 user_util):
600 user_util):
601 user = user_util.create_user()
601 user = user_util.create_user()
602 user_id = user.user_id
602 user_id = user.user_id
603 for token, role, expires in expected_tokens:
603 for token, role, expires in expected_tokens:
604 new_token = AuthTokenModel().create(user_id, 'test-token', expires, role)
604 new_token = AuthTokenModel().create(user_id, 'test-token', expires, role)
605 new_token.api_key = token # inject known name for testing...
605 new_token.api_key = token # inject known name for testing...
606
606
607 assert auth_result == user.authenticate_by_token(
607 assert auth_result == user.authenticate_by_token(
608 test_token, roles=test_roles, include_builtin_token=True)
608 test_token, roles=test_roles)
General Comments 0
You need to be logged in to leave comments. Login now