Show More
@@ -0,0 +1,138 b'' | |||||
|
1 | # -*- coding: utf-8 -*- | |||
|
2 | ||||
|
3 | # Copyright (C) 2017-2017 RhodeCode GmbH | |||
|
4 | # | |||
|
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 | |||
|
7 | # (only), as published by the Free Software Foundation. | |||
|
8 | # | |||
|
9 | # This program is distributed in the hope that it will be useful, | |||
|
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |||
|
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |||
|
12 | # GNU General Public License for more details. | |||
|
13 | # | |||
|
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/>. | |||
|
16 | # | |||
|
17 | # This program is dual-licensed. If you wish to learn more about the | |||
|
18 | # RhodeCode Enterprise Edition, including its added features, Support services, | |||
|
19 | # and proprietary license terms, please see https://rhodecode.com/licenses/ | |||
|
20 | ||||
|
21 | import logging | |||
|
22 | import datetime | |||
|
23 | ||||
|
24 | from rhodecode.model import meta | |||
|
25 | from rhodecode.model.db import User, UserLog | |||
|
26 | ||||
|
27 | ||||
|
28 | log = logging.getLogger(__name__) | |||
|
29 | ||||
|
30 | ||||
|
31 | ACTIONS = { | |||
|
32 | 'repo.add': {}, | |||
|
33 | 'repo.edit': {}, | |||
|
34 | } | |||
|
35 | ||||
|
36 | ||||
|
37 | class UserWrap(object): | |||
|
38 | """ | |||
|
39 | Fake object used to imitate AuthUser | |||
|
40 | """ | |||
|
41 | ||||
|
42 | def __init__(self, user_id=None, username=None, ip_addr=None): | |||
|
43 | self.user_id = user_id | |||
|
44 | self.username = username | |||
|
45 | self.ip_addr = ip_addr | |||
|
46 | ||||
|
47 | ||||
|
48 | def _store_log(action_name, action_data, user_id, username, user_data, | |||
|
49 | ip_address, repository_id, repository_name): | |||
|
50 | user_log = UserLog() | |||
|
51 | user_log.version = UserLog.VERSION_2 | |||
|
52 | ||||
|
53 | user_log.action = action_name | |||
|
54 | user_log.action_data = action_data | |||
|
55 | ||||
|
56 | user_log.user_ip = ip_address | |||
|
57 | ||||
|
58 | user_log.user_id = user_id | |||
|
59 | user_log.username = username | |||
|
60 | user_log.user_data = user_data | |||
|
61 | ||||
|
62 | user_log.repository_id = repository_id | |||
|
63 | user_log.repository_name = repository_name | |||
|
64 | ||||
|
65 | user_log.action_date = datetime.datetime.now() | |||
|
66 | ||||
|
67 | log.info('AUDIT: Logging action: `%s` by user:id:%s[%s] ip:%s', | |||
|
68 | action_name, user_id, username, ip_address) | |||
|
69 | ||||
|
70 | return user_log | |||
|
71 | ||||
|
72 | ||||
|
73 | def store( | |||
|
74 | action, user, action_data=None, user_data=None, ip_addr=None, | |||
|
75 | repo=None, sa_session=None, commit=False): | |||
|
76 | """ | |||
|
77 | Audit logger for various actions made by users, typically this results in a call such:: | |||
|
78 | ||||
|
79 | from rhodecode.lib import audit_logger | |||
|
80 | ||||
|
81 | audit_logger.store(action='repo.edit', user=self._rhodecode_user) | |||
|
82 | audit_logger.store(action='repo.delete', user=audit_logger.UserWrap(username='itried-to-login', ip_addr='8.8.8.8')) | |||
|
83 | ||||
|
84 | # without an user ? | |||
|
85 | audit_user = audit_logger.UserWrap( | |||
|
86 | username=self.request.params.get('username'), | |||
|
87 | ip_addr=self.request.remote_addr) | |||
|
88 | audit_logger.store(action='user.login.failure', user=audit_user) | |||
|
89 | """ | |||
|
90 | from rhodecode.lib.utils2 import safe_unicode | |||
|
91 | from rhodecode.lib.auth import AuthUser | |||
|
92 | ||||
|
93 | if action not in ACTIONS: | |||
|
94 | raise ValueError('Action `{}` not in valid actions'.format(action)) | |||
|
95 | ||||
|
96 | if not sa_session: | |||
|
97 | sa_session = meta.Session() | |||
|
98 | ||||
|
99 | try: | |||
|
100 | username = getattr(user, 'username', None) | |||
|
101 | if not username: | |||
|
102 | pass | |||
|
103 | ||||
|
104 | user_id = getattr(user, 'user_id', None) | |||
|
105 | if not user_id: | |||
|
106 | # maybe we have username ? Try to figure user_id from username | |||
|
107 | if username: | |||
|
108 | user_id = getattr( | |||
|
109 | User.get_by_username(username), 'user_id', None) | |||
|
110 | ||||
|
111 | ip_addr = ip_addr or getattr(user, 'ip_addr', None) | |||
|
112 | if not ip_addr: | |||
|
113 | pass | |||
|
114 | ||||
|
115 | if not user_data: | |||
|
116 | # try to get this from the auth user | |||
|
117 | if isinstance(user, AuthUser): | |||
|
118 | user_data = {} | |||
|
119 | ||||
|
120 | repository_id = getattr(repo, 'repo_id', None) | |||
|
121 | repository_name = getattr(repo, 'repo_name', None) | |||
|
122 | ||||
|
123 | user_log = _store_log( | |||
|
124 | action_name=safe_unicode(action), | |||
|
125 | action_data=action_data or {}, | |||
|
126 | user_id=user_id, | |||
|
127 | username=username, | |||
|
128 | user_data=user_data or {}, | |||
|
129 | ip_address=safe_unicode(ip_addr), | |||
|
130 | repository_id=repository_id, | |||
|
131 | repository_name=repository_name | |||
|
132 | ) | |||
|
133 | sa_session.add(user_log) | |||
|
134 | if commit: | |||
|
135 | sa_session.commit() | |||
|
136 | ||||
|
137 | except Exception: | |||
|
138 | log.exception('AUDIT: failed to store audit log') |
@@ -1,3982 +1,3986 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 zope.cachedescriptors.property import Lazy as LazyProperty |
|
45 | from zope.cachedescriptors.property import Lazy as LazyProperty | |
46 |
|
46 | |||
47 | from pylons import url |
|
47 | from pylons import url | |
48 | from pylons.i18n.translation import lazy_ugettext as _ |
|
48 | from pylons.i18n.translation import lazy_ugettext as _ | |
49 |
|
49 | |||
50 | from rhodecode.lib.vcs import get_vcs_instance |
|
50 | from rhodecode.lib.vcs import get_vcs_instance | |
51 | from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference |
|
51 | from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference | |
52 | from rhodecode.lib.utils2 import ( |
|
52 | from rhodecode.lib.utils2 import ( | |
53 | str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe, |
|
53 | str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe, | |
54 | time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict, |
|
54 | time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict, | |
55 | glob2re, StrictAttributeDict, cleaned_uri) |
|
55 | glob2re, StrictAttributeDict, cleaned_uri) | |
56 | from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType |
|
56 | from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType | |
57 | from rhodecode.lib.ext_json import json |
|
57 | from rhodecode.lib.ext_json import json | |
58 | from rhodecode.lib.caching_query import FromCache |
|
58 | from rhodecode.lib.caching_query import FromCache | |
59 | from rhodecode.lib.encrypt import AESCipher |
|
59 | from rhodecode.lib.encrypt import AESCipher | |
60 |
|
60 | |||
61 | from rhodecode.model.meta import Base, Session |
|
61 | from rhodecode.model.meta import Base, Session | |
62 |
|
62 | |||
63 | URL_SEP = '/' |
|
63 | URL_SEP = '/' | |
64 | log = logging.getLogger(__name__) |
|
64 | log = logging.getLogger(__name__) | |
65 |
|
65 | |||
66 | # ============================================================================= |
|
66 | # ============================================================================= | |
67 | # BASE CLASSES |
|
67 | # BASE CLASSES | |
68 | # ============================================================================= |
|
68 | # ============================================================================= | |
69 |
|
69 | |||
70 | # this is propagated from .ini file rhodecode.encrypted_values.secret or |
|
70 | # this is propagated from .ini file rhodecode.encrypted_values.secret or | |
71 | # beaker.session.secret if first is not set. |
|
71 | # beaker.session.secret if first is not set. | |
72 | # and initialized at environment.py |
|
72 | # and initialized at environment.py | |
73 | ENCRYPTION_KEY = None |
|
73 | ENCRYPTION_KEY = None | |
74 |
|
74 | |||
75 | # used to sort permissions by types, '#' used here is not allowed to be in |
|
75 | # used to sort permissions by types, '#' used here is not allowed to be in | |
76 | # usernames, and it's very early in sorted string.printable table. |
|
76 | # usernames, and it's very early in sorted string.printable table. | |
77 | PERMISSION_TYPE_SORT = { |
|
77 | PERMISSION_TYPE_SORT = { | |
78 | 'admin': '####', |
|
78 | 'admin': '####', | |
79 | 'write': '###', |
|
79 | 'write': '###', | |
80 | 'read': '##', |
|
80 | 'read': '##', | |
81 | 'none': '#', |
|
81 | 'none': '#', | |
82 | } |
|
82 | } | |
83 |
|
83 | |||
84 |
|
84 | |||
85 | def display_sort(obj): |
|
85 | def display_sort(obj): | |
86 | """ |
|
86 | """ | |
87 | Sort function used to sort permissions in .permissions() function of |
|
87 | Sort function used to sort permissions in .permissions() function of | |
88 | Repository, RepoGroup, UserGroup. Also it put the default user in front |
|
88 | Repository, RepoGroup, UserGroup. Also it put the default user in front | |
89 | of all other resources |
|
89 | of all other resources | |
90 | """ |
|
90 | """ | |
91 |
|
91 | |||
92 | if obj.username == User.DEFAULT_USER: |
|
92 | if obj.username == User.DEFAULT_USER: | |
93 | return '#####' |
|
93 | return '#####' | |
94 | prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '') |
|
94 | prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '') | |
95 | return prefix + obj.username |
|
95 | return prefix + obj.username | |
96 |
|
96 | |||
97 |
|
97 | |||
98 | def _hash_key(k): |
|
98 | def _hash_key(k): | |
99 | return md5_safe(k) |
|
99 | return md5_safe(k) | |
100 |
|
100 | |||
101 |
|
101 | |||
102 | class EncryptedTextValue(TypeDecorator): |
|
102 | class EncryptedTextValue(TypeDecorator): | |
103 | """ |
|
103 | """ | |
104 | Special column for encrypted long text data, use like:: |
|
104 | Special column for encrypted long text data, use like:: | |
105 |
|
105 | |||
106 | value = Column("encrypted_value", EncryptedValue(), nullable=False) |
|
106 | value = Column("encrypted_value", EncryptedValue(), nullable=False) | |
107 |
|
107 | |||
108 | This column is intelligent so if value is in unencrypted form it return |
|
108 | This column is intelligent so if value is in unencrypted form it return | |
109 | unencrypted form, but on save it always encrypts |
|
109 | unencrypted form, but on save it always encrypts | |
110 | """ |
|
110 | """ | |
111 | impl = Text |
|
111 | impl = Text | |
112 |
|
112 | |||
113 | def process_bind_param(self, value, dialect): |
|
113 | def process_bind_param(self, value, dialect): | |
114 | if not value: |
|
114 | if not value: | |
115 | return value |
|
115 | return value | |
116 | if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'): |
|
116 | if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'): | |
117 | # protect against double encrypting if someone manually starts |
|
117 | # protect against double encrypting if someone manually starts | |
118 | # doing |
|
118 | # doing | |
119 | raise ValueError('value needs to be in unencrypted format, ie. ' |
|
119 | raise ValueError('value needs to be in unencrypted format, ie. ' | |
120 | 'not starting with enc$aes') |
|
120 | 'not starting with enc$aes') | |
121 | return 'enc$aes_hmac$%s' % AESCipher( |
|
121 | return 'enc$aes_hmac$%s' % AESCipher( | |
122 | ENCRYPTION_KEY, hmac=True).encrypt(value) |
|
122 | ENCRYPTION_KEY, hmac=True).encrypt(value) | |
123 |
|
123 | |||
124 | def process_result_value(self, value, dialect): |
|
124 | def process_result_value(self, value, dialect): | |
125 | import rhodecode |
|
125 | import rhodecode | |
126 |
|
126 | |||
127 | if not value: |
|
127 | if not value: | |
128 | return value |
|
128 | return value | |
129 |
|
129 | |||
130 | parts = value.split('$', 3) |
|
130 | parts = value.split('$', 3) | |
131 | if not len(parts) == 3: |
|
131 | if not len(parts) == 3: | |
132 | # probably not encrypted values |
|
132 | # probably not encrypted values | |
133 | return value |
|
133 | return value | |
134 | else: |
|
134 | else: | |
135 | if parts[0] != 'enc': |
|
135 | if parts[0] != 'enc': | |
136 | # parts ok but without our header ? |
|
136 | # parts ok but without our header ? | |
137 | return value |
|
137 | return value | |
138 | enc_strict_mode = str2bool(rhodecode.CONFIG.get( |
|
138 | enc_strict_mode = str2bool(rhodecode.CONFIG.get( | |
139 | 'rhodecode.encrypted_values.strict') or True) |
|
139 | 'rhodecode.encrypted_values.strict') or True) | |
140 | # at that stage we know it's our encryption |
|
140 | # at that stage we know it's our encryption | |
141 | if parts[1] == 'aes': |
|
141 | if parts[1] == 'aes': | |
142 | decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2]) |
|
142 | decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2]) | |
143 | elif parts[1] == 'aes_hmac': |
|
143 | elif parts[1] == 'aes_hmac': | |
144 | decrypted_data = AESCipher( |
|
144 | decrypted_data = AESCipher( | |
145 | ENCRYPTION_KEY, hmac=True, |
|
145 | ENCRYPTION_KEY, hmac=True, | |
146 | strict_verification=enc_strict_mode).decrypt(parts[2]) |
|
146 | strict_verification=enc_strict_mode).decrypt(parts[2]) | |
147 | else: |
|
147 | else: | |
148 | raise ValueError( |
|
148 | raise ValueError( | |
149 | 'Encryption type part is wrong, must be `aes` ' |
|
149 | 'Encryption type part is wrong, must be `aes` ' | |
150 | 'or `aes_hmac`, got `%s` instead' % (parts[1])) |
|
150 | 'or `aes_hmac`, got `%s` instead' % (parts[1])) | |
151 | return decrypted_data |
|
151 | return decrypted_data | |
152 |
|
152 | |||
153 |
|
153 | |||
154 | class BaseModel(object): |
|
154 | class BaseModel(object): | |
155 | """ |
|
155 | """ | |
156 | Base Model for all classes |
|
156 | Base Model for all classes | |
157 | """ |
|
157 | """ | |
158 |
|
158 | |||
159 | @classmethod |
|
159 | @classmethod | |
160 | def _get_keys(cls): |
|
160 | def _get_keys(cls): | |
161 | """return column names for this model """ |
|
161 | """return column names for this model """ | |
162 | return class_mapper(cls).c.keys() |
|
162 | return class_mapper(cls).c.keys() | |
163 |
|
163 | |||
164 | def get_dict(self): |
|
164 | def get_dict(self): | |
165 | """ |
|
165 | """ | |
166 | return dict with keys and values corresponding |
|
166 | return dict with keys and values corresponding | |
167 | to this model data """ |
|
167 | to this model data """ | |
168 |
|
168 | |||
169 | d = {} |
|
169 | d = {} | |
170 | for k in self._get_keys(): |
|
170 | for k in self._get_keys(): | |
171 | d[k] = getattr(self, k) |
|
171 | d[k] = getattr(self, k) | |
172 |
|
172 | |||
173 | # also use __json__() if present to get additional fields |
|
173 | # also use __json__() if present to get additional fields | |
174 | _json_attr = getattr(self, '__json__', None) |
|
174 | _json_attr = getattr(self, '__json__', None) | |
175 | if _json_attr: |
|
175 | if _json_attr: | |
176 | # update with attributes from __json__ |
|
176 | # update with attributes from __json__ | |
177 | if callable(_json_attr): |
|
177 | if callable(_json_attr): | |
178 | _json_attr = _json_attr() |
|
178 | _json_attr = _json_attr() | |
179 | for k, val in _json_attr.iteritems(): |
|
179 | for k, val in _json_attr.iteritems(): | |
180 | d[k] = val |
|
180 | d[k] = val | |
181 | return d |
|
181 | return d | |
182 |
|
182 | |||
183 | def get_appstruct(self): |
|
183 | def get_appstruct(self): | |
184 | """return list with keys and values tuples corresponding |
|
184 | """return list with keys and values tuples corresponding | |
185 | to this model data """ |
|
185 | to this model data """ | |
186 |
|
186 | |||
187 | l = [] |
|
187 | l = [] | |
188 | for k in self._get_keys(): |
|
188 | for k in self._get_keys(): | |
189 | l.append((k, getattr(self, k),)) |
|
189 | l.append((k, getattr(self, k),)) | |
190 | return l |
|
190 | return l | |
191 |
|
191 | |||
192 | def populate_obj(self, populate_dict): |
|
192 | def populate_obj(self, populate_dict): | |
193 | """populate model with data from given populate_dict""" |
|
193 | """populate model with data from given populate_dict""" | |
194 |
|
194 | |||
195 | for k in self._get_keys(): |
|
195 | for k in self._get_keys(): | |
196 | if k in populate_dict: |
|
196 | if k in populate_dict: | |
197 | setattr(self, k, populate_dict[k]) |
|
197 | setattr(self, k, populate_dict[k]) | |
198 |
|
198 | |||
199 | @classmethod |
|
199 | @classmethod | |
200 | def query(cls): |
|
200 | def query(cls): | |
201 | return Session().query(cls) |
|
201 | return Session().query(cls) | |
202 |
|
202 | |||
203 | @classmethod |
|
203 | @classmethod | |
204 | def get(cls, id_): |
|
204 | def get(cls, id_): | |
205 | if id_: |
|
205 | if id_: | |
206 | return cls.query().get(id_) |
|
206 | return cls.query().get(id_) | |
207 |
|
207 | |||
208 | @classmethod |
|
208 | @classmethod | |
209 | def get_or_404(cls, id_, pyramid_exc=False): |
|
209 | def get_or_404(cls, id_, pyramid_exc=False): | |
210 | if pyramid_exc: |
|
210 | if pyramid_exc: | |
211 | # NOTE(marcink): backward compat, once migration to pyramid |
|
211 | # NOTE(marcink): backward compat, once migration to pyramid | |
212 | # this should only use pyramid exceptions |
|
212 | # this should only use pyramid exceptions | |
213 | from pyramid.httpexceptions import HTTPNotFound |
|
213 | from pyramid.httpexceptions import HTTPNotFound | |
214 | else: |
|
214 | else: | |
215 | from webob.exc import HTTPNotFound |
|
215 | from webob.exc import HTTPNotFound | |
216 |
|
216 | |||
217 | try: |
|
217 | try: | |
218 | id_ = int(id_) |
|
218 | id_ = int(id_) | |
219 | except (TypeError, ValueError): |
|
219 | except (TypeError, ValueError): | |
220 | raise HTTPNotFound |
|
220 | raise HTTPNotFound | |
221 |
|
221 | |||
222 | res = cls.query().get(id_) |
|
222 | res = cls.query().get(id_) | |
223 | if not res: |
|
223 | if not res: | |
224 | raise HTTPNotFound |
|
224 | raise HTTPNotFound | |
225 | return res |
|
225 | return res | |
226 |
|
226 | |||
227 | @classmethod |
|
227 | @classmethod | |
228 | def getAll(cls): |
|
228 | def getAll(cls): | |
229 | # deprecated and left for backward compatibility |
|
229 | # deprecated and left for backward compatibility | |
230 | return cls.get_all() |
|
230 | return cls.get_all() | |
231 |
|
231 | |||
232 | @classmethod |
|
232 | @classmethod | |
233 | def get_all(cls): |
|
233 | def get_all(cls): | |
234 | return cls.query().all() |
|
234 | return cls.query().all() | |
235 |
|
235 | |||
236 | @classmethod |
|
236 | @classmethod | |
237 | def delete(cls, id_): |
|
237 | def delete(cls, id_): | |
238 | obj = cls.query().get(id_) |
|
238 | obj = cls.query().get(id_) | |
239 | Session().delete(obj) |
|
239 | Session().delete(obj) | |
240 |
|
240 | |||
241 | @classmethod |
|
241 | @classmethod | |
242 | def identity_cache(cls, session, attr_name, value): |
|
242 | def identity_cache(cls, session, attr_name, value): | |
243 | exist_in_session = [] |
|
243 | exist_in_session = [] | |
244 | for (item_cls, pkey), instance in session.identity_map.items(): |
|
244 | for (item_cls, pkey), instance in session.identity_map.items(): | |
245 | if cls == item_cls and getattr(instance, attr_name) == value: |
|
245 | if cls == item_cls and getattr(instance, attr_name) == value: | |
246 | exist_in_session.append(instance) |
|
246 | exist_in_session.append(instance) | |
247 | if exist_in_session: |
|
247 | if exist_in_session: | |
248 | if len(exist_in_session) == 1: |
|
248 | if len(exist_in_session) == 1: | |
249 | return exist_in_session[0] |
|
249 | return exist_in_session[0] | |
250 | log.exception( |
|
250 | log.exception( | |
251 | 'multiple objects with attr %s and ' |
|
251 | 'multiple objects with attr %s and ' | |
252 | 'value %s found with same name: %r', |
|
252 | 'value %s found with same name: %r', | |
253 | attr_name, value, exist_in_session) |
|
253 | attr_name, value, exist_in_session) | |
254 |
|
254 | |||
255 | def __repr__(self): |
|
255 | def __repr__(self): | |
256 | if hasattr(self, '__unicode__'): |
|
256 | if hasattr(self, '__unicode__'): | |
257 | # python repr needs to return str |
|
257 | # python repr needs to return str | |
258 | try: |
|
258 | try: | |
259 | return safe_str(self.__unicode__()) |
|
259 | return safe_str(self.__unicode__()) | |
260 | except UnicodeDecodeError: |
|
260 | except UnicodeDecodeError: | |
261 | pass |
|
261 | pass | |
262 | return '<DB:%s>' % (self.__class__.__name__) |
|
262 | return '<DB:%s>' % (self.__class__.__name__) | |
263 |
|
263 | |||
264 |
|
264 | |||
265 | class RhodeCodeSetting(Base, BaseModel): |
|
265 | class RhodeCodeSetting(Base, BaseModel): | |
266 | __tablename__ = 'rhodecode_settings' |
|
266 | __tablename__ = 'rhodecode_settings' | |
267 | __table_args__ = ( |
|
267 | __table_args__ = ( | |
268 | UniqueConstraint('app_settings_name'), |
|
268 | UniqueConstraint('app_settings_name'), | |
269 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
269 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
270 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
270 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
271 | ) |
|
271 | ) | |
272 |
|
272 | |||
273 | SETTINGS_TYPES = { |
|
273 | SETTINGS_TYPES = { | |
274 | 'str': safe_str, |
|
274 | 'str': safe_str, | |
275 | 'int': safe_int, |
|
275 | 'int': safe_int, | |
276 | 'unicode': safe_unicode, |
|
276 | 'unicode': safe_unicode, | |
277 | 'bool': str2bool, |
|
277 | 'bool': str2bool, | |
278 | 'list': functools.partial(aslist, sep=',') |
|
278 | 'list': functools.partial(aslist, sep=',') | |
279 | } |
|
279 | } | |
280 | DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions' |
|
280 | DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions' | |
281 | GLOBAL_CONF_KEY = 'app_settings' |
|
281 | GLOBAL_CONF_KEY = 'app_settings' | |
282 |
|
282 | |||
283 | app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
283 | app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
284 | app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None) |
|
284 | app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None) | |
285 | _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None) |
|
285 | _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None) | |
286 | _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None) |
|
286 | _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None) | |
287 |
|
287 | |||
288 | def __init__(self, key='', val='', type='unicode'): |
|
288 | def __init__(self, key='', val='', type='unicode'): | |
289 | self.app_settings_name = key |
|
289 | self.app_settings_name = key | |
290 | self.app_settings_type = type |
|
290 | self.app_settings_type = type | |
291 | self.app_settings_value = val |
|
291 | self.app_settings_value = val | |
292 |
|
292 | |||
293 | @validates('_app_settings_value') |
|
293 | @validates('_app_settings_value') | |
294 | def validate_settings_value(self, key, val): |
|
294 | def validate_settings_value(self, key, val): | |
295 | assert type(val) == unicode |
|
295 | assert type(val) == unicode | |
296 | return val |
|
296 | return val | |
297 |
|
297 | |||
298 | @hybrid_property |
|
298 | @hybrid_property | |
299 | def app_settings_value(self): |
|
299 | def app_settings_value(self): | |
300 | v = self._app_settings_value |
|
300 | v = self._app_settings_value | |
301 | _type = self.app_settings_type |
|
301 | _type = self.app_settings_type | |
302 | if _type: |
|
302 | if _type: | |
303 | _type = self.app_settings_type.split('.')[0] |
|
303 | _type = self.app_settings_type.split('.')[0] | |
304 | # decode the encrypted value |
|
304 | # decode the encrypted value | |
305 | if 'encrypted' in self.app_settings_type: |
|
305 | if 'encrypted' in self.app_settings_type: | |
306 | cipher = EncryptedTextValue() |
|
306 | cipher = EncryptedTextValue() | |
307 | v = safe_unicode(cipher.process_result_value(v, None)) |
|
307 | v = safe_unicode(cipher.process_result_value(v, None)) | |
308 |
|
308 | |||
309 | converter = self.SETTINGS_TYPES.get(_type) or \ |
|
309 | converter = self.SETTINGS_TYPES.get(_type) or \ | |
310 | self.SETTINGS_TYPES['unicode'] |
|
310 | self.SETTINGS_TYPES['unicode'] | |
311 | return converter(v) |
|
311 | return converter(v) | |
312 |
|
312 | |||
313 | @app_settings_value.setter |
|
313 | @app_settings_value.setter | |
314 | def app_settings_value(self, val): |
|
314 | def app_settings_value(self, val): | |
315 | """ |
|
315 | """ | |
316 | Setter that will always make sure we use unicode in app_settings_value |
|
316 | Setter that will always make sure we use unicode in app_settings_value | |
317 |
|
317 | |||
318 | :param val: |
|
318 | :param val: | |
319 | """ |
|
319 | """ | |
320 | val = safe_unicode(val) |
|
320 | val = safe_unicode(val) | |
321 | # encode the encrypted value |
|
321 | # encode the encrypted value | |
322 | if 'encrypted' in self.app_settings_type: |
|
322 | if 'encrypted' in self.app_settings_type: | |
323 | cipher = EncryptedTextValue() |
|
323 | cipher = EncryptedTextValue() | |
324 | val = safe_unicode(cipher.process_bind_param(val, None)) |
|
324 | val = safe_unicode(cipher.process_bind_param(val, None)) | |
325 | self._app_settings_value = val |
|
325 | self._app_settings_value = val | |
326 |
|
326 | |||
327 | @hybrid_property |
|
327 | @hybrid_property | |
328 | def app_settings_type(self): |
|
328 | def app_settings_type(self): | |
329 | return self._app_settings_type |
|
329 | return self._app_settings_type | |
330 |
|
330 | |||
331 | @app_settings_type.setter |
|
331 | @app_settings_type.setter | |
332 | def app_settings_type(self, val): |
|
332 | def app_settings_type(self, val): | |
333 | if val.split('.')[0] not in self.SETTINGS_TYPES: |
|
333 | if val.split('.')[0] not in self.SETTINGS_TYPES: | |
334 | raise Exception('type must be one of %s got %s' |
|
334 | raise Exception('type must be one of %s got %s' | |
335 | % (self.SETTINGS_TYPES.keys(), val)) |
|
335 | % (self.SETTINGS_TYPES.keys(), val)) | |
336 | self._app_settings_type = val |
|
336 | self._app_settings_type = val | |
337 |
|
337 | |||
338 | def __unicode__(self): |
|
338 | def __unicode__(self): | |
339 | return u"<%s('%s:%s[%s]')>" % ( |
|
339 | return u"<%s('%s:%s[%s]')>" % ( | |
340 | self.__class__.__name__, |
|
340 | self.__class__.__name__, | |
341 | self.app_settings_name, self.app_settings_value, |
|
341 | self.app_settings_name, self.app_settings_value, | |
342 | self.app_settings_type |
|
342 | self.app_settings_type | |
343 | ) |
|
343 | ) | |
344 |
|
344 | |||
345 |
|
345 | |||
346 | class RhodeCodeUi(Base, BaseModel): |
|
346 | class RhodeCodeUi(Base, BaseModel): | |
347 | __tablename__ = 'rhodecode_ui' |
|
347 | __tablename__ = 'rhodecode_ui' | |
348 | __table_args__ = ( |
|
348 | __table_args__ = ( | |
349 | UniqueConstraint('ui_key'), |
|
349 | UniqueConstraint('ui_key'), | |
350 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
350 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
351 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
351 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
352 | ) |
|
352 | ) | |
353 |
|
353 | |||
354 | HOOK_REPO_SIZE = 'changegroup.repo_size' |
|
354 | HOOK_REPO_SIZE = 'changegroup.repo_size' | |
355 | # HG |
|
355 | # HG | |
356 | HOOK_PRE_PULL = 'preoutgoing.pre_pull' |
|
356 | HOOK_PRE_PULL = 'preoutgoing.pre_pull' | |
357 | HOOK_PULL = 'outgoing.pull_logger' |
|
357 | HOOK_PULL = 'outgoing.pull_logger' | |
358 | HOOK_PRE_PUSH = 'prechangegroup.pre_push' |
|
358 | HOOK_PRE_PUSH = 'prechangegroup.pre_push' | |
359 | HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push' |
|
359 | HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push' | |
360 | HOOK_PUSH = 'changegroup.push_logger' |
|
360 | HOOK_PUSH = 'changegroup.push_logger' | |
361 |
|
361 | |||
362 | # TODO: johbo: Unify way how hooks are configured for git and hg, |
|
362 | # TODO: johbo: Unify way how hooks are configured for git and hg, | |
363 | # git part is currently hardcoded. |
|
363 | # git part is currently hardcoded. | |
364 |
|
364 | |||
365 | # SVN PATTERNS |
|
365 | # SVN PATTERNS | |
366 | SVN_BRANCH_ID = 'vcs_svn_branch' |
|
366 | SVN_BRANCH_ID = 'vcs_svn_branch' | |
367 | SVN_TAG_ID = 'vcs_svn_tag' |
|
367 | SVN_TAG_ID = 'vcs_svn_tag' | |
368 |
|
368 | |||
369 | ui_id = Column( |
|
369 | ui_id = Column( | |
370 | "ui_id", Integer(), nullable=False, unique=True, default=None, |
|
370 | "ui_id", Integer(), nullable=False, unique=True, default=None, | |
371 | primary_key=True) |
|
371 | primary_key=True) | |
372 | ui_section = Column( |
|
372 | ui_section = Column( | |
373 | "ui_section", String(255), nullable=True, unique=None, default=None) |
|
373 | "ui_section", String(255), nullable=True, unique=None, default=None) | |
374 | ui_key = Column( |
|
374 | ui_key = Column( | |
375 | "ui_key", String(255), nullable=True, unique=None, default=None) |
|
375 | "ui_key", String(255), nullable=True, unique=None, default=None) | |
376 | ui_value = Column( |
|
376 | ui_value = Column( | |
377 | "ui_value", String(255), nullable=True, unique=None, default=None) |
|
377 | "ui_value", String(255), nullable=True, unique=None, default=None) | |
378 | ui_active = Column( |
|
378 | ui_active = Column( | |
379 | "ui_active", Boolean(), nullable=True, unique=None, default=True) |
|
379 | "ui_active", Boolean(), nullable=True, unique=None, default=True) | |
380 |
|
380 | |||
381 | def __repr__(self): |
|
381 | def __repr__(self): | |
382 | return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section, |
|
382 | return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section, | |
383 | self.ui_key, self.ui_value) |
|
383 | self.ui_key, self.ui_value) | |
384 |
|
384 | |||
385 |
|
385 | |||
386 | class RepoRhodeCodeSetting(Base, BaseModel): |
|
386 | class RepoRhodeCodeSetting(Base, BaseModel): | |
387 | __tablename__ = 'repo_rhodecode_settings' |
|
387 | __tablename__ = 'repo_rhodecode_settings' | |
388 | __table_args__ = ( |
|
388 | __table_args__ = ( | |
389 | UniqueConstraint( |
|
389 | UniqueConstraint( | |
390 | 'app_settings_name', 'repository_id', |
|
390 | 'app_settings_name', 'repository_id', | |
391 | name='uq_repo_rhodecode_setting_name_repo_id'), |
|
391 | name='uq_repo_rhodecode_setting_name_repo_id'), | |
392 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
392 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
393 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
393 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
394 | ) |
|
394 | ) | |
395 |
|
395 | |||
396 | repository_id = Column( |
|
396 | repository_id = Column( | |
397 | "repository_id", Integer(), ForeignKey('repositories.repo_id'), |
|
397 | "repository_id", Integer(), ForeignKey('repositories.repo_id'), | |
398 | nullable=False) |
|
398 | nullable=False) | |
399 | app_settings_id = Column( |
|
399 | app_settings_id = Column( | |
400 | "app_settings_id", Integer(), nullable=False, unique=True, |
|
400 | "app_settings_id", Integer(), nullable=False, unique=True, | |
401 | default=None, primary_key=True) |
|
401 | default=None, primary_key=True) | |
402 | app_settings_name = Column( |
|
402 | app_settings_name = Column( | |
403 | "app_settings_name", String(255), nullable=True, unique=None, |
|
403 | "app_settings_name", String(255), nullable=True, unique=None, | |
404 | default=None) |
|
404 | default=None) | |
405 | _app_settings_value = Column( |
|
405 | _app_settings_value = Column( | |
406 | "app_settings_value", String(4096), nullable=True, unique=None, |
|
406 | "app_settings_value", String(4096), nullable=True, unique=None, | |
407 | default=None) |
|
407 | default=None) | |
408 | _app_settings_type = Column( |
|
408 | _app_settings_type = Column( | |
409 | "app_settings_type", String(255), nullable=True, unique=None, |
|
409 | "app_settings_type", String(255), nullable=True, unique=None, | |
410 | default=None) |
|
410 | default=None) | |
411 |
|
411 | |||
412 | repository = relationship('Repository') |
|
412 | repository = relationship('Repository') | |
413 |
|
413 | |||
414 | def __init__(self, repository_id, key='', val='', type='unicode'): |
|
414 | def __init__(self, repository_id, key='', val='', type='unicode'): | |
415 | self.repository_id = repository_id |
|
415 | self.repository_id = repository_id | |
416 | self.app_settings_name = key |
|
416 | self.app_settings_name = key | |
417 | self.app_settings_type = type |
|
417 | self.app_settings_type = type | |
418 | self.app_settings_value = val |
|
418 | self.app_settings_value = val | |
419 |
|
419 | |||
420 | @validates('_app_settings_value') |
|
420 | @validates('_app_settings_value') | |
421 | def validate_settings_value(self, key, val): |
|
421 | def validate_settings_value(self, key, val): | |
422 | assert type(val) == unicode |
|
422 | assert type(val) == unicode | |
423 | return val |
|
423 | return val | |
424 |
|
424 | |||
425 | @hybrid_property |
|
425 | @hybrid_property | |
426 | def app_settings_value(self): |
|
426 | def app_settings_value(self): | |
427 | v = self._app_settings_value |
|
427 | v = self._app_settings_value | |
428 | type_ = self.app_settings_type |
|
428 | type_ = self.app_settings_type | |
429 | SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES |
|
429 | SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES | |
430 | converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode'] |
|
430 | converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode'] | |
431 | return converter(v) |
|
431 | return converter(v) | |
432 |
|
432 | |||
433 | @app_settings_value.setter |
|
433 | @app_settings_value.setter | |
434 | def app_settings_value(self, val): |
|
434 | def app_settings_value(self, val): | |
435 | """ |
|
435 | """ | |
436 | Setter that will always make sure we use unicode in app_settings_value |
|
436 | Setter that will always make sure we use unicode in app_settings_value | |
437 |
|
437 | |||
438 | :param val: |
|
438 | :param val: | |
439 | """ |
|
439 | """ | |
440 | self._app_settings_value = safe_unicode(val) |
|
440 | self._app_settings_value = safe_unicode(val) | |
441 |
|
441 | |||
442 | @hybrid_property |
|
442 | @hybrid_property | |
443 | def app_settings_type(self): |
|
443 | def app_settings_type(self): | |
444 | return self._app_settings_type |
|
444 | return self._app_settings_type | |
445 |
|
445 | |||
446 | @app_settings_type.setter |
|
446 | @app_settings_type.setter | |
447 | def app_settings_type(self, val): |
|
447 | def app_settings_type(self, val): | |
448 | SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES |
|
448 | SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES | |
449 | if val not in SETTINGS_TYPES: |
|
449 | if val not in SETTINGS_TYPES: | |
450 | raise Exception('type must be one of %s got %s' |
|
450 | raise Exception('type must be one of %s got %s' | |
451 | % (SETTINGS_TYPES.keys(), val)) |
|
451 | % (SETTINGS_TYPES.keys(), val)) | |
452 | self._app_settings_type = val |
|
452 | self._app_settings_type = val | |
453 |
|
453 | |||
454 | def __unicode__(self): |
|
454 | def __unicode__(self): | |
455 | return u"<%s('%s:%s:%s[%s]')>" % ( |
|
455 | return u"<%s('%s:%s:%s[%s]')>" % ( | |
456 | self.__class__.__name__, self.repository.repo_name, |
|
456 | self.__class__.__name__, self.repository.repo_name, | |
457 | self.app_settings_name, self.app_settings_value, |
|
457 | self.app_settings_name, self.app_settings_value, | |
458 | self.app_settings_type |
|
458 | self.app_settings_type | |
459 | ) |
|
459 | ) | |
460 |
|
460 | |||
461 |
|
461 | |||
462 | class RepoRhodeCodeUi(Base, BaseModel): |
|
462 | class RepoRhodeCodeUi(Base, BaseModel): | |
463 | __tablename__ = 'repo_rhodecode_ui' |
|
463 | __tablename__ = 'repo_rhodecode_ui' | |
464 | __table_args__ = ( |
|
464 | __table_args__ = ( | |
465 | UniqueConstraint( |
|
465 | UniqueConstraint( | |
466 | 'repository_id', 'ui_section', 'ui_key', |
|
466 | 'repository_id', 'ui_section', 'ui_key', | |
467 | name='uq_repo_rhodecode_ui_repository_id_section_key'), |
|
467 | name='uq_repo_rhodecode_ui_repository_id_section_key'), | |
468 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
468 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
469 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
469 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
470 | ) |
|
470 | ) | |
471 |
|
471 | |||
472 | repository_id = Column( |
|
472 | repository_id = Column( | |
473 | "repository_id", Integer(), ForeignKey('repositories.repo_id'), |
|
473 | "repository_id", Integer(), ForeignKey('repositories.repo_id'), | |
474 | nullable=False) |
|
474 | nullable=False) | |
475 | ui_id = Column( |
|
475 | ui_id = Column( | |
476 | "ui_id", Integer(), nullable=False, unique=True, default=None, |
|
476 | "ui_id", Integer(), nullable=False, unique=True, default=None, | |
477 | primary_key=True) |
|
477 | primary_key=True) | |
478 | ui_section = Column( |
|
478 | ui_section = Column( | |
479 | "ui_section", String(255), nullable=True, unique=None, default=None) |
|
479 | "ui_section", String(255), nullable=True, unique=None, default=None) | |
480 | ui_key = Column( |
|
480 | ui_key = Column( | |
481 | "ui_key", String(255), nullable=True, unique=None, default=None) |
|
481 | "ui_key", String(255), nullable=True, unique=None, default=None) | |
482 | ui_value = Column( |
|
482 | ui_value = Column( | |
483 | "ui_value", String(255), nullable=True, unique=None, default=None) |
|
483 | "ui_value", String(255), nullable=True, unique=None, default=None) | |
484 | ui_active = Column( |
|
484 | ui_active = Column( | |
485 | "ui_active", Boolean(), nullable=True, unique=None, default=True) |
|
485 | "ui_active", Boolean(), nullable=True, unique=None, default=True) | |
486 |
|
486 | |||
487 | repository = relationship('Repository') |
|
487 | repository = relationship('Repository') | |
488 |
|
488 | |||
489 | def __repr__(self): |
|
489 | def __repr__(self): | |
490 | return '<%s[%s:%s]%s=>%s]>' % ( |
|
490 | return '<%s[%s:%s]%s=>%s]>' % ( | |
491 | self.__class__.__name__, self.repository.repo_name, |
|
491 | self.__class__.__name__, self.repository.repo_name, | |
492 | self.ui_section, self.ui_key, self.ui_value) |
|
492 | self.ui_section, self.ui_key, self.ui_value) | |
493 |
|
493 | |||
494 |
|
494 | |||
495 | class User(Base, BaseModel): |
|
495 | class User(Base, BaseModel): | |
496 | __tablename__ = 'users' |
|
496 | __tablename__ = 'users' | |
497 | __table_args__ = ( |
|
497 | __table_args__ = ( | |
498 | UniqueConstraint('username'), UniqueConstraint('email'), |
|
498 | UniqueConstraint('username'), UniqueConstraint('email'), | |
499 | Index('u_username_idx', 'username'), |
|
499 | Index('u_username_idx', 'username'), | |
500 | Index('u_email_idx', 'email'), |
|
500 | Index('u_email_idx', 'email'), | |
501 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
501 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
502 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
502 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
503 | ) |
|
503 | ) | |
504 | DEFAULT_USER = 'default' |
|
504 | DEFAULT_USER = 'default' | |
505 | DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org' |
|
505 | DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org' | |
506 | DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}' |
|
506 | DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}' | |
507 |
|
507 | |||
508 | user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
508 | user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
509 | username = Column("username", String(255), nullable=True, unique=None, default=None) |
|
509 | username = Column("username", String(255), nullable=True, unique=None, default=None) | |
510 | password = Column("password", String(255), nullable=True, unique=None, default=None) |
|
510 | password = Column("password", String(255), nullable=True, unique=None, default=None) | |
511 | active = Column("active", Boolean(), nullable=True, unique=None, default=True) |
|
511 | active = Column("active", Boolean(), nullable=True, unique=None, default=True) | |
512 | admin = Column("admin", Boolean(), nullable=True, unique=None, default=False) |
|
512 | admin = Column("admin", Boolean(), nullable=True, unique=None, default=False) | |
513 | name = Column("firstname", String(255), nullable=True, unique=None, default=None) |
|
513 | name = Column("firstname", String(255), nullable=True, unique=None, default=None) | |
514 | lastname = Column("lastname", String(255), nullable=True, unique=None, default=None) |
|
514 | lastname = Column("lastname", String(255), nullable=True, unique=None, default=None) | |
515 | _email = Column("email", String(255), nullable=True, unique=None, default=None) |
|
515 | _email = Column("email", String(255), nullable=True, unique=None, default=None) | |
516 | last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None) |
|
516 | last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None) | |
517 | last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None) |
|
517 | last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None) | |
518 |
|
518 | |||
519 | extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None) |
|
519 | extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None) | |
520 | extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None) |
|
520 | extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None) | |
521 | _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None) |
|
521 | _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None) | |
522 | inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True) |
|
522 | inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True) | |
523 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
523 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
524 | _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data |
|
524 | _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data | |
525 |
|
525 | |||
526 | user_log = relationship('UserLog') |
|
526 | user_log = relationship('UserLog') | |
527 | user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all') |
|
527 | user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all') | |
528 |
|
528 | |||
529 | repositories = relationship('Repository') |
|
529 | repositories = relationship('Repository') | |
530 | repository_groups = relationship('RepoGroup') |
|
530 | repository_groups = relationship('RepoGroup') | |
531 | user_groups = relationship('UserGroup') |
|
531 | user_groups = relationship('UserGroup') | |
532 |
|
532 | |||
533 | user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all') |
|
533 | user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all') | |
534 | followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all') |
|
534 | followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all') | |
535 |
|
535 | |||
536 | repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all') |
|
536 | repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all') | |
537 | repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all') |
|
537 | repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all') | |
538 | user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all') |
|
538 | user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all') | |
539 |
|
539 | |||
540 | group_member = relationship('UserGroupMember', cascade='all') |
|
540 | group_member = relationship('UserGroupMember', cascade='all') | |
541 |
|
541 | |||
542 | notifications = relationship('UserNotification', cascade='all') |
|
542 | notifications = relationship('UserNotification', cascade='all') | |
543 | # notifications assigned to this user |
|
543 | # notifications assigned to this user | |
544 | user_created_notifications = relationship('Notification', cascade='all') |
|
544 | user_created_notifications = relationship('Notification', cascade='all') | |
545 | # comments created by this user |
|
545 | # comments created by this user | |
546 | user_comments = relationship('ChangesetComment', cascade='all') |
|
546 | user_comments = relationship('ChangesetComment', cascade='all') | |
547 | # user profile extra info |
|
547 | # user profile extra info | |
548 | user_emails = relationship('UserEmailMap', cascade='all') |
|
548 | user_emails = relationship('UserEmailMap', cascade='all') | |
549 | user_ip_map = relationship('UserIpMap', cascade='all') |
|
549 | user_ip_map = relationship('UserIpMap', cascade='all') | |
550 | user_auth_tokens = relationship('UserApiKeys', cascade='all') |
|
550 | user_auth_tokens = relationship('UserApiKeys', cascade='all') | |
551 | # gists |
|
551 | # gists | |
552 | user_gists = relationship('Gist', cascade='all') |
|
552 | user_gists = relationship('Gist', cascade='all') | |
553 | # user pull requests |
|
553 | # user pull requests | |
554 | user_pull_requests = relationship('PullRequest', cascade='all') |
|
554 | user_pull_requests = relationship('PullRequest', cascade='all') | |
555 | # external identities |
|
555 | # external identities | |
556 | extenal_identities = relationship( |
|
556 | extenal_identities = relationship( | |
557 | 'ExternalIdentity', |
|
557 | 'ExternalIdentity', | |
558 | primaryjoin="User.user_id==ExternalIdentity.local_user_id", |
|
558 | primaryjoin="User.user_id==ExternalIdentity.local_user_id", | |
559 | cascade='all') |
|
559 | cascade='all') | |
560 |
|
560 | |||
561 | def __unicode__(self): |
|
561 | def __unicode__(self): | |
562 | return u"<%s('id:%s:%s')>" % (self.__class__.__name__, |
|
562 | return u"<%s('id:%s:%s')>" % (self.__class__.__name__, | |
563 | self.user_id, self.username) |
|
563 | self.user_id, self.username) | |
564 |
|
564 | |||
565 | @hybrid_property |
|
565 | @hybrid_property | |
566 | def email(self): |
|
566 | def email(self): | |
567 | return self._email |
|
567 | return self._email | |
568 |
|
568 | |||
569 | @email.setter |
|
569 | @email.setter | |
570 | def email(self, val): |
|
570 | def email(self, val): | |
571 | self._email = val.lower() if val else None |
|
571 | self._email = val.lower() if val else None | |
572 |
|
572 | |||
573 | @hybrid_property |
|
573 | @hybrid_property | |
574 | def api_key(self): |
|
574 | def api_key(self): | |
575 | """ |
|
575 | """ | |
576 | Fetch if exist an auth-token with role ALL connected to this user |
|
576 | Fetch if exist an auth-token with role ALL connected to this user | |
577 | """ |
|
577 | """ | |
578 | user_auth_token = UserApiKeys.query()\ |
|
578 | user_auth_token = UserApiKeys.query()\ | |
579 | .filter(UserApiKeys.user_id == self.user_id)\ |
|
579 | .filter(UserApiKeys.user_id == self.user_id)\ | |
580 | .filter(or_(UserApiKeys.expires == -1, |
|
580 | .filter(or_(UserApiKeys.expires == -1, | |
581 | UserApiKeys.expires >= time.time()))\ |
|
581 | UserApiKeys.expires >= time.time()))\ | |
582 | .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first() |
|
582 | .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first() | |
583 | if user_auth_token: |
|
583 | if user_auth_token: | |
584 | user_auth_token = user_auth_token.api_key |
|
584 | user_auth_token = user_auth_token.api_key | |
585 |
|
585 | |||
586 | return user_auth_token |
|
586 | return user_auth_token | |
587 |
|
587 | |||
588 | @api_key.setter |
|
588 | @api_key.setter | |
589 | def api_key(self, val): |
|
589 | def api_key(self, val): | |
590 | # don't allow to set API key this is deprecated for now |
|
590 | # don't allow to set API key this is deprecated for now | |
591 | self._api_key = None |
|
591 | self._api_key = None | |
592 |
|
592 | |||
593 | @property |
|
593 | @property | |
594 | def firstname(self): |
|
594 | def firstname(self): | |
595 | # alias for future |
|
595 | # alias for future | |
596 | return self.name |
|
596 | return self.name | |
597 |
|
597 | |||
598 | @property |
|
598 | @property | |
599 | def emails(self): |
|
599 | def emails(self): | |
600 | other = UserEmailMap.query().filter(UserEmailMap.user==self).all() |
|
600 | other = UserEmailMap.query().filter(UserEmailMap.user==self).all() | |
601 | return [self.email] + [x.email for x in other] |
|
601 | return [self.email] + [x.email for x in other] | |
602 |
|
602 | |||
603 | @property |
|
603 | @property | |
604 | def auth_tokens(self): |
|
604 | def auth_tokens(self): | |
605 | return [x.api_key for x in self.extra_auth_tokens] |
|
605 | return [x.api_key for x in self.extra_auth_tokens] | |
606 |
|
606 | |||
607 | @property |
|
607 | @property | |
608 | def extra_auth_tokens(self): |
|
608 | def extra_auth_tokens(self): | |
609 | return UserApiKeys.query().filter(UserApiKeys.user == self).all() |
|
609 | return UserApiKeys.query().filter(UserApiKeys.user == self).all() | |
610 |
|
610 | |||
611 | @property |
|
611 | @property | |
612 | def feed_token(self): |
|
612 | def feed_token(self): | |
613 | return self.get_feed_token() |
|
613 | return self.get_feed_token() | |
614 |
|
614 | |||
615 | def get_feed_token(self): |
|
615 | def get_feed_token(self): | |
616 | feed_tokens = UserApiKeys.query()\ |
|
616 | feed_tokens = UserApiKeys.query()\ | |
617 | .filter(UserApiKeys.user == self)\ |
|
617 | .filter(UserApiKeys.user == self)\ | |
618 | .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\ |
|
618 | .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\ | |
619 | .all() |
|
619 | .all() | |
620 | if feed_tokens: |
|
620 | if feed_tokens: | |
621 | return feed_tokens[0].api_key |
|
621 | return feed_tokens[0].api_key | |
622 | return 'NO_FEED_TOKEN_AVAILABLE' |
|
622 | return 'NO_FEED_TOKEN_AVAILABLE' | |
623 |
|
623 | |||
624 | @classmethod |
|
624 | @classmethod | |
625 | def extra_valid_auth_tokens(cls, user, role=None): |
|
625 | def extra_valid_auth_tokens(cls, user, role=None): | |
626 | tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\ |
|
626 | tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\ | |
627 | .filter(or_(UserApiKeys.expires == -1, |
|
627 | .filter(or_(UserApiKeys.expires == -1, | |
628 | UserApiKeys.expires >= time.time())) |
|
628 | UserApiKeys.expires >= time.time())) | |
629 | if role: |
|
629 | if role: | |
630 | tokens = tokens.filter(or_(UserApiKeys.role == role, |
|
630 | tokens = tokens.filter(or_(UserApiKeys.role == role, | |
631 | UserApiKeys.role == UserApiKeys.ROLE_ALL)) |
|
631 | UserApiKeys.role == UserApiKeys.ROLE_ALL)) | |
632 | return tokens.all() |
|
632 | return tokens.all() | |
633 |
|
633 | |||
634 | def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None): |
|
634 | def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None): | |
635 | from rhodecode.lib import auth |
|
635 | from rhodecode.lib import auth | |
636 |
|
636 | |||
637 | log.debug('Trying to authenticate user: %s via auth-token, ' |
|
637 | log.debug('Trying to authenticate user: %s via auth-token, ' | |
638 | 'and roles: %s', self, roles) |
|
638 | 'and roles: %s', self, roles) | |
639 |
|
639 | |||
640 | if not auth_token: |
|
640 | if not auth_token: | |
641 | return False |
|
641 | return False | |
642 |
|
642 | |||
643 | crypto_backend = auth.crypto_backend() |
|
643 | crypto_backend = auth.crypto_backend() | |
644 |
|
644 | |||
645 | roles = (roles or []) + [UserApiKeys.ROLE_ALL] |
|
645 | roles = (roles or []) + [UserApiKeys.ROLE_ALL] | |
646 | tokens_q = UserApiKeys.query()\ |
|
646 | tokens_q = UserApiKeys.query()\ | |
647 | .filter(UserApiKeys.user_id == self.user_id)\ |
|
647 | .filter(UserApiKeys.user_id == self.user_id)\ | |
648 | .filter(or_(UserApiKeys.expires == -1, |
|
648 | .filter(or_(UserApiKeys.expires == -1, | |
649 | UserApiKeys.expires >= time.time())) |
|
649 | UserApiKeys.expires >= time.time())) | |
650 |
|
650 | |||
651 | tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles)) |
|
651 | tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles)) | |
652 |
|
652 | |||
653 | plain_tokens = [] |
|
653 | plain_tokens = [] | |
654 | hash_tokens = [] |
|
654 | hash_tokens = [] | |
655 |
|
655 | |||
656 | for token in tokens_q.all(): |
|
656 | for token in tokens_q.all(): | |
657 | # verify scope first |
|
657 | # verify scope first | |
658 | if token.repo_id: |
|
658 | if token.repo_id: | |
659 | # token has a scope, we need to verify it |
|
659 | # token has a scope, we need to verify it | |
660 | if scope_repo_id != token.repo_id: |
|
660 | if scope_repo_id != token.repo_id: | |
661 | log.debug( |
|
661 | log.debug( | |
662 | 'Scope mismatch: token has a set repo scope: %s, ' |
|
662 | 'Scope mismatch: token has a set repo scope: %s, ' | |
663 | 'and calling scope is:%s, skipping further checks', |
|
663 | 'and calling scope is:%s, skipping further checks', | |
664 | token.repo, scope_repo_id) |
|
664 | token.repo, scope_repo_id) | |
665 | # token has a scope, and it doesn't match, skip token |
|
665 | # token has a scope, and it doesn't match, skip token | |
666 | continue |
|
666 | continue | |
667 |
|
667 | |||
668 | if token.api_key.startswith(crypto_backend.ENC_PREF): |
|
668 | if token.api_key.startswith(crypto_backend.ENC_PREF): | |
669 | hash_tokens.append(token.api_key) |
|
669 | hash_tokens.append(token.api_key) | |
670 | else: |
|
670 | else: | |
671 | plain_tokens.append(token.api_key) |
|
671 | plain_tokens.append(token.api_key) | |
672 |
|
672 | |||
673 | is_plain_match = auth_token in plain_tokens |
|
673 | is_plain_match = auth_token in plain_tokens | |
674 | if is_plain_match: |
|
674 | if is_plain_match: | |
675 | return True |
|
675 | return True | |
676 |
|
676 | |||
677 | for hashed in hash_tokens: |
|
677 | for hashed in hash_tokens: | |
678 | # TODO(marcink): this is expensive to calculate, but most secure |
|
678 | # TODO(marcink): this is expensive to calculate, but most secure | |
679 | match = crypto_backend.hash_check(auth_token, hashed) |
|
679 | match = crypto_backend.hash_check(auth_token, hashed) | |
680 | if match: |
|
680 | if match: | |
681 | return True |
|
681 | return True | |
682 |
|
682 | |||
683 | return False |
|
683 | return False | |
684 |
|
684 | |||
685 | @property |
|
685 | @property | |
686 | def ip_addresses(self): |
|
686 | def ip_addresses(self): | |
687 | ret = UserIpMap.query().filter(UserIpMap.user == self).all() |
|
687 | ret = UserIpMap.query().filter(UserIpMap.user == self).all() | |
688 | return [x.ip_addr for x in ret] |
|
688 | return [x.ip_addr for x in ret] | |
689 |
|
689 | |||
690 | @property |
|
690 | @property | |
691 | def username_and_name(self): |
|
691 | def username_and_name(self): | |
692 | return '%s (%s %s)' % (self.username, self.firstname, self.lastname) |
|
692 | return '%s (%s %s)' % (self.username, self.firstname, self.lastname) | |
693 |
|
693 | |||
694 | @property |
|
694 | @property | |
695 | def username_or_name_or_email(self): |
|
695 | def username_or_name_or_email(self): | |
696 | full_name = self.full_name if self.full_name is not ' ' else None |
|
696 | full_name = self.full_name if self.full_name is not ' ' else None | |
697 | return self.username or full_name or self.email |
|
697 | return self.username or full_name or self.email | |
698 |
|
698 | |||
699 | @property |
|
699 | @property | |
700 | def full_name(self): |
|
700 | def full_name(self): | |
701 | return '%s %s' % (self.firstname, self.lastname) |
|
701 | return '%s %s' % (self.firstname, self.lastname) | |
702 |
|
702 | |||
703 | @property |
|
703 | @property | |
704 | def full_name_or_username(self): |
|
704 | def full_name_or_username(self): | |
705 | return ('%s %s' % (self.firstname, self.lastname) |
|
705 | return ('%s %s' % (self.firstname, self.lastname) | |
706 | if (self.firstname and self.lastname) else self.username) |
|
706 | if (self.firstname and self.lastname) else self.username) | |
707 |
|
707 | |||
708 | @property |
|
708 | @property | |
709 | def full_contact(self): |
|
709 | def full_contact(self): | |
710 | return '%s %s <%s>' % (self.firstname, self.lastname, self.email) |
|
710 | return '%s %s <%s>' % (self.firstname, self.lastname, self.email) | |
711 |
|
711 | |||
712 | @property |
|
712 | @property | |
713 | def short_contact(self): |
|
713 | def short_contact(self): | |
714 | return '%s %s' % (self.firstname, self.lastname) |
|
714 | return '%s %s' % (self.firstname, self.lastname) | |
715 |
|
715 | |||
716 | @property |
|
716 | @property | |
717 | def is_admin(self): |
|
717 | def is_admin(self): | |
718 | return self.admin |
|
718 | return self.admin | |
719 |
|
719 | |||
720 | @property |
|
720 | @property | |
721 | def AuthUser(self): |
|
721 | def AuthUser(self): | |
722 | """ |
|
722 | """ | |
723 | Returns instance of AuthUser for this user |
|
723 | Returns instance of AuthUser for this user | |
724 | """ |
|
724 | """ | |
725 | from rhodecode.lib.auth import AuthUser |
|
725 | from rhodecode.lib.auth import AuthUser | |
726 | return AuthUser(user_id=self.user_id, username=self.username) |
|
726 | return AuthUser(user_id=self.user_id, username=self.username) | |
727 |
|
727 | |||
728 | @hybrid_property |
|
728 | @hybrid_property | |
729 | def user_data(self): |
|
729 | def user_data(self): | |
730 | if not self._user_data: |
|
730 | if not self._user_data: | |
731 | return {} |
|
731 | return {} | |
732 |
|
732 | |||
733 | try: |
|
733 | try: | |
734 | return json.loads(self._user_data) |
|
734 | return json.loads(self._user_data) | |
735 | except TypeError: |
|
735 | except TypeError: | |
736 | return {} |
|
736 | return {} | |
737 |
|
737 | |||
738 | @user_data.setter |
|
738 | @user_data.setter | |
739 | def user_data(self, val): |
|
739 | def user_data(self, val): | |
740 | if not isinstance(val, dict): |
|
740 | if not isinstance(val, dict): | |
741 | raise Exception('user_data must be dict, got %s' % type(val)) |
|
741 | raise Exception('user_data must be dict, got %s' % type(val)) | |
742 | try: |
|
742 | try: | |
743 | self._user_data = json.dumps(val) |
|
743 | self._user_data = json.dumps(val) | |
744 | except Exception: |
|
744 | except Exception: | |
745 | log.error(traceback.format_exc()) |
|
745 | log.error(traceback.format_exc()) | |
746 |
|
746 | |||
747 | @classmethod |
|
747 | @classmethod | |
748 | def get_by_username(cls, username, case_insensitive=False, |
|
748 | def get_by_username(cls, username, case_insensitive=False, | |
749 | cache=False, identity_cache=False): |
|
749 | cache=False, identity_cache=False): | |
750 | session = Session() |
|
750 | session = Session() | |
751 |
|
751 | |||
752 | if case_insensitive: |
|
752 | if case_insensitive: | |
753 | q = cls.query().filter( |
|
753 | q = cls.query().filter( | |
754 | func.lower(cls.username) == func.lower(username)) |
|
754 | func.lower(cls.username) == func.lower(username)) | |
755 | else: |
|
755 | else: | |
756 | q = cls.query().filter(cls.username == username) |
|
756 | q = cls.query().filter(cls.username == username) | |
757 |
|
757 | |||
758 | if cache: |
|
758 | if cache: | |
759 | if identity_cache: |
|
759 | if identity_cache: | |
760 | val = cls.identity_cache(session, 'username', username) |
|
760 | val = cls.identity_cache(session, 'username', username) | |
761 | if val: |
|
761 | if val: | |
762 | return val |
|
762 | return val | |
763 | else: |
|
763 | else: | |
764 | q = q.options( |
|
764 | q = q.options( | |
765 | FromCache("sql_cache_short", |
|
765 | FromCache("sql_cache_short", | |
766 | "get_user_by_name_%s" % _hash_key(username))) |
|
766 | "get_user_by_name_%s" % _hash_key(username))) | |
767 |
|
767 | |||
768 | return q.scalar() |
|
768 | return q.scalar() | |
769 |
|
769 | |||
770 | @classmethod |
|
770 | @classmethod | |
771 | def get_by_auth_token(cls, auth_token, cache=False): |
|
771 | def get_by_auth_token(cls, auth_token, cache=False): | |
772 | q = UserApiKeys.query()\ |
|
772 | q = UserApiKeys.query()\ | |
773 | .filter(UserApiKeys.api_key == auth_token)\ |
|
773 | .filter(UserApiKeys.api_key == auth_token)\ | |
774 | .filter(or_(UserApiKeys.expires == -1, |
|
774 | .filter(or_(UserApiKeys.expires == -1, | |
775 | UserApiKeys.expires >= time.time())) |
|
775 | UserApiKeys.expires >= time.time())) | |
776 | if cache: |
|
776 | if cache: | |
777 | q = q.options(FromCache("sql_cache_short", |
|
777 | q = q.options(FromCache("sql_cache_short", | |
778 | "get_auth_token_%s" % auth_token)) |
|
778 | "get_auth_token_%s" % auth_token)) | |
779 |
|
779 | |||
780 | match = q.first() |
|
780 | match = q.first() | |
781 | if match: |
|
781 | if match: | |
782 | return match.user |
|
782 | return match.user | |
783 |
|
783 | |||
784 | @classmethod |
|
784 | @classmethod | |
785 | def get_by_email(cls, email, case_insensitive=False, cache=False): |
|
785 | def get_by_email(cls, email, case_insensitive=False, cache=False): | |
786 |
|
786 | |||
787 | if case_insensitive: |
|
787 | if case_insensitive: | |
788 | q = cls.query().filter(func.lower(cls.email) == func.lower(email)) |
|
788 | q = cls.query().filter(func.lower(cls.email) == func.lower(email)) | |
789 |
|
789 | |||
790 | else: |
|
790 | else: | |
791 | q = cls.query().filter(cls.email == email) |
|
791 | q = cls.query().filter(cls.email == email) | |
792 |
|
792 | |||
793 | if cache: |
|
793 | if cache: | |
794 | q = q.options(FromCache("sql_cache_short", |
|
794 | q = q.options(FromCache("sql_cache_short", | |
795 | "get_email_key_%s" % _hash_key(email))) |
|
795 | "get_email_key_%s" % _hash_key(email))) | |
796 |
|
796 | |||
797 | ret = q.scalar() |
|
797 | ret = q.scalar() | |
798 | if ret is None: |
|
798 | if ret is None: | |
799 | q = UserEmailMap.query() |
|
799 | q = UserEmailMap.query() | |
800 | # try fetching in alternate email map |
|
800 | # try fetching in alternate email map | |
801 | if case_insensitive: |
|
801 | if case_insensitive: | |
802 | q = q.filter(func.lower(UserEmailMap.email) == func.lower(email)) |
|
802 | q = q.filter(func.lower(UserEmailMap.email) == func.lower(email)) | |
803 | else: |
|
803 | else: | |
804 | q = q.filter(UserEmailMap.email == email) |
|
804 | q = q.filter(UserEmailMap.email == email) | |
805 | q = q.options(joinedload(UserEmailMap.user)) |
|
805 | q = q.options(joinedload(UserEmailMap.user)) | |
806 | if cache: |
|
806 | if cache: | |
807 | q = q.options(FromCache("sql_cache_short", |
|
807 | q = q.options(FromCache("sql_cache_short", | |
808 | "get_email_map_key_%s" % email)) |
|
808 | "get_email_map_key_%s" % email)) | |
809 | ret = getattr(q.scalar(), 'user', None) |
|
809 | ret = getattr(q.scalar(), 'user', None) | |
810 |
|
810 | |||
811 | return ret |
|
811 | return ret | |
812 |
|
812 | |||
813 | @classmethod |
|
813 | @classmethod | |
814 | def get_from_cs_author(cls, author): |
|
814 | def get_from_cs_author(cls, author): | |
815 | """ |
|
815 | """ | |
816 | Tries to get User objects out of commit author string |
|
816 | Tries to get User objects out of commit author string | |
817 |
|
817 | |||
818 | :param author: |
|
818 | :param author: | |
819 | """ |
|
819 | """ | |
820 | from rhodecode.lib.helpers import email, author_name |
|
820 | from rhodecode.lib.helpers import email, author_name | |
821 | # Valid email in the attribute passed, see if they're in the system |
|
821 | # Valid email in the attribute passed, see if they're in the system | |
822 | _email = email(author) |
|
822 | _email = email(author) | |
823 | if _email: |
|
823 | if _email: | |
824 | user = cls.get_by_email(_email, case_insensitive=True) |
|
824 | user = cls.get_by_email(_email, case_insensitive=True) | |
825 | if user: |
|
825 | if user: | |
826 | return user |
|
826 | return user | |
827 | # Maybe we can match by username? |
|
827 | # Maybe we can match by username? | |
828 | _author = author_name(author) |
|
828 | _author = author_name(author) | |
829 | user = cls.get_by_username(_author, case_insensitive=True) |
|
829 | user = cls.get_by_username(_author, case_insensitive=True) | |
830 | if user: |
|
830 | if user: | |
831 | return user |
|
831 | return user | |
832 |
|
832 | |||
833 | def update_userdata(self, **kwargs): |
|
833 | def update_userdata(self, **kwargs): | |
834 | usr = self |
|
834 | usr = self | |
835 | old = usr.user_data |
|
835 | old = usr.user_data | |
836 | old.update(**kwargs) |
|
836 | old.update(**kwargs) | |
837 | usr.user_data = old |
|
837 | usr.user_data = old | |
838 | Session().add(usr) |
|
838 | Session().add(usr) | |
839 | log.debug('updated userdata with ', kwargs) |
|
839 | log.debug('updated userdata with ', kwargs) | |
840 |
|
840 | |||
841 | def update_lastlogin(self): |
|
841 | def update_lastlogin(self): | |
842 | """Update user lastlogin""" |
|
842 | """Update user lastlogin""" | |
843 | self.last_login = datetime.datetime.now() |
|
843 | self.last_login = datetime.datetime.now() | |
844 | Session().add(self) |
|
844 | Session().add(self) | |
845 | log.debug('updated user %s lastlogin', self.username) |
|
845 | log.debug('updated user %s lastlogin', self.username) | |
846 |
|
846 | |||
847 | def update_lastactivity(self): |
|
847 | def update_lastactivity(self): | |
848 | """Update user lastactivity""" |
|
848 | """Update user lastactivity""" | |
849 | self.last_activity = datetime.datetime.now() |
|
849 | self.last_activity = datetime.datetime.now() | |
850 | Session().add(self) |
|
850 | Session().add(self) | |
851 | log.debug('updated user %s lastactivity', self.username) |
|
851 | log.debug('updated user %s lastactivity', self.username) | |
852 |
|
852 | |||
853 | def update_password(self, new_password): |
|
853 | def update_password(self, new_password): | |
854 | from rhodecode.lib.auth import get_crypt_password |
|
854 | from rhodecode.lib.auth import get_crypt_password | |
855 |
|
855 | |||
856 | self.password = get_crypt_password(new_password) |
|
856 | self.password = get_crypt_password(new_password) | |
857 | Session().add(self) |
|
857 | Session().add(self) | |
858 |
|
858 | |||
859 | @classmethod |
|
859 | @classmethod | |
860 | def get_first_super_admin(cls): |
|
860 | def get_first_super_admin(cls): | |
861 | user = User.query().filter(User.admin == true()).first() |
|
861 | user = User.query().filter(User.admin == true()).first() | |
862 | if user is None: |
|
862 | if user is None: | |
863 | raise Exception('FATAL: Missing administrative account!') |
|
863 | raise Exception('FATAL: Missing administrative account!') | |
864 | return user |
|
864 | return user | |
865 |
|
865 | |||
866 | @classmethod |
|
866 | @classmethod | |
867 | def get_all_super_admins(cls): |
|
867 | def get_all_super_admins(cls): | |
868 | """ |
|
868 | """ | |
869 | Returns all admin accounts sorted by username |
|
869 | Returns all admin accounts sorted by username | |
870 | """ |
|
870 | """ | |
871 | return User.query().filter(User.admin == true())\ |
|
871 | return User.query().filter(User.admin == true())\ | |
872 | .order_by(User.username.asc()).all() |
|
872 | .order_by(User.username.asc()).all() | |
873 |
|
873 | |||
874 | @classmethod |
|
874 | @classmethod | |
875 | def get_default_user(cls, cache=False): |
|
875 | def get_default_user(cls, cache=False): | |
876 | user = User.get_by_username(User.DEFAULT_USER, cache=cache) |
|
876 | user = User.get_by_username(User.DEFAULT_USER, cache=cache) | |
877 | if user is None: |
|
877 | if user is None: | |
878 | raise Exception('FATAL: Missing default account!') |
|
878 | raise Exception('FATAL: Missing default account!') | |
879 | return user |
|
879 | return user | |
880 |
|
880 | |||
881 | def _get_default_perms(self, user, suffix=''): |
|
881 | def _get_default_perms(self, user, suffix=''): | |
882 | from rhodecode.model.permission import PermissionModel |
|
882 | from rhodecode.model.permission import PermissionModel | |
883 | return PermissionModel().get_default_perms(user.user_perms, suffix) |
|
883 | return PermissionModel().get_default_perms(user.user_perms, suffix) | |
884 |
|
884 | |||
885 | def get_default_perms(self, suffix=''): |
|
885 | def get_default_perms(self, suffix=''): | |
886 | return self._get_default_perms(self, suffix) |
|
886 | return self._get_default_perms(self, suffix) | |
887 |
|
887 | |||
888 | def get_api_data(self, include_secrets=False, details='full'): |
|
888 | def get_api_data(self, include_secrets=False, details='full'): | |
889 | """ |
|
889 | """ | |
890 | Common function for generating user related data for API |
|
890 | Common function for generating user related data for API | |
891 |
|
891 | |||
892 | :param include_secrets: By default secrets in the API data will be replaced |
|
892 | :param include_secrets: By default secrets in the API data will be replaced | |
893 | by a placeholder value to prevent exposing this data by accident. In case |
|
893 | by a placeholder value to prevent exposing this data by accident. In case | |
894 | this data shall be exposed, set this flag to ``True``. |
|
894 | this data shall be exposed, set this flag to ``True``. | |
895 |
|
895 | |||
896 | :param details: details can be 'basic|full' basic gives only a subset of |
|
896 | :param details: details can be 'basic|full' basic gives only a subset of | |
897 | the available user information that includes user_id, name and emails. |
|
897 | the available user information that includes user_id, name and emails. | |
898 | """ |
|
898 | """ | |
899 | user = self |
|
899 | user = self | |
900 | user_data = self.user_data |
|
900 | user_data = self.user_data | |
901 | data = { |
|
901 | data = { | |
902 | 'user_id': user.user_id, |
|
902 | 'user_id': user.user_id, | |
903 | 'username': user.username, |
|
903 | 'username': user.username, | |
904 | 'firstname': user.name, |
|
904 | 'firstname': user.name, | |
905 | 'lastname': user.lastname, |
|
905 | 'lastname': user.lastname, | |
906 | 'email': user.email, |
|
906 | 'email': user.email, | |
907 | 'emails': user.emails, |
|
907 | 'emails': user.emails, | |
908 | } |
|
908 | } | |
909 | if details == 'basic': |
|
909 | if details == 'basic': | |
910 | return data |
|
910 | return data | |
911 |
|
911 | |||
912 | api_key_length = 40 |
|
912 | api_key_length = 40 | |
913 | api_key_replacement = '*' * api_key_length |
|
913 | api_key_replacement = '*' * api_key_length | |
914 |
|
914 | |||
915 | extras = { |
|
915 | extras = { | |
916 | 'api_keys': [api_key_replacement], |
|
916 | 'api_keys': [api_key_replacement], | |
917 | 'auth_tokens': [api_key_replacement], |
|
917 | 'auth_tokens': [api_key_replacement], | |
918 | 'active': user.active, |
|
918 | 'active': user.active, | |
919 | 'admin': user.admin, |
|
919 | 'admin': user.admin, | |
920 | 'extern_type': user.extern_type, |
|
920 | 'extern_type': user.extern_type, | |
921 | 'extern_name': user.extern_name, |
|
921 | 'extern_name': user.extern_name, | |
922 | 'last_login': user.last_login, |
|
922 | 'last_login': user.last_login, | |
923 | 'last_activity': user.last_activity, |
|
923 | 'last_activity': user.last_activity, | |
924 | 'ip_addresses': user.ip_addresses, |
|
924 | 'ip_addresses': user.ip_addresses, | |
925 | 'language': user_data.get('language') |
|
925 | 'language': user_data.get('language') | |
926 | } |
|
926 | } | |
927 | data.update(extras) |
|
927 | data.update(extras) | |
928 |
|
928 | |||
929 | if include_secrets: |
|
929 | if include_secrets: | |
930 | data['api_keys'] = user.auth_tokens |
|
930 | data['api_keys'] = user.auth_tokens | |
931 | data['auth_tokens'] = user.extra_auth_tokens |
|
931 | data['auth_tokens'] = user.extra_auth_tokens | |
932 | return data |
|
932 | return data | |
933 |
|
933 | |||
934 | def __json__(self): |
|
934 | def __json__(self): | |
935 | data = { |
|
935 | data = { | |
936 | 'full_name': self.full_name, |
|
936 | 'full_name': self.full_name, | |
937 | 'full_name_or_username': self.full_name_or_username, |
|
937 | 'full_name_or_username': self.full_name_or_username, | |
938 | 'short_contact': self.short_contact, |
|
938 | 'short_contact': self.short_contact, | |
939 | 'full_contact': self.full_contact, |
|
939 | 'full_contact': self.full_contact, | |
940 | } |
|
940 | } | |
941 | data.update(self.get_api_data()) |
|
941 | data.update(self.get_api_data()) | |
942 | return data |
|
942 | return data | |
943 |
|
943 | |||
944 |
|
944 | |||
945 | class UserApiKeys(Base, BaseModel): |
|
945 | class UserApiKeys(Base, BaseModel): | |
946 | __tablename__ = 'user_api_keys' |
|
946 | __tablename__ = 'user_api_keys' | |
947 | __table_args__ = ( |
|
947 | __table_args__ = ( | |
948 | Index('uak_api_key_idx', 'api_key'), |
|
948 | Index('uak_api_key_idx', 'api_key'), | |
949 | Index('uak_api_key_expires_idx', 'api_key', 'expires'), |
|
949 | Index('uak_api_key_expires_idx', 'api_key', 'expires'), | |
950 | UniqueConstraint('api_key'), |
|
950 | UniqueConstraint('api_key'), | |
951 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
951 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
952 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
952 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
953 | ) |
|
953 | ) | |
954 | __mapper_args__ = {} |
|
954 | __mapper_args__ = {} | |
955 |
|
955 | |||
956 | # ApiKey role |
|
956 | # ApiKey role | |
957 | ROLE_ALL = 'token_role_all' |
|
957 | ROLE_ALL = 'token_role_all' | |
958 | ROLE_HTTP = 'token_role_http' |
|
958 | ROLE_HTTP = 'token_role_http' | |
959 | ROLE_VCS = 'token_role_vcs' |
|
959 | ROLE_VCS = 'token_role_vcs' | |
960 | ROLE_API = 'token_role_api' |
|
960 | ROLE_API = 'token_role_api' | |
961 | ROLE_FEED = 'token_role_feed' |
|
961 | ROLE_FEED = 'token_role_feed' | |
962 | ROLE_PASSWORD_RESET = 'token_password_reset' |
|
962 | ROLE_PASSWORD_RESET = 'token_password_reset' | |
963 |
|
963 | |||
964 | ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED] |
|
964 | ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED] | |
965 |
|
965 | |||
966 | user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
966 | user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
967 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
967 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) | |
968 | api_key = Column("api_key", String(255), nullable=False, unique=True) |
|
968 | api_key = Column("api_key", String(255), nullable=False, unique=True) | |
969 | description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql')) |
|
969 | description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql')) | |
970 | expires = Column('expires', Float(53), nullable=False) |
|
970 | expires = Column('expires', Float(53), nullable=False) | |
971 | role = Column('role', String(255), nullable=True) |
|
971 | role = Column('role', String(255), nullable=True) | |
972 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
972 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
973 |
|
973 | |||
974 | # scope columns |
|
974 | # scope columns | |
975 | repo_id = Column( |
|
975 | repo_id = Column( | |
976 | 'repo_id', Integer(), ForeignKey('repositories.repo_id'), |
|
976 | 'repo_id', Integer(), ForeignKey('repositories.repo_id'), | |
977 | nullable=True, unique=None, default=None) |
|
977 | nullable=True, unique=None, default=None) | |
978 | repo = relationship('Repository', lazy='joined') |
|
978 | repo = relationship('Repository', lazy='joined') | |
979 |
|
979 | |||
980 | repo_group_id = Column( |
|
980 | repo_group_id = Column( | |
981 | 'repo_group_id', Integer(), ForeignKey('groups.group_id'), |
|
981 | 'repo_group_id', Integer(), ForeignKey('groups.group_id'), | |
982 | nullable=True, unique=None, default=None) |
|
982 | nullable=True, unique=None, default=None) | |
983 | repo_group = relationship('RepoGroup', lazy='joined') |
|
983 | repo_group = relationship('RepoGroup', lazy='joined') | |
984 |
|
984 | |||
985 | user = relationship('User', lazy='joined') |
|
985 | user = relationship('User', lazy='joined') | |
986 |
|
986 | |||
987 | def __unicode__(self): |
|
987 | def __unicode__(self): | |
988 | return u"<%s('%s')>" % (self.__class__.__name__, self.role) |
|
988 | return u"<%s('%s')>" % (self.__class__.__name__, self.role) | |
989 |
|
989 | |||
990 | def __json__(self): |
|
990 | def __json__(self): | |
991 | data = { |
|
991 | data = { | |
992 | 'auth_token': self.api_key, |
|
992 | 'auth_token': self.api_key, | |
993 | 'role': self.role, |
|
993 | 'role': self.role, | |
994 | 'scope': self.scope_humanized, |
|
994 | 'scope': self.scope_humanized, | |
995 | 'expired': self.expired |
|
995 | 'expired': self.expired | |
996 | } |
|
996 | } | |
997 | return data |
|
997 | return data | |
998 |
|
998 | |||
999 | @property |
|
999 | @property | |
1000 | def expired(self): |
|
1000 | def expired(self): | |
1001 | if self.expires == -1: |
|
1001 | if self.expires == -1: | |
1002 | return False |
|
1002 | return False | |
1003 | return time.time() > self.expires |
|
1003 | return time.time() > self.expires | |
1004 |
|
1004 | |||
1005 | @classmethod |
|
1005 | @classmethod | |
1006 | def _get_role_name(cls, role): |
|
1006 | def _get_role_name(cls, role): | |
1007 | return { |
|
1007 | return { | |
1008 | cls.ROLE_ALL: _('all'), |
|
1008 | cls.ROLE_ALL: _('all'), | |
1009 | cls.ROLE_HTTP: _('http/web interface'), |
|
1009 | cls.ROLE_HTTP: _('http/web interface'), | |
1010 | cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'), |
|
1010 | cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'), | |
1011 | cls.ROLE_API: _('api calls'), |
|
1011 | cls.ROLE_API: _('api calls'), | |
1012 | cls.ROLE_FEED: _('feed access'), |
|
1012 | cls.ROLE_FEED: _('feed access'), | |
1013 | }.get(role, role) |
|
1013 | }.get(role, role) | |
1014 |
|
1014 | |||
1015 | @property |
|
1015 | @property | |
1016 | def role_humanized(self): |
|
1016 | def role_humanized(self): | |
1017 | return self._get_role_name(self.role) |
|
1017 | return self._get_role_name(self.role) | |
1018 |
|
1018 | |||
1019 | def _get_scope(self): |
|
1019 | def _get_scope(self): | |
1020 | if self.repo: |
|
1020 | if self.repo: | |
1021 | return repr(self.repo) |
|
1021 | return repr(self.repo) | |
1022 | if self.repo_group: |
|
1022 | if self.repo_group: | |
1023 | return repr(self.repo_group) + ' (recursive)' |
|
1023 | return repr(self.repo_group) + ' (recursive)' | |
1024 | return 'global' |
|
1024 | return 'global' | |
1025 |
|
1025 | |||
1026 | @property |
|
1026 | @property | |
1027 | def scope_humanized(self): |
|
1027 | def scope_humanized(self): | |
1028 | return self._get_scope() |
|
1028 | return self._get_scope() | |
1029 |
|
1029 | |||
1030 |
|
1030 | |||
1031 | class UserEmailMap(Base, BaseModel): |
|
1031 | class UserEmailMap(Base, BaseModel): | |
1032 | __tablename__ = 'user_email_map' |
|
1032 | __tablename__ = 'user_email_map' | |
1033 | __table_args__ = ( |
|
1033 | __table_args__ = ( | |
1034 | Index('uem_email_idx', 'email'), |
|
1034 | Index('uem_email_idx', 'email'), | |
1035 | UniqueConstraint('email'), |
|
1035 | UniqueConstraint('email'), | |
1036 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1036 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
1037 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
1037 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
1038 | ) |
|
1038 | ) | |
1039 | __mapper_args__ = {} |
|
1039 | __mapper_args__ = {} | |
1040 |
|
1040 | |||
1041 | email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1041 | email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
1042 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
1042 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) | |
1043 | _email = Column("email", String(255), nullable=True, unique=False, default=None) |
|
1043 | _email = Column("email", String(255), nullable=True, unique=False, default=None) | |
1044 | user = relationship('User', lazy='joined') |
|
1044 | user = relationship('User', lazy='joined') | |
1045 |
|
1045 | |||
1046 | @validates('_email') |
|
1046 | @validates('_email') | |
1047 | def validate_email(self, key, email): |
|
1047 | def validate_email(self, key, email): | |
1048 | # check if this email is not main one |
|
1048 | # check if this email is not main one | |
1049 | main_email = Session().query(User).filter(User.email == email).scalar() |
|
1049 | main_email = Session().query(User).filter(User.email == email).scalar() | |
1050 | if main_email is not None: |
|
1050 | if main_email is not None: | |
1051 | raise AttributeError('email %s is present is user table' % email) |
|
1051 | raise AttributeError('email %s is present is user table' % email) | |
1052 | return email |
|
1052 | return email | |
1053 |
|
1053 | |||
1054 | @hybrid_property |
|
1054 | @hybrid_property | |
1055 | def email(self): |
|
1055 | def email(self): | |
1056 | return self._email |
|
1056 | return self._email | |
1057 |
|
1057 | |||
1058 | @email.setter |
|
1058 | @email.setter | |
1059 | def email(self, val): |
|
1059 | def email(self, val): | |
1060 | self._email = val.lower() if val else None |
|
1060 | self._email = val.lower() if val else None | |
1061 |
|
1061 | |||
1062 |
|
1062 | |||
1063 | class UserIpMap(Base, BaseModel): |
|
1063 | class UserIpMap(Base, BaseModel): | |
1064 | __tablename__ = 'user_ip_map' |
|
1064 | __tablename__ = 'user_ip_map' | |
1065 | __table_args__ = ( |
|
1065 | __table_args__ = ( | |
1066 | UniqueConstraint('user_id', 'ip_addr'), |
|
1066 | UniqueConstraint('user_id', 'ip_addr'), | |
1067 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1067 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
1068 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
1068 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
1069 | ) |
|
1069 | ) | |
1070 | __mapper_args__ = {} |
|
1070 | __mapper_args__ = {} | |
1071 |
|
1071 | |||
1072 | ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1072 | ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
1073 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
1073 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) | |
1074 | ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None) |
|
1074 | ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None) | |
1075 | active = Column("active", Boolean(), nullable=True, unique=None, default=True) |
|
1075 | active = Column("active", Boolean(), nullable=True, unique=None, default=True) | |
1076 | description = Column("description", String(10000), nullable=True, unique=None, default=None) |
|
1076 | description = Column("description", String(10000), nullable=True, unique=None, default=None) | |
1077 | user = relationship('User', lazy='joined') |
|
1077 | user = relationship('User', lazy='joined') | |
1078 |
|
1078 | |||
1079 | @classmethod |
|
1079 | @classmethod | |
1080 | def _get_ip_range(cls, ip_addr): |
|
1080 | def _get_ip_range(cls, ip_addr): | |
1081 | net = ipaddress.ip_network(ip_addr, strict=False) |
|
1081 | net = ipaddress.ip_network(ip_addr, strict=False) | |
1082 | return [str(net.network_address), str(net.broadcast_address)] |
|
1082 | return [str(net.network_address), str(net.broadcast_address)] | |
1083 |
|
1083 | |||
1084 | def __json__(self): |
|
1084 | def __json__(self): | |
1085 | return { |
|
1085 | return { | |
1086 | 'ip_addr': self.ip_addr, |
|
1086 | 'ip_addr': self.ip_addr, | |
1087 | 'ip_range': self._get_ip_range(self.ip_addr), |
|
1087 | 'ip_range': self._get_ip_range(self.ip_addr), | |
1088 | } |
|
1088 | } | |
1089 |
|
1089 | |||
1090 | def __unicode__(self): |
|
1090 | def __unicode__(self): | |
1091 | return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__, |
|
1091 | return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__, | |
1092 | self.user_id, self.ip_addr) |
|
1092 | self.user_id, self.ip_addr) | |
1093 |
|
1093 | |||
1094 |
|
1094 | |||
1095 | class UserLog(Base, BaseModel): |
|
1095 | class UserLog(Base, BaseModel): | |
1096 | __tablename__ = 'user_logs' |
|
1096 | __tablename__ = 'user_logs' | |
1097 | __table_args__ = ( |
|
1097 | __table_args__ = ( | |
1098 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1098 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
1099 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1099 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
1100 | ) |
|
1100 | ) | |
|
1101 | VERSION_1 = 'v1' | |||
|
1102 | VERSION_2 = 'v2' | |||
|
1103 | VERSIONS = [VERSION_1, VERSION_2] | |||
|
1104 | ||||
1101 | user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1105 | user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
1102 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
1106 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) | |
1103 | username = Column("username", String(255), nullable=True, unique=None, default=None) |
|
1107 | username = Column("username", String(255), nullable=True, unique=None, default=None) | |
1104 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True) |
|
1108 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True) | |
1105 | repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None) |
|
1109 | repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None) | |
1106 | user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None) |
|
1110 | user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None) | |
1107 | action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None) |
|
1111 | action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None) | |
1108 | action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None) |
|
1112 | action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None) | |
1109 |
|
1113 | |||
1110 |
version = Column("version", String(255), nullable=True, default= |
|
1114 | version = Column("version", String(255), nullable=True, default=VERSION_1) | |
1111 | user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384))))) |
|
1115 | user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384))))) | |
1112 | action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384))))) |
|
1116 | action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384))))) | |
1113 |
|
1117 | |||
1114 | def __unicode__(self): |
|
1118 | def __unicode__(self): | |
1115 | return u"<%s('id:%s:%s')>" % ( |
|
1119 | return u"<%s('id:%s:%s')>" % ( | |
1116 | self.__class__.__name__, self.repository_name, self.action) |
|
1120 | self.__class__.__name__, self.repository_name, self.action) | |
1117 |
|
1121 | |||
1118 | def __json__(self): |
|
1122 | def __json__(self): | |
1119 | return { |
|
1123 | return { | |
1120 | 'user_id': self.user_id, |
|
1124 | 'user_id': self.user_id, | |
1121 | 'username': self.username, |
|
1125 | 'username': self.username, | |
1122 | 'repository_id': self.repository_id, |
|
1126 | 'repository_id': self.repository_id, | |
1123 | 'repository_name': self.repository_name, |
|
1127 | 'repository_name': self.repository_name, | |
1124 | 'user_ip': self.user_ip, |
|
1128 | 'user_ip': self.user_ip, | |
1125 | 'action_date': self.action_date, |
|
1129 | 'action_date': self.action_date, | |
1126 | 'action': self.action, |
|
1130 | 'action': self.action, | |
1127 | } |
|
1131 | } | |
1128 |
|
1132 | |||
1129 | @property |
|
1133 | @property | |
1130 | def action_as_day(self): |
|
1134 | def action_as_day(self): | |
1131 | return datetime.date(*self.action_date.timetuple()[:3]) |
|
1135 | return datetime.date(*self.action_date.timetuple()[:3]) | |
1132 |
|
1136 | |||
1133 | user = relationship('User') |
|
1137 | user = relationship('User') | |
1134 | repository = relationship('Repository', cascade='') |
|
1138 | repository = relationship('Repository', cascade='') | |
1135 |
|
1139 | |||
1136 |
|
1140 | |||
1137 | class UserGroup(Base, BaseModel): |
|
1141 | class UserGroup(Base, BaseModel): | |
1138 | __tablename__ = 'users_groups' |
|
1142 | __tablename__ = 'users_groups' | |
1139 | __table_args__ = ( |
|
1143 | __table_args__ = ( | |
1140 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1144 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
1141 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1145 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
1142 | ) |
|
1146 | ) | |
1143 |
|
1147 | |||
1144 | users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1148 | users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
1145 | users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None) |
|
1149 | users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None) | |
1146 | user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None) |
|
1150 | user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None) | |
1147 | users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None) |
|
1151 | users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None) | |
1148 | inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True) |
|
1152 | inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True) | |
1149 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None) |
|
1153 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None) | |
1150 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
1154 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
1151 | _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data |
|
1155 | _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data | |
1152 |
|
1156 | |||
1153 | members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined") |
|
1157 | members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined") | |
1154 | users_group_to_perm = relationship('UserGroupToPerm', cascade='all') |
|
1158 | users_group_to_perm = relationship('UserGroupToPerm', cascade='all') | |
1155 | users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all') |
|
1159 | users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all') | |
1156 | users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all') |
|
1160 | users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all') | |
1157 | user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all') |
|
1161 | user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all') | |
1158 | user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all') |
|
1162 | user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all') | |
1159 |
|
1163 | |||
1160 | user = relationship('User') |
|
1164 | user = relationship('User') | |
1161 |
|
1165 | |||
1162 | @hybrid_property |
|
1166 | @hybrid_property | |
1163 | def group_data(self): |
|
1167 | def group_data(self): | |
1164 | if not self._group_data: |
|
1168 | if not self._group_data: | |
1165 | return {} |
|
1169 | return {} | |
1166 |
|
1170 | |||
1167 | try: |
|
1171 | try: | |
1168 | return json.loads(self._group_data) |
|
1172 | return json.loads(self._group_data) | |
1169 | except TypeError: |
|
1173 | except TypeError: | |
1170 | return {} |
|
1174 | return {} | |
1171 |
|
1175 | |||
1172 | @group_data.setter |
|
1176 | @group_data.setter | |
1173 | def group_data(self, val): |
|
1177 | def group_data(self, val): | |
1174 | try: |
|
1178 | try: | |
1175 | self._group_data = json.dumps(val) |
|
1179 | self._group_data = json.dumps(val) | |
1176 | except Exception: |
|
1180 | except Exception: | |
1177 | log.error(traceback.format_exc()) |
|
1181 | log.error(traceback.format_exc()) | |
1178 |
|
1182 | |||
1179 | def __unicode__(self): |
|
1183 | def __unicode__(self): | |
1180 | return u"<%s('id:%s:%s')>" % (self.__class__.__name__, |
|
1184 | return u"<%s('id:%s:%s')>" % (self.__class__.__name__, | |
1181 | self.users_group_id, |
|
1185 | self.users_group_id, | |
1182 | self.users_group_name) |
|
1186 | self.users_group_name) | |
1183 |
|
1187 | |||
1184 | @classmethod |
|
1188 | @classmethod | |
1185 | def get_by_group_name(cls, group_name, cache=False, |
|
1189 | def get_by_group_name(cls, group_name, cache=False, | |
1186 | case_insensitive=False): |
|
1190 | case_insensitive=False): | |
1187 | if case_insensitive: |
|
1191 | if case_insensitive: | |
1188 | q = cls.query().filter(func.lower(cls.users_group_name) == |
|
1192 | q = cls.query().filter(func.lower(cls.users_group_name) == | |
1189 | func.lower(group_name)) |
|
1193 | func.lower(group_name)) | |
1190 |
|
1194 | |||
1191 | else: |
|
1195 | else: | |
1192 | q = cls.query().filter(cls.users_group_name == group_name) |
|
1196 | q = cls.query().filter(cls.users_group_name == group_name) | |
1193 | if cache: |
|
1197 | if cache: | |
1194 | q = q.options(FromCache( |
|
1198 | q = q.options(FromCache( | |
1195 | "sql_cache_short", |
|
1199 | "sql_cache_short", | |
1196 | "get_group_%s" % _hash_key(group_name))) |
|
1200 | "get_group_%s" % _hash_key(group_name))) | |
1197 | return q.scalar() |
|
1201 | return q.scalar() | |
1198 |
|
1202 | |||
1199 | @classmethod |
|
1203 | @classmethod | |
1200 | def get(cls, user_group_id, cache=False): |
|
1204 | def get(cls, user_group_id, cache=False): | |
1201 | user_group = cls.query() |
|
1205 | user_group = cls.query() | |
1202 | if cache: |
|
1206 | if cache: | |
1203 | user_group = user_group.options(FromCache("sql_cache_short", |
|
1207 | user_group = user_group.options(FromCache("sql_cache_short", | |
1204 | "get_users_group_%s" % user_group_id)) |
|
1208 | "get_users_group_%s" % user_group_id)) | |
1205 | return user_group.get(user_group_id) |
|
1209 | return user_group.get(user_group_id) | |
1206 |
|
1210 | |||
1207 | def permissions(self, with_admins=True, with_owner=True): |
|
1211 | def permissions(self, with_admins=True, with_owner=True): | |
1208 | q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self) |
|
1212 | q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self) | |
1209 | q = q.options(joinedload(UserUserGroupToPerm.user_group), |
|
1213 | q = q.options(joinedload(UserUserGroupToPerm.user_group), | |
1210 | joinedload(UserUserGroupToPerm.user), |
|
1214 | joinedload(UserUserGroupToPerm.user), | |
1211 | joinedload(UserUserGroupToPerm.permission),) |
|
1215 | joinedload(UserUserGroupToPerm.permission),) | |
1212 |
|
1216 | |||
1213 | # get owners and admins and permissions. We do a trick of re-writing |
|
1217 | # get owners and admins and permissions. We do a trick of re-writing | |
1214 | # objects from sqlalchemy to named-tuples due to sqlalchemy session |
|
1218 | # objects from sqlalchemy to named-tuples due to sqlalchemy session | |
1215 | # has a global reference and changing one object propagates to all |
|
1219 | # has a global reference and changing one object propagates to all | |
1216 | # others. This means if admin is also an owner admin_row that change |
|
1220 | # others. This means if admin is also an owner admin_row that change | |
1217 | # would propagate to both objects |
|
1221 | # would propagate to both objects | |
1218 | perm_rows = [] |
|
1222 | perm_rows = [] | |
1219 | for _usr in q.all(): |
|
1223 | for _usr in q.all(): | |
1220 | usr = AttributeDict(_usr.user.get_dict()) |
|
1224 | usr = AttributeDict(_usr.user.get_dict()) | |
1221 | usr.permission = _usr.permission.permission_name |
|
1225 | usr.permission = _usr.permission.permission_name | |
1222 | perm_rows.append(usr) |
|
1226 | perm_rows.append(usr) | |
1223 |
|
1227 | |||
1224 | # filter the perm rows by 'default' first and then sort them by |
|
1228 | # filter the perm rows by 'default' first and then sort them by | |
1225 | # admin,write,read,none permissions sorted again alphabetically in |
|
1229 | # admin,write,read,none permissions sorted again alphabetically in | |
1226 | # each group |
|
1230 | # each group | |
1227 | perm_rows = sorted(perm_rows, key=display_sort) |
|
1231 | perm_rows = sorted(perm_rows, key=display_sort) | |
1228 |
|
1232 | |||
1229 | _admin_perm = 'usergroup.admin' |
|
1233 | _admin_perm = 'usergroup.admin' | |
1230 | owner_row = [] |
|
1234 | owner_row = [] | |
1231 | if with_owner: |
|
1235 | if with_owner: | |
1232 | usr = AttributeDict(self.user.get_dict()) |
|
1236 | usr = AttributeDict(self.user.get_dict()) | |
1233 | usr.owner_row = True |
|
1237 | usr.owner_row = True | |
1234 | usr.permission = _admin_perm |
|
1238 | usr.permission = _admin_perm | |
1235 | owner_row.append(usr) |
|
1239 | owner_row.append(usr) | |
1236 |
|
1240 | |||
1237 | super_admin_rows = [] |
|
1241 | super_admin_rows = [] | |
1238 | if with_admins: |
|
1242 | if with_admins: | |
1239 | for usr in User.get_all_super_admins(): |
|
1243 | for usr in User.get_all_super_admins(): | |
1240 | # if this admin is also owner, don't double the record |
|
1244 | # if this admin is also owner, don't double the record | |
1241 | if usr.user_id == owner_row[0].user_id: |
|
1245 | if usr.user_id == owner_row[0].user_id: | |
1242 | owner_row[0].admin_row = True |
|
1246 | owner_row[0].admin_row = True | |
1243 | else: |
|
1247 | else: | |
1244 | usr = AttributeDict(usr.get_dict()) |
|
1248 | usr = AttributeDict(usr.get_dict()) | |
1245 | usr.admin_row = True |
|
1249 | usr.admin_row = True | |
1246 | usr.permission = _admin_perm |
|
1250 | usr.permission = _admin_perm | |
1247 | super_admin_rows.append(usr) |
|
1251 | super_admin_rows.append(usr) | |
1248 |
|
1252 | |||
1249 | return super_admin_rows + owner_row + perm_rows |
|
1253 | return super_admin_rows + owner_row + perm_rows | |
1250 |
|
1254 | |||
1251 | def permission_user_groups(self): |
|
1255 | def permission_user_groups(self): | |
1252 | q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self) |
|
1256 | q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self) | |
1253 | q = q.options(joinedload(UserGroupUserGroupToPerm.user_group), |
|
1257 | q = q.options(joinedload(UserGroupUserGroupToPerm.user_group), | |
1254 | joinedload(UserGroupUserGroupToPerm.target_user_group), |
|
1258 | joinedload(UserGroupUserGroupToPerm.target_user_group), | |
1255 | joinedload(UserGroupUserGroupToPerm.permission),) |
|
1259 | joinedload(UserGroupUserGroupToPerm.permission),) | |
1256 |
|
1260 | |||
1257 | perm_rows = [] |
|
1261 | perm_rows = [] | |
1258 | for _user_group in q.all(): |
|
1262 | for _user_group in q.all(): | |
1259 | usr = AttributeDict(_user_group.user_group.get_dict()) |
|
1263 | usr = AttributeDict(_user_group.user_group.get_dict()) | |
1260 | usr.permission = _user_group.permission.permission_name |
|
1264 | usr.permission = _user_group.permission.permission_name | |
1261 | perm_rows.append(usr) |
|
1265 | perm_rows.append(usr) | |
1262 |
|
1266 | |||
1263 | return perm_rows |
|
1267 | return perm_rows | |
1264 |
|
1268 | |||
1265 | def _get_default_perms(self, user_group, suffix=''): |
|
1269 | def _get_default_perms(self, user_group, suffix=''): | |
1266 | from rhodecode.model.permission import PermissionModel |
|
1270 | from rhodecode.model.permission import PermissionModel | |
1267 | return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix) |
|
1271 | return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix) | |
1268 |
|
1272 | |||
1269 | def get_default_perms(self, suffix=''): |
|
1273 | def get_default_perms(self, suffix=''): | |
1270 | return self._get_default_perms(self, suffix) |
|
1274 | return self._get_default_perms(self, suffix) | |
1271 |
|
1275 | |||
1272 | def get_api_data(self, with_group_members=True, include_secrets=False): |
|
1276 | def get_api_data(self, with_group_members=True, include_secrets=False): | |
1273 | """ |
|
1277 | """ | |
1274 | :param include_secrets: See :meth:`User.get_api_data`, this parameter is |
|
1278 | :param include_secrets: See :meth:`User.get_api_data`, this parameter is | |
1275 | basically forwarded. |
|
1279 | basically forwarded. | |
1276 |
|
1280 | |||
1277 | """ |
|
1281 | """ | |
1278 | user_group = self |
|
1282 | user_group = self | |
1279 | data = { |
|
1283 | data = { | |
1280 | 'users_group_id': user_group.users_group_id, |
|
1284 | 'users_group_id': user_group.users_group_id, | |
1281 | 'group_name': user_group.users_group_name, |
|
1285 | 'group_name': user_group.users_group_name, | |
1282 | 'group_description': user_group.user_group_description, |
|
1286 | 'group_description': user_group.user_group_description, | |
1283 | 'active': user_group.users_group_active, |
|
1287 | 'active': user_group.users_group_active, | |
1284 | 'owner': user_group.user.username, |
|
1288 | 'owner': user_group.user.username, | |
1285 | 'owner_email': user_group.user.email, |
|
1289 | 'owner_email': user_group.user.email, | |
1286 | } |
|
1290 | } | |
1287 |
|
1291 | |||
1288 | if with_group_members: |
|
1292 | if with_group_members: | |
1289 | users = [] |
|
1293 | users = [] | |
1290 | for user in user_group.members: |
|
1294 | for user in user_group.members: | |
1291 | user = user.user |
|
1295 | user = user.user | |
1292 | users.append(user.get_api_data(include_secrets=include_secrets)) |
|
1296 | users.append(user.get_api_data(include_secrets=include_secrets)) | |
1293 | data['users'] = users |
|
1297 | data['users'] = users | |
1294 |
|
1298 | |||
1295 | return data |
|
1299 | return data | |
1296 |
|
1300 | |||
1297 |
|
1301 | |||
1298 | class UserGroupMember(Base, BaseModel): |
|
1302 | class UserGroupMember(Base, BaseModel): | |
1299 | __tablename__ = 'users_groups_members' |
|
1303 | __tablename__ = 'users_groups_members' | |
1300 | __table_args__ = ( |
|
1304 | __table_args__ = ( | |
1301 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1305 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
1302 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1306 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
1303 | ) |
|
1307 | ) | |
1304 |
|
1308 | |||
1305 | users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1309 | users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
1306 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
1310 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) | |
1307 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
1311 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) | |
1308 |
|
1312 | |||
1309 | user = relationship('User', lazy='joined') |
|
1313 | user = relationship('User', lazy='joined') | |
1310 | users_group = relationship('UserGroup') |
|
1314 | users_group = relationship('UserGroup') | |
1311 |
|
1315 | |||
1312 | def __init__(self, gr_id='', u_id=''): |
|
1316 | def __init__(self, gr_id='', u_id=''): | |
1313 | self.users_group_id = gr_id |
|
1317 | self.users_group_id = gr_id | |
1314 | self.user_id = u_id |
|
1318 | self.user_id = u_id | |
1315 |
|
1319 | |||
1316 |
|
1320 | |||
1317 | class RepositoryField(Base, BaseModel): |
|
1321 | class RepositoryField(Base, BaseModel): | |
1318 | __tablename__ = 'repositories_fields' |
|
1322 | __tablename__ = 'repositories_fields' | |
1319 | __table_args__ = ( |
|
1323 | __table_args__ = ( | |
1320 | UniqueConstraint('repository_id', 'field_key'), # no-multi field |
|
1324 | UniqueConstraint('repository_id', 'field_key'), # no-multi field | |
1321 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1325 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
1322 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1326 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
1323 | ) |
|
1327 | ) | |
1324 | PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields |
|
1328 | PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields | |
1325 |
|
1329 | |||
1326 | repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
1330 | repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
1327 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None) |
|
1331 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None) | |
1328 | field_key = Column("field_key", String(250)) |
|
1332 | field_key = Column("field_key", String(250)) | |
1329 | field_label = Column("field_label", String(1024), nullable=False) |
|
1333 | field_label = Column("field_label", String(1024), nullable=False) | |
1330 | field_value = Column("field_value", String(10000), nullable=False) |
|
1334 | field_value = Column("field_value", String(10000), nullable=False) | |
1331 | field_desc = Column("field_desc", String(1024), nullable=False) |
|
1335 | field_desc = Column("field_desc", String(1024), nullable=False) | |
1332 | field_type = Column("field_type", String(255), nullable=False, unique=None) |
|
1336 | field_type = Column("field_type", String(255), nullable=False, unique=None) | |
1333 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
1337 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
1334 |
|
1338 | |||
1335 | repository = relationship('Repository') |
|
1339 | repository = relationship('Repository') | |
1336 |
|
1340 | |||
1337 | @property |
|
1341 | @property | |
1338 | def field_key_prefixed(self): |
|
1342 | def field_key_prefixed(self): | |
1339 | return 'ex_%s' % self.field_key |
|
1343 | return 'ex_%s' % self.field_key | |
1340 |
|
1344 | |||
1341 | @classmethod |
|
1345 | @classmethod | |
1342 | def un_prefix_key(cls, key): |
|
1346 | def un_prefix_key(cls, key): | |
1343 | if key.startswith(cls.PREFIX): |
|
1347 | if key.startswith(cls.PREFIX): | |
1344 | return key[len(cls.PREFIX):] |
|
1348 | return key[len(cls.PREFIX):] | |
1345 | return key |
|
1349 | return key | |
1346 |
|
1350 | |||
1347 | @classmethod |
|
1351 | @classmethod | |
1348 | def get_by_key_name(cls, key, repo): |
|
1352 | def get_by_key_name(cls, key, repo): | |
1349 | row = cls.query()\ |
|
1353 | row = cls.query()\ | |
1350 | .filter(cls.repository == repo)\ |
|
1354 | .filter(cls.repository == repo)\ | |
1351 | .filter(cls.field_key == key).scalar() |
|
1355 | .filter(cls.field_key == key).scalar() | |
1352 | return row |
|
1356 | return row | |
1353 |
|
1357 | |||
1354 |
|
1358 | |||
1355 | class Repository(Base, BaseModel): |
|
1359 | class Repository(Base, BaseModel): | |
1356 | __tablename__ = 'repositories' |
|
1360 | __tablename__ = 'repositories' | |
1357 | __table_args__ = ( |
|
1361 | __table_args__ = ( | |
1358 | Index('r_repo_name_idx', 'repo_name', mysql_length=255), |
|
1362 | Index('r_repo_name_idx', 'repo_name', mysql_length=255), | |
1359 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
1363 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
1360 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
1364 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
1361 | ) |
|
1365 | ) | |
1362 | DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}' |
|
1366 | DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}' | |
1363 | DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}' |
|
1367 | DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}' | |
1364 |
|
1368 | |||
1365 | STATE_CREATED = 'repo_state_created' |
|
1369 | STATE_CREATED = 'repo_state_created' | |
1366 | STATE_PENDING = 'repo_state_pending' |
|
1370 | STATE_PENDING = 'repo_state_pending' | |
1367 | STATE_ERROR = 'repo_state_error' |
|
1371 | STATE_ERROR = 'repo_state_error' | |
1368 |
|
1372 | |||
1369 | LOCK_AUTOMATIC = 'lock_auto' |
|
1373 | LOCK_AUTOMATIC = 'lock_auto' | |
1370 | LOCK_API = 'lock_api' |
|
1374 | LOCK_API = 'lock_api' | |
1371 | LOCK_WEB = 'lock_web' |
|
1375 | LOCK_WEB = 'lock_web' | |
1372 | LOCK_PULL = 'lock_pull' |
|
1376 | LOCK_PULL = 'lock_pull' | |
1373 |
|
1377 | |||
1374 | NAME_SEP = URL_SEP |
|
1378 | NAME_SEP = URL_SEP | |
1375 |
|
1379 | |||
1376 | repo_id = Column( |
|
1380 | repo_id = Column( | |
1377 | "repo_id", Integer(), nullable=False, unique=True, default=None, |
|
1381 | "repo_id", Integer(), nullable=False, unique=True, default=None, | |
1378 | primary_key=True) |
|
1382 | primary_key=True) | |
1379 | _repo_name = Column( |
|
1383 | _repo_name = Column( | |
1380 | "repo_name", Text(), nullable=False, default=None) |
|
1384 | "repo_name", Text(), nullable=False, default=None) | |
1381 | _repo_name_hash = Column( |
|
1385 | _repo_name_hash = Column( | |
1382 | "repo_name_hash", String(255), nullable=False, unique=True) |
|
1386 | "repo_name_hash", String(255), nullable=False, unique=True) | |
1383 | repo_state = Column("repo_state", String(255), nullable=True) |
|
1387 | repo_state = Column("repo_state", String(255), nullable=True) | |
1384 |
|
1388 | |||
1385 | clone_uri = Column( |
|
1389 | clone_uri = Column( | |
1386 | "clone_uri", EncryptedTextValue(), nullable=True, unique=False, |
|
1390 | "clone_uri", EncryptedTextValue(), nullable=True, unique=False, | |
1387 | default=None) |
|
1391 | default=None) | |
1388 | repo_type = Column( |
|
1392 | repo_type = Column( | |
1389 | "repo_type", String(255), nullable=False, unique=False, default=None) |
|
1393 | "repo_type", String(255), nullable=False, unique=False, default=None) | |
1390 | user_id = Column( |
|
1394 | user_id = Column( | |
1391 | "user_id", Integer(), ForeignKey('users.user_id'), nullable=False, |
|
1395 | "user_id", Integer(), ForeignKey('users.user_id'), nullable=False, | |
1392 | unique=False, default=None) |
|
1396 | unique=False, default=None) | |
1393 | private = Column( |
|
1397 | private = Column( | |
1394 | "private", Boolean(), nullable=True, unique=None, default=None) |
|
1398 | "private", Boolean(), nullable=True, unique=None, default=None) | |
1395 | enable_statistics = Column( |
|
1399 | enable_statistics = Column( | |
1396 | "statistics", Boolean(), nullable=True, unique=None, default=True) |
|
1400 | "statistics", Boolean(), nullable=True, unique=None, default=True) | |
1397 | enable_downloads = Column( |
|
1401 | enable_downloads = Column( | |
1398 | "downloads", Boolean(), nullable=True, unique=None, default=True) |
|
1402 | "downloads", Boolean(), nullable=True, unique=None, default=True) | |
1399 | description = Column( |
|
1403 | description = Column( | |
1400 | "description", String(10000), nullable=True, unique=None, default=None) |
|
1404 | "description", String(10000), nullable=True, unique=None, default=None) | |
1401 | created_on = Column( |
|
1405 | created_on = Column( | |
1402 | 'created_on', DateTime(timezone=False), nullable=True, unique=None, |
|
1406 | 'created_on', DateTime(timezone=False), nullable=True, unique=None, | |
1403 | default=datetime.datetime.now) |
|
1407 | default=datetime.datetime.now) | |
1404 | updated_on = Column( |
|
1408 | updated_on = Column( | |
1405 | 'updated_on', DateTime(timezone=False), nullable=True, unique=None, |
|
1409 | 'updated_on', DateTime(timezone=False), nullable=True, unique=None, | |
1406 | default=datetime.datetime.now) |
|
1410 | default=datetime.datetime.now) | |
1407 | _landing_revision = Column( |
|
1411 | _landing_revision = Column( | |
1408 | "landing_revision", String(255), nullable=False, unique=False, |
|
1412 | "landing_revision", String(255), nullable=False, unique=False, | |
1409 | default=None) |
|
1413 | default=None) | |
1410 | enable_locking = Column( |
|
1414 | enable_locking = Column( | |
1411 | "enable_locking", Boolean(), nullable=False, unique=None, |
|
1415 | "enable_locking", Boolean(), nullable=False, unique=None, | |
1412 | default=False) |
|
1416 | default=False) | |
1413 | _locked = Column( |
|
1417 | _locked = Column( | |
1414 | "locked", String(255), nullable=True, unique=False, default=None) |
|
1418 | "locked", String(255), nullable=True, unique=False, default=None) | |
1415 | _changeset_cache = Column( |
|
1419 | _changeset_cache = Column( | |
1416 | "changeset_cache", LargeBinary(), nullable=True) # JSON data |
|
1420 | "changeset_cache", LargeBinary(), nullable=True) # JSON data | |
1417 |
|
1421 | |||
1418 | fork_id = Column( |
|
1422 | fork_id = Column( | |
1419 | "fork_id", Integer(), ForeignKey('repositories.repo_id'), |
|
1423 | "fork_id", Integer(), ForeignKey('repositories.repo_id'), | |
1420 | nullable=True, unique=False, default=None) |
|
1424 | nullable=True, unique=False, default=None) | |
1421 | group_id = Column( |
|
1425 | group_id = Column( | |
1422 | "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, |
|
1426 | "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True, | |
1423 | unique=False, default=None) |
|
1427 | unique=False, default=None) | |
1424 |
|
1428 | |||
1425 | user = relationship('User', lazy='joined') |
|
1429 | user = relationship('User', lazy='joined') | |
1426 | fork = relationship('Repository', remote_side=repo_id, lazy='joined') |
|
1430 | fork = relationship('Repository', remote_side=repo_id, lazy='joined') | |
1427 | group = relationship('RepoGroup', lazy='joined') |
|
1431 | group = relationship('RepoGroup', lazy='joined') | |
1428 | repo_to_perm = relationship( |
|
1432 | repo_to_perm = relationship( | |
1429 | 'UserRepoToPerm', cascade='all', |
|
1433 | 'UserRepoToPerm', cascade='all', | |
1430 | order_by='UserRepoToPerm.repo_to_perm_id') |
|
1434 | order_by='UserRepoToPerm.repo_to_perm_id') | |
1431 | users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all') |
|
1435 | users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all') | |
1432 | stats = relationship('Statistics', cascade='all', uselist=False) |
|
1436 | stats = relationship('Statistics', cascade='all', uselist=False) | |
1433 |
|
1437 | |||
1434 | followers = relationship( |
|
1438 | followers = relationship( | |
1435 | 'UserFollowing', |
|
1439 | 'UserFollowing', | |
1436 | primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', |
|
1440 | primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id', | |
1437 | cascade='all') |
|
1441 | cascade='all') | |
1438 | extra_fields = relationship( |
|
1442 | extra_fields = relationship( | |
1439 | 'RepositoryField', cascade="all, delete, delete-orphan") |
|
1443 | 'RepositoryField', cascade="all, delete, delete-orphan") | |
1440 | logs = relationship('UserLog') |
|
1444 | logs = relationship('UserLog') | |
1441 | comments = relationship( |
|
1445 | comments = relationship( | |
1442 | 'ChangesetComment', cascade="all, delete, delete-orphan") |
|
1446 | 'ChangesetComment', cascade="all, delete, delete-orphan") | |
1443 | pull_requests_source = relationship( |
|
1447 | pull_requests_source = relationship( | |
1444 | 'PullRequest', |
|
1448 | 'PullRequest', | |
1445 | primaryjoin='PullRequest.source_repo_id==Repository.repo_id', |
|
1449 | primaryjoin='PullRequest.source_repo_id==Repository.repo_id', | |
1446 | cascade="all, delete, delete-orphan") |
|
1450 | cascade="all, delete, delete-orphan") | |
1447 | pull_requests_target = relationship( |
|
1451 | pull_requests_target = relationship( | |
1448 | 'PullRequest', |
|
1452 | 'PullRequest', | |
1449 | primaryjoin='PullRequest.target_repo_id==Repository.repo_id', |
|
1453 | primaryjoin='PullRequest.target_repo_id==Repository.repo_id', | |
1450 | cascade="all, delete, delete-orphan") |
|
1454 | cascade="all, delete, delete-orphan") | |
1451 | ui = relationship('RepoRhodeCodeUi', cascade="all") |
|
1455 | ui = relationship('RepoRhodeCodeUi', cascade="all") | |
1452 | settings = relationship('RepoRhodeCodeSetting', cascade="all") |
|
1456 | settings = relationship('RepoRhodeCodeSetting', cascade="all") | |
1453 | integrations = relationship('Integration', |
|
1457 | integrations = relationship('Integration', | |
1454 | cascade="all, delete, delete-orphan") |
|
1458 | cascade="all, delete, delete-orphan") | |
1455 |
|
1459 | |||
1456 | def __unicode__(self): |
|
1460 | def __unicode__(self): | |
1457 | return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id, |
|
1461 | return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id, | |
1458 | safe_unicode(self.repo_name)) |
|
1462 | safe_unicode(self.repo_name)) | |
1459 |
|
1463 | |||
1460 | @hybrid_property |
|
1464 | @hybrid_property | |
1461 | def landing_rev(self): |
|
1465 | def landing_rev(self): | |
1462 | # always should return [rev_type, rev] |
|
1466 | # always should return [rev_type, rev] | |
1463 | if self._landing_revision: |
|
1467 | if self._landing_revision: | |
1464 | _rev_info = self._landing_revision.split(':') |
|
1468 | _rev_info = self._landing_revision.split(':') | |
1465 | if len(_rev_info) < 2: |
|
1469 | if len(_rev_info) < 2: | |
1466 | _rev_info.insert(0, 'rev') |
|
1470 | _rev_info.insert(0, 'rev') | |
1467 | return [_rev_info[0], _rev_info[1]] |
|
1471 | return [_rev_info[0], _rev_info[1]] | |
1468 | return [None, None] |
|
1472 | return [None, None] | |
1469 |
|
1473 | |||
1470 | @landing_rev.setter |
|
1474 | @landing_rev.setter | |
1471 | def landing_rev(self, val): |
|
1475 | def landing_rev(self, val): | |
1472 | if ':' not in val: |
|
1476 | if ':' not in val: | |
1473 | raise ValueError('value must be delimited with `:` and consist ' |
|
1477 | raise ValueError('value must be delimited with `:` and consist ' | |
1474 | 'of <rev_type>:<rev>, got %s instead' % val) |
|
1478 | 'of <rev_type>:<rev>, got %s instead' % val) | |
1475 | self._landing_revision = val |
|
1479 | self._landing_revision = val | |
1476 |
|
1480 | |||
1477 | @hybrid_property |
|
1481 | @hybrid_property | |
1478 | def locked(self): |
|
1482 | def locked(self): | |
1479 | if self._locked: |
|
1483 | if self._locked: | |
1480 | user_id, timelocked, reason = self._locked.split(':') |
|
1484 | user_id, timelocked, reason = self._locked.split(':') | |
1481 | lock_values = int(user_id), timelocked, reason |
|
1485 | lock_values = int(user_id), timelocked, reason | |
1482 | else: |
|
1486 | else: | |
1483 | lock_values = [None, None, None] |
|
1487 | lock_values = [None, None, None] | |
1484 | return lock_values |
|
1488 | return lock_values | |
1485 |
|
1489 | |||
1486 | @locked.setter |
|
1490 | @locked.setter | |
1487 | def locked(self, val): |
|
1491 | def locked(self, val): | |
1488 | if val and isinstance(val, (list, tuple)): |
|
1492 | if val and isinstance(val, (list, tuple)): | |
1489 | self._locked = ':'.join(map(str, val)) |
|
1493 | self._locked = ':'.join(map(str, val)) | |
1490 | else: |
|
1494 | else: | |
1491 | self._locked = None |
|
1495 | self._locked = None | |
1492 |
|
1496 | |||
1493 | @hybrid_property |
|
1497 | @hybrid_property | |
1494 | def changeset_cache(self): |
|
1498 | def changeset_cache(self): | |
1495 | from rhodecode.lib.vcs.backends.base import EmptyCommit |
|
1499 | from rhodecode.lib.vcs.backends.base import EmptyCommit | |
1496 | dummy = EmptyCommit().__json__() |
|
1500 | dummy = EmptyCommit().__json__() | |
1497 | if not self._changeset_cache: |
|
1501 | if not self._changeset_cache: | |
1498 | return dummy |
|
1502 | return dummy | |
1499 | try: |
|
1503 | try: | |
1500 | return json.loads(self._changeset_cache) |
|
1504 | return json.loads(self._changeset_cache) | |
1501 | except TypeError: |
|
1505 | except TypeError: | |
1502 | return dummy |
|
1506 | return dummy | |
1503 | except Exception: |
|
1507 | except Exception: | |
1504 | log.error(traceback.format_exc()) |
|
1508 | log.error(traceback.format_exc()) | |
1505 | return dummy |
|
1509 | return dummy | |
1506 |
|
1510 | |||
1507 | @changeset_cache.setter |
|
1511 | @changeset_cache.setter | |
1508 | def changeset_cache(self, val): |
|
1512 | def changeset_cache(self, val): | |
1509 | try: |
|
1513 | try: | |
1510 | self._changeset_cache = json.dumps(val) |
|
1514 | self._changeset_cache = json.dumps(val) | |
1511 | except Exception: |
|
1515 | except Exception: | |
1512 | log.error(traceback.format_exc()) |
|
1516 | log.error(traceback.format_exc()) | |
1513 |
|
1517 | |||
1514 | @hybrid_property |
|
1518 | @hybrid_property | |
1515 | def repo_name(self): |
|
1519 | def repo_name(self): | |
1516 | return self._repo_name |
|
1520 | return self._repo_name | |
1517 |
|
1521 | |||
1518 | @repo_name.setter |
|
1522 | @repo_name.setter | |
1519 | def repo_name(self, value): |
|
1523 | def repo_name(self, value): | |
1520 | self._repo_name = value |
|
1524 | self._repo_name = value | |
1521 | self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest() |
|
1525 | self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest() | |
1522 |
|
1526 | |||
1523 | @classmethod |
|
1527 | @classmethod | |
1524 | def normalize_repo_name(cls, repo_name): |
|
1528 | def normalize_repo_name(cls, repo_name): | |
1525 | """ |
|
1529 | """ | |
1526 | Normalizes os specific repo_name to the format internally stored inside |
|
1530 | Normalizes os specific repo_name to the format internally stored inside | |
1527 | database using URL_SEP |
|
1531 | database using URL_SEP | |
1528 |
|
1532 | |||
1529 | :param cls: |
|
1533 | :param cls: | |
1530 | :param repo_name: |
|
1534 | :param repo_name: | |
1531 | """ |
|
1535 | """ | |
1532 | return cls.NAME_SEP.join(repo_name.split(os.sep)) |
|
1536 | return cls.NAME_SEP.join(repo_name.split(os.sep)) | |
1533 |
|
1537 | |||
1534 | @classmethod |
|
1538 | @classmethod | |
1535 | def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False): |
|
1539 | def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False): | |
1536 | session = Session() |
|
1540 | session = Session() | |
1537 | q = session.query(cls).filter(cls.repo_name == repo_name) |
|
1541 | q = session.query(cls).filter(cls.repo_name == repo_name) | |
1538 |
|
1542 | |||
1539 | if cache: |
|
1543 | if cache: | |
1540 | if identity_cache: |
|
1544 | if identity_cache: | |
1541 | val = cls.identity_cache(session, 'repo_name', repo_name) |
|
1545 | val = cls.identity_cache(session, 'repo_name', repo_name) | |
1542 | if val: |
|
1546 | if val: | |
1543 | return val |
|
1547 | return val | |
1544 | else: |
|
1548 | else: | |
1545 | q = q.options( |
|
1549 | q = q.options( | |
1546 | FromCache("sql_cache_short", |
|
1550 | FromCache("sql_cache_short", | |
1547 | "get_repo_by_name_%s" % _hash_key(repo_name))) |
|
1551 | "get_repo_by_name_%s" % _hash_key(repo_name))) | |
1548 |
|
1552 | |||
1549 | return q.scalar() |
|
1553 | return q.scalar() | |
1550 |
|
1554 | |||
1551 | @classmethod |
|
1555 | @classmethod | |
1552 | def get_by_full_path(cls, repo_full_path): |
|
1556 | def get_by_full_path(cls, repo_full_path): | |
1553 | repo_name = repo_full_path.split(cls.base_path(), 1)[-1] |
|
1557 | repo_name = repo_full_path.split(cls.base_path(), 1)[-1] | |
1554 | repo_name = cls.normalize_repo_name(repo_name) |
|
1558 | repo_name = cls.normalize_repo_name(repo_name) | |
1555 | return cls.get_by_repo_name(repo_name.strip(URL_SEP)) |
|
1559 | return cls.get_by_repo_name(repo_name.strip(URL_SEP)) | |
1556 |
|
1560 | |||
1557 | @classmethod |
|
1561 | @classmethod | |
1558 | def get_repo_forks(cls, repo_id): |
|
1562 | def get_repo_forks(cls, repo_id): | |
1559 | return cls.query().filter(Repository.fork_id == repo_id) |
|
1563 | return cls.query().filter(Repository.fork_id == repo_id) | |
1560 |
|
1564 | |||
1561 | @classmethod |
|
1565 | @classmethod | |
1562 | def base_path(cls): |
|
1566 | def base_path(cls): | |
1563 | """ |
|
1567 | """ | |
1564 | Returns base path when all repos are stored |
|
1568 | Returns base path when all repos are stored | |
1565 |
|
1569 | |||
1566 | :param cls: |
|
1570 | :param cls: | |
1567 | """ |
|
1571 | """ | |
1568 | q = Session().query(RhodeCodeUi)\ |
|
1572 | q = Session().query(RhodeCodeUi)\ | |
1569 | .filter(RhodeCodeUi.ui_key == cls.NAME_SEP) |
|
1573 | .filter(RhodeCodeUi.ui_key == cls.NAME_SEP) | |
1570 | q = q.options(FromCache("sql_cache_short", "repository_repo_path")) |
|
1574 | q = q.options(FromCache("sql_cache_short", "repository_repo_path")) | |
1571 | return q.one().ui_value |
|
1575 | return q.one().ui_value | |
1572 |
|
1576 | |||
1573 | @classmethod |
|
1577 | @classmethod | |
1574 | def is_valid(cls, repo_name): |
|
1578 | def is_valid(cls, repo_name): | |
1575 | """ |
|
1579 | """ | |
1576 | returns True if given repo name is a valid filesystem repository |
|
1580 | returns True if given repo name is a valid filesystem repository | |
1577 |
|
1581 | |||
1578 | :param cls: |
|
1582 | :param cls: | |
1579 | :param repo_name: |
|
1583 | :param repo_name: | |
1580 | """ |
|
1584 | """ | |
1581 | from rhodecode.lib.utils import is_valid_repo |
|
1585 | from rhodecode.lib.utils import is_valid_repo | |
1582 |
|
1586 | |||
1583 | return is_valid_repo(repo_name, cls.base_path()) |
|
1587 | return is_valid_repo(repo_name, cls.base_path()) | |
1584 |
|
1588 | |||
1585 | @classmethod |
|
1589 | @classmethod | |
1586 | def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None), |
|
1590 | def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None), | |
1587 | case_insensitive=True): |
|
1591 | case_insensitive=True): | |
1588 | q = Repository.query() |
|
1592 | q = Repository.query() | |
1589 |
|
1593 | |||
1590 | if not isinstance(user_id, Optional): |
|
1594 | if not isinstance(user_id, Optional): | |
1591 | q = q.filter(Repository.user_id == user_id) |
|
1595 | q = q.filter(Repository.user_id == user_id) | |
1592 |
|
1596 | |||
1593 | if not isinstance(group_id, Optional): |
|
1597 | if not isinstance(group_id, Optional): | |
1594 | q = q.filter(Repository.group_id == group_id) |
|
1598 | q = q.filter(Repository.group_id == group_id) | |
1595 |
|
1599 | |||
1596 | if case_insensitive: |
|
1600 | if case_insensitive: | |
1597 | q = q.order_by(func.lower(Repository.repo_name)) |
|
1601 | q = q.order_by(func.lower(Repository.repo_name)) | |
1598 | else: |
|
1602 | else: | |
1599 | q = q.order_by(Repository.repo_name) |
|
1603 | q = q.order_by(Repository.repo_name) | |
1600 | return q.all() |
|
1604 | return q.all() | |
1601 |
|
1605 | |||
1602 | @property |
|
1606 | @property | |
1603 | def forks(self): |
|
1607 | def forks(self): | |
1604 | """ |
|
1608 | """ | |
1605 | Return forks of this repo |
|
1609 | Return forks of this repo | |
1606 | """ |
|
1610 | """ | |
1607 | return Repository.get_repo_forks(self.repo_id) |
|
1611 | return Repository.get_repo_forks(self.repo_id) | |
1608 |
|
1612 | |||
1609 | @property |
|
1613 | @property | |
1610 | def parent(self): |
|
1614 | def parent(self): | |
1611 | """ |
|
1615 | """ | |
1612 | Returns fork parent |
|
1616 | Returns fork parent | |
1613 | """ |
|
1617 | """ | |
1614 | return self.fork |
|
1618 | return self.fork | |
1615 |
|
1619 | |||
1616 | @property |
|
1620 | @property | |
1617 | def just_name(self): |
|
1621 | def just_name(self): | |
1618 | return self.repo_name.split(self.NAME_SEP)[-1] |
|
1622 | return self.repo_name.split(self.NAME_SEP)[-1] | |
1619 |
|
1623 | |||
1620 | @property |
|
1624 | @property | |
1621 | def groups_with_parents(self): |
|
1625 | def groups_with_parents(self): | |
1622 | groups = [] |
|
1626 | groups = [] | |
1623 | if self.group is None: |
|
1627 | if self.group is None: | |
1624 | return groups |
|
1628 | return groups | |
1625 |
|
1629 | |||
1626 | cur_gr = self.group |
|
1630 | cur_gr = self.group | |
1627 | groups.insert(0, cur_gr) |
|
1631 | groups.insert(0, cur_gr) | |
1628 | while 1: |
|
1632 | while 1: | |
1629 | gr = getattr(cur_gr, 'parent_group', None) |
|
1633 | gr = getattr(cur_gr, 'parent_group', None) | |
1630 | cur_gr = cur_gr.parent_group |
|
1634 | cur_gr = cur_gr.parent_group | |
1631 | if gr is None: |
|
1635 | if gr is None: | |
1632 | break |
|
1636 | break | |
1633 | groups.insert(0, gr) |
|
1637 | groups.insert(0, gr) | |
1634 |
|
1638 | |||
1635 | return groups |
|
1639 | return groups | |
1636 |
|
1640 | |||
1637 | @property |
|
1641 | @property | |
1638 | def groups_and_repo(self): |
|
1642 | def groups_and_repo(self): | |
1639 | return self.groups_with_parents, self |
|
1643 | return self.groups_with_parents, self | |
1640 |
|
1644 | |||
1641 | @LazyProperty |
|
1645 | @LazyProperty | |
1642 | def repo_path(self): |
|
1646 | def repo_path(self): | |
1643 | """ |
|
1647 | """ | |
1644 | Returns base full path for that repository means where it actually |
|
1648 | Returns base full path for that repository means where it actually | |
1645 | exists on a filesystem |
|
1649 | exists on a filesystem | |
1646 | """ |
|
1650 | """ | |
1647 | q = Session().query(RhodeCodeUi).filter( |
|
1651 | q = Session().query(RhodeCodeUi).filter( | |
1648 | RhodeCodeUi.ui_key == self.NAME_SEP) |
|
1652 | RhodeCodeUi.ui_key == self.NAME_SEP) | |
1649 | q = q.options(FromCache("sql_cache_short", "repository_repo_path")) |
|
1653 | q = q.options(FromCache("sql_cache_short", "repository_repo_path")) | |
1650 | return q.one().ui_value |
|
1654 | return q.one().ui_value | |
1651 |
|
1655 | |||
1652 | @property |
|
1656 | @property | |
1653 | def repo_full_path(self): |
|
1657 | def repo_full_path(self): | |
1654 | p = [self.repo_path] |
|
1658 | p = [self.repo_path] | |
1655 | # we need to split the name by / since this is how we store the |
|
1659 | # we need to split the name by / since this is how we store the | |
1656 | # names in the database, but that eventually needs to be converted |
|
1660 | # names in the database, but that eventually needs to be converted | |
1657 | # into a valid system path |
|
1661 | # into a valid system path | |
1658 | p += self.repo_name.split(self.NAME_SEP) |
|
1662 | p += self.repo_name.split(self.NAME_SEP) | |
1659 | return os.path.join(*map(safe_unicode, p)) |
|
1663 | return os.path.join(*map(safe_unicode, p)) | |
1660 |
|
1664 | |||
1661 | @property |
|
1665 | @property | |
1662 | def cache_keys(self): |
|
1666 | def cache_keys(self): | |
1663 | """ |
|
1667 | """ | |
1664 | Returns associated cache keys for that repo |
|
1668 | Returns associated cache keys for that repo | |
1665 | """ |
|
1669 | """ | |
1666 | return CacheKey.query()\ |
|
1670 | return CacheKey.query()\ | |
1667 | .filter(CacheKey.cache_args == self.repo_name)\ |
|
1671 | .filter(CacheKey.cache_args == self.repo_name)\ | |
1668 | .order_by(CacheKey.cache_key)\ |
|
1672 | .order_by(CacheKey.cache_key)\ | |
1669 | .all() |
|
1673 | .all() | |
1670 |
|
1674 | |||
1671 | def get_new_name(self, repo_name): |
|
1675 | def get_new_name(self, repo_name): | |
1672 | """ |
|
1676 | """ | |
1673 | returns new full repository name based on assigned group and new new |
|
1677 | returns new full repository name based on assigned group and new new | |
1674 |
|
1678 | |||
1675 | :param group_name: |
|
1679 | :param group_name: | |
1676 | """ |
|
1680 | """ | |
1677 | path_prefix = self.group.full_path_splitted if self.group else [] |
|
1681 | path_prefix = self.group.full_path_splitted if self.group else [] | |
1678 | return self.NAME_SEP.join(path_prefix + [repo_name]) |
|
1682 | return self.NAME_SEP.join(path_prefix + [repo_name]) | |
1679 |
|
1683 | |||
1680 | @property |
|
1684 | @property | |
1681 | def _config(self): |
|
1685 | def _config(self): | |
1682 | """ |
|
1686 | """ | |
1683 | Returns db based config object. |
|
1687 | Returns db based config object. | |
1684 | """ |
|
1688 | """ | |
1685 | from rhodecode.lib.utils import make_db_config |
|
1689 | from rhodecode.lib.utils import make_db_config | |
1686 | return make_db_config(clear_session=False, repo=self) |
|
1690 | return make_db_config(clear_session=False, repo=self) | |
1687 |
|
1691 | |||
1688 | def permissions(self, with_admins=True, with_owner=True): |
|
1692 | def permissions(self, with_admins=True, with_owner=True): | |
1689 | q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self) |
|
1693 | q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self) | |
1690 | q = q.options(joinedload(UserRepoToPerm.repository), |
|
1694 | q = q.options(joinedload(UserRepoToPerm.repository), | |
1691 | joinedload(UserRepoToPerm.user), |
|
1695 | joinedload(UserRepoToPerm.user), | |
1692 | joinedload(UserRepoToPerm.permission),) |
|
1696 | joinedload(UserRepoToPerm.permission),) | |
1693 |
|
1697 | |||
1694 | # get owners and admins and permissions. We do a trick of re-writing |
|
1698 | # get owners and admins and permissions. We do a trick of re-writing | |
1695 | # objects from sqlalchemy to named-tuples due to sqlalchemy session |
|
1699 | # objects from sqlalchemy to named-tuples due to sqlalchemy session | |
1696 | # has a global reference and changing one object propagates to all |
|
1700 | # has a global reference and changing one object propagates to all | |
1697 | # others. This means if admin is also an owner admin_row that change |
|
1701 | # others. This means if admin is also an owner admin_row that change | |
1698 | # would propagate to both objects |
|
1702 | # would propagate to both objects | |
1699 | perm_rows = [] |
|
1703 | perm_rows = [] | |
1700 | for _usr in q.all(): |
|
1704 | for _usr in q.all(): | |
1701 | usr = AttributeDict(_usr.user.get_dict()) |
|
1705 | usr = AttributeDict(_usr.user.get_dict()) | |
1702 | usr.permission = _usr.permission.permission_name |
|
1706 | usr.permission = _usr.permission.permission_name | |
1703 | perm_rows.append(usr) |
|
1707 | perm_rows.append(usr) | |
1704 |
|
1708 | |||
1705 | # filter the perm rows by 'default' first and then sort them by |
|
1709 | # filter the perm rows by 'default' first and then sort them by | |
1706 | # admin,write,read,none permissions sorted again alphabetically in |
|
1710 | # admin,write,read,none permissions sorted again alphabetically in | |
1707 | # each group |
|
1711 | # each group | |
1708 | perm_rows = sorted(perm_rows, key=display_sort) |
|
1712 | perm_rows = sorted(perm_rows, key=display_sort) | |
1709 |
|
1713 | |||
1710 | _admin_perm = 'repository.admin' |
|
1714 | _admin_perm = 'repository.admin' | |
1711 | owner_row = [] |
|
1715 | owner_row = [] | |
1712 | if with_owner: |
|
1716 | if with_owner: | |
1713 | usr = AttributeDict(self.user.get_dict()) |
|
1717 | usr = AttributeDict(self.user.get_dict()) | |
1714 | usr.owner_row = True |
|
1718 | usr.owner_row = True | |
1715 | usr.permission = _admin_perm |
|
1719 | usr.permission = _admin_perm | |
1716 | owner_row.append(usr) |
|
1720 | owner_row.append(usr) | |
1717 |
|
1721 | |||
1718 | super_admin_rows = [] |
|
1722 | super_admin_rows = [] | |
1719 | if with_admins: |
|
1723 | if with_admins: | |
1720 | for usr in User.get_all_super_admins(): |
|
1724 | for usr in User.get_all_super_admins(): | |
1721 | # if this admin is also owner, don't double the record |
|
1725 | # if this admin is also owner, don't double the record | |
1722 | if usr.user_id == owner_row[0].user_id: |
|
1726 | if usr.user_id == owner_row[0].user_id: | |
1723 | owner_row[0].admin_row = True |
|
1727 | owner_row[0].admin_row = True | |
1724 | else: |
|
1728 | else: | |
1725 | usr = AttributeDict(usr.get_dict()) |
|
1729 | usr = AttributeDict(usr.get_dict()) | |
1726 | usr.admin_row = True |
|
1730 | usr.admin_row = True | |
1727 | usr.permission = _admin_perm |
|
1731 | usr.permission = _admin_perm | |
1728 | super_admin_rows.append(usr) |
|
1732 | super_admin_rows.append(usr) | |
1729 |
|
1733 | |||
1730 | return super_admin_rows + owner_row + perm_rows |
|
1734 | return super_admin_rows + owner_row + perm_rows | |
1731 |
|
1735 | |||
1732 | def permission_user_groups(self): |
|
1736 | def permission_user_groups(self): | |
1733 | q = UserGroupRepoToPerm.query().filter( |
|
1737 | q = UserGroupRepoToPerm.query().filter( | |
1734 | UserGroupRepoToPerm.repository == self) |
|
1738 | UserGroupRepoToPerm.repository == self) | |
1735 | q = q.options(joinedload(UserGroupRepoToPerm.repository), |
|
1739 | q = q.options(joinedload(UserGroupRepoToPerm.repository), | |
1736 | joinedload(UserGroupRepoToPerm.users_group), |
|
1740 | joinedload(UserGroupRepoToPerm.users_group), | |
1737 | joinedload(UserGroupRepoToPerm.permission),) |
|
1741 | joinedload(UserGroupRepoToPerm.permission),) | |
1738 |
|
1742 | |||
1739 | perm_rows = [] |
|
1743 | perm_rows = [] | |
1740 | for _user_group in q.all(): |
|
1744 | for _user_group in q.all(): | |
1741 | usr = AttributeDict(_user_group.users_group.get_dict()) |
|
1745 | usr = AttributeDict(_user_group.users_group.get_dict()) | |
1742 | usr.permission = _user_group.permission.permission_name |
|
1746 | usr.permission = _user_group.permission.permission_name | |
1743 | perm_rows.append(usr) |
|
1747 | perm_rows.append(usr) | |
1744 |
|
1748 | |||
1745 | return perm_rows |
|
1749 | return perm_rows | |
1746 |
|
1750 | |||
1747 | def get_api_data(self, include_secrets=False): |
|
1751 | def get_api_data(self, include_secrets=False): | |
1748 | """ |
|
1752 | """ | |
1749 | Common function for generating repo api data |
|
1753 | Common function for generating repo api data | |
1750 |
|
1754 | |||
1751 | :param include_secrets: See :meth:`User.get_api_data`. |
|
1755 | :param include_secrets: See :meth:`User.get_api_data`. | |
1752 |
|
1756 | |||
1753 | """ |
|
1757 | """ | |
1754 | # TODO: mikhail: Here there is an anti-pattern, we probably need to |
|
1758 | # TODO: mikhail: Here there is an anti-pattern, we probably need to | |
1755 | # move this methods on models level. |
|
1759 | # move this methods on models level. | |
1756 | from rhodecode.model.settings import SettingsModel |
|
1760 | from rhodecode.model.settings import SettingsModel | |
1757 |
|
1761 | |||
1758 | repo = self |
|
1762 | repo = self | |
1759 | _user_id, _time, _reason = self.locked |
|
1763 | _user_id, _time, _reason = self.locked | |
1760 |
|
1764 | |||
1761 | data = { |
|
1765 | data = { | |
1762 | 'repo_id': repo.repo_id, |
|
1766 | 'repo_id': repo.repo_id, | |
1763 | 'repo_name': repo.repo_name, |
|
1767 | 'repo_name': repo.repo_name, | |
1764 | 'repo_type': repo.repo_type, |
|
1768 | 'repo_type': repo.repo_type, | |
1765 | 'clone_uri': repo.clone_uri or '', |
|
1769 | 'clone_uri': repo.clone_uri or '', | |
1766 | 'url': url('summary_home', repo_name=self.repo_name, qualified=True), |
|
1770 | 'url': url('summary_home', repo_name=self.repo_name, qualified=True), | |
1767 | 'private': repo.private, |
|
1771 | 'private': repo.private, | |
1768 | 'created_on': repo.created_on, |
|
1772 | 'created_on': repo.created_on, | |
1769 | 'description': repo.description, |
|
1773 | 'description': repo.description, | |
1770 | 'landing_rev': repo.landing_rev, |
|
1774 | 'landing_rev': repo.landing_rev, | |
1771 | 'owner': repo.user.username, |
|
1775 | 'owner': repo.user.username, | |
1772 | 'fork_of': repo.fork.repo_name if repo.fork else None, |
|
1776 | 'fork_of': repo.fork.repo_name if repo.fork else None, | |
1773 | 'enable_statistics': repo.enable_statistics, |
|
1777 | 'enable_statistics': repo.enable_statistics, | |
1774 | 'enable_locking': repo.enable_locking, |
|
1778 | 'enable_locking': repo.enable_locking, | |
1775 | 'enable_downloads': repo.enable_downloads, |
|
1779 | 'enable_downloads': repo.enable_downloads, | |
1776 | 'last_changeset': repo.changeset_cache, |
|
1780 | 'last_changeset': repo.changeset_cache, | |
1777 | 'locked_by': User.get(_user_id).get_api_data( |
|
1781 | 'locked_by': User.get(_user_id).get_api_data( | |
1778 | include_secrets=include_secrets) if _user_id else None, |
|
1782 | include_secrets=include_secrets) if _user_id else None, | |
1779 | 'locked_date': time_to_datetime(_time) if _time else None, |
|
1783 | 'locked_date': time_to_datetime(_time) if _time else None, | |
1780 | 'lock_reason': _reason if _reason else None, |
|
1784 | 'lock_reason': _reason if _reason else None, | |
1781 | } |
|
1785 | } | |
1782 |
|
1786 | |||
1783 | # TODO: mikhail: should be per-repo settings here |
|
1787 | # TODO: mikhail: should be per-repo settings here | |
1784 | rc_config = SettingsModel().get_all_settings() |
|
1788 | rc_config = SettingsModel().get_all_settings() | |
1785 | repository_fields = str2bool( |
|
1789 | repository_fields = str2bool( | |
1786 | rc_config.get('rhodecode_repository_fields')) |
|
1790 | rc_config.get('rhodecode_repository_fields')) | |
1787 | if repository_fields: |
|
1791 | if repository_fields: | |
1788 | for f in self.extra_fields: |
|
1792 | for f in self.extra_fields: | |
1789 | data[f.field_key_prefixed] = f.field_value |
|
1793 | data[f.field_key_prefixed] = f.field_value | |
1790 |
|
1794 | |||
1791 | return data |
|
1795 | return data | |
1792 |
|
1796 | |||
1793 | @classmethod |
|
1797 | @classmethod | |
1794 | def lock(cls, repo, user_id, lock_time=None, lock_reason=None): |
|
1798 | def lock(cls, repo, user_id, lock_time=None, lock_reason=None): | |
1795 | if not lock_time: |
|
1799 | if not lock_time: | |
1796 | lock_time = time.time() |
|
1800 | lock_time = time.time() | |
1797 | if not lock_reason: |
|
1801 | if not lock_reason: | |
1798 | lock_reason = cls.LOCK_AUTOMATIC |
|
1802 | lock_reason = cls.LOCK_AUTOMATIC | |
1799 | repo.locked = [user_id, lock_time, lock_reason] |
|
1803 | repo.locked = [user_id, lock_time, lock_reason] | |
1800 | Session().add(repo) |
|
1804 | Session().add(repo) | |
1801 | Session().commit() |
|
1805 | Session().commit() | |
1802 |
|
1806 | |||
1803 | @classmethod |
|
1807 | @classmethod | |
1804 | def unlock(cls, repo): |
|
1808 | def unlock(cls, repo): | |
1805 | repo.locked = None |
|
1809 | repo.locked = None | |
1806 | Session().add(repo) |
|
1810 | Session().add(repo) | |
1807 | Session().commit() |
|
1811 | Session().commit() | |
1808 |
|
1812 | |||
1809 | @classmethod |
|
1813 | @classmethod | |
1810 | def getlock(cls, repo): |
|
1814 | def getlock(cls, repo): | |
1811 | return repo.locked |
|
1815 | return repo.locked | |
1812 |
|
1816 | |||
1813 | def is_user_lock(self, user_id): |
|
1817 | def is_user_lock(self, user_id): | |
1814 | if self.lock[0]: |
|
1818 | if self.lock[0]: | |
1815 | lock_user_id = safe_int(self.lock[0]) |
|
1819 | lock_user_id = safe_int(self.lock[0]) | |
1816 | user_id = safe_int(user_id) |
|
1820 | user_id = safe_int(user_id) | |
1817 | # both are ints, and they are equal |
|
1821 | # both are ints, and they are equal | |
1818 | return all([lock_user_id, user_id]) and lock_user_id == user_id |
|
1822 | return all([lock_user_id, user_id]) and lock_user_id == user_id | |
1819 |
|
1823 | |||
1820 | return False |
|
1824 | return False | |
1821 |
|
1825 | |||
1822 | def get_locking_state(self, action, user_id, only_when_enabled=True): |
|
1826 | def get_locking_state(self, action, user_id, only_when_enabled=True): | |
1823 | """ |
|
1827 | """ | |
1824 | Checks locking on this repository, if locking is enabled and lock is |
|
1828 | Checks locking on this repository, if locking is enabled and lock is | |
1825 | present returns a tuple of make_lock, locked, locked_by. |
|
1829 | present returns a tuple of make_lock, locked, locked_by. | |
1826 | make_lock can have 3 states None (do nothing) True, make lock |
|
1830 | make_lock can have 3 states None (do nothing) True, make lock | |
1827 | False release lock, This value is later propagated to hooks, which |
|
1831 | False release lock, This value is later propagated to hooks, which | |
1828 | do the locking. Think about this as signals passed to hooks what to do. |
|
1832 | do the locking. Think about this as signals passed to hooks what to do. | |
1829 |
|
1833 | |||
1830 | """ |
|
1834 | """ | |
1831 | # TODO: johbo: This is part of the business logic and should be moved |
|
1835 | # TODO: johbo: This is part of the business logic and should be moved | |
1832 | # into the RepositoryModel. |
|
1836 | # into the RepositoryModel. | |
1833 |
|
1837 | |||
1834 | if action not in ('push', 'pull'): |
|
1838 | if action not in ('push', 'pull'): | |
1835 | raise ValueError("Invalid action value: %s" % repr(action)) |
|
1839 | raise ValueError("Invalid action value: %s" % repr(action)) | |
1836 |
|
1840 | |||
1837 | # defines if locked error should be thrown to user |
|
1841 | # defines if locked error should be thrown to user | |
1838 | currently_locked = False |
|
1842 | currently_locked = False | |
1839 | # defines if new lock should be made, tri-state |
|
1843 | # defines if new lock should be made, tri-state | |
1840 | make_lock = None |
|
1844 | make_lock = None | |
1841 | repo = self |
|
1845 | repo = self | |
1842 | user = User.get(user_id) |
|
1846 | user = User.get(user_id) | |
1843 |
|
1847 | |||
1844 | lock_info = repo.locked |
|
1848 | lock_info = repo.locked | |
1845 |
|
1849 | |||
1846 | if repo and (repo.enable_locking or not only_when_enabled): |
|
1850 | if repo and (repo.enable_locking or not only_when_enabled): | |
1847 | if action == 'push': |
|
1851 | if action == 'push': | |
1848 | # check if it's already locked !, if it is compare users |
|
1852 | # check if it's already locked !, if it is compare users | |
1849 | locked_by_user_id = lock_info[0] |
|
1853 | locked_by_user_id = lock_info[0] | |
1850 | if user.user_id == locked_by_user_id: |
|
1854 | if user.user_id == locked_by_user_id: | |
1851 | log.debug( |
|
1855 | log.debug( | |
1852 | 'Got `push` action from user %s, now unlocking', user) |
|
1856 | 'Got `push` action from user %s, now unlocking', user) | |
1853 | # unlock if we have push from user who locked |
|
1857 | # unlock if we have push from user who locked | |
1854 | make_lock = False |
|
1858 | make_lock = False | |
1855 | else: |
|
1859 | else: | |
1856 | # we're not the same user who locked, ban with |
|
1860 | # we're not the same user who locked, ban with | |
1857 | # code defined in settings (default is 423 HTTP Locked) ! |
|
1861 | # code defined in settings (default is 423 HTTP Locked) ! | |
1858 | log.debug('Repo %s is currently locked by %s', repo, user) |
|
1862 | log.debug('Repo %s is currently locked by %s', repo, user) | |
1859 | currently_locked = True |
|
1863 | currently_locked = True | |
1860 | elif action == 'pull': |
|
1864 | elif action == 'pull': | |
1861 | # [0] user [1] date |
|
1865 | # [0] user [1] date | |
1862 | if lock_info[0] and lock_info[1]: |
|
1866 | if lock_info[0] and lock_info[1]: | |
1863 | log.debug('Repo %s is currently locked by %s', repo, user) |
|
1867 | log.debug('Repo %s is currently locked by %s', repo, user) | |
1864 | currently_locked = True |
|
1868 | currently_locked = True | |
1865 | else: |
|
1869 | else: | |
1866 | log.debug('Setting lock on repo %s by %s', repo, user) |
|
1870 | log.debug('Setting lock on repo %s by %s', repo, user) | |
1867 | make_lock = True |
|
1871 | make_lock = True | |
1868 |
|
1872 | |||
1869 | else: |
|
1873 | else: | |
1870 | log.debug('Repository %s do not have locking enabled', repo) |
|
1874 | log.debug('Repository %s do not have locking enabled', repo) | |
1871 |
|
1875 | |||
1872 | log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s', |
|
1876 | log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s', | |
1873 | make_lock, currently_locked, lock_info) |
|
1877 | make_lock, currently_locked, lock_info) | |
1874 |
|
1878 | |||
1875 | from rhodecode.lib.auth import HasRepoPermissionAny |
|
1879 | from rhodecode.lib.auth import HasRepoPermissionAny | |
1876 | perm_check = HasRepoPermissionAny('repository.write', 'repository.admin') |
|
1880 | perm_check = HasRepoPermissionAny('repository.write', 'repository.admin') | |
1877 | if make_lock and not perm_check(repo_name=repo.repo_name, user=user): |
|
1881 | if make_lock and not perm_check(repo_name=repo.repo_name, user=user): | |
1878 | # if we don't have at least write permission we cannot make a lock |
|
1882 | # if we don't have at least write permission we cannot make a lock | |
1879 | log.debug('lock state reset back to FALSE due to lack ' |
|
1883 | log.debug('lock state reset back to FALSE due to lack ' | |
1880 | 'of at least read permission') |
|
1884 | 'of at least read permission') | |
1881 | make_lock = False |
|
1885 | make_lock = False | |
1882 |
|
1886 | |||
1883 | return make_lock, currently_locked, lock_info |
|
1887 | return make_lock, currently_locked, lock_info | |
1884 |
|
1888 | |||
1885 | @property |
|
1889 | @property | |
1886 | def last_db_change(self): |
|
1890 | def last_db_change(self): | |
1887 | return self.updated_on |
|
1891 | return self.updated_on | |
1888 |
|
1892 | |||
1889 | @property |
|
1893 | @property | |
1890 | def clone_uri_hidden(self): |
|
1894 | def clone_uri_hidden(self): | |
1891 | clone_uri = self.clone_uri |
|
1895 | clone_uri = self.clone_uri | |
1892 | if clone_uri: |
|
1896 | if clone_uri: | |
1893 | import urlobject |
|
1897 | import urlobject | |
1894 | url_obj = urlobject.URLObject(cleaned_uri(clone_uri)) |
|
1898 | url_obj = urlobject.URLObject(cleaned_uri(clone_uri)) | |
1895 | if url_obj.password: |
|
1899 | if url_obj.password: | |
1896 | clone_uri = url_obj.with_password('*****') |
|
1900 | clone_uri = url_obj.with_password('*****') | |
1897 | return clone_uri |
|
1901 | return clone_uri | |
1898 |
|
1902 | |||
1899 | def clone_url(self, **override): |
|
1903 | def clone_url(self, **override): | |
1900 | qualified_home_url = url('home', qualified=True) |
|
1904 | qualified_home_url = url('home', qualified=True) | |
1901 |
|
1905 | |||
1902 | uri_tmpl = None |
|
1906 | uri_tmpl = None | |
1903 | if 'with_id' in override: |
|
1907 | if 'with_id' in override: | |
1904 | uri_tmpl = self.DEFAULT_CLONE_URI_ID |
|
1908 | uri_tmpl = self.DEFAULT_CLONE_URI_ID | |
1905 | del override['with_id'] |
|
1909 | del override['with_id'] | |
1906 |
|
1910 | |||
1907 | if 'uri_tmpl' in override: |
|
1911 | if 'uri_tmpl' in override: | |
1908 | uri_tmpl = override['uri_tmpl'] |
|
1912 | uri_tmpl = override['uri_tmpl'] | |
1909 | del override['uri_tmpl'] |
|
1913 | del override['uri_tmpl'] | |
1910 |
|
1914 | |||
1911 | # we didn't override our tmpl from **overrides |
|
1915 | # we didn't override our tmpl from **overrides | |
1912 | if not uri_tmpl: |
|
1916 | if not uri_tmpl: | |
1913 | uri_tmpl = self.DEFAULT_CLONE_URI |
|
1917 | uri_tmpl = self.DEFAULT_CLONE_URI | |
1914 | try: |
|
1918 | try: | |
1915 | from pylons import tmpl_context as c |
|
1919 | from pylons import tmpl_context as c | |
1916 | uri_tmpl = c.clone_uri_tmpl |
|
1920 | uri_tmpl = c.clone_uri_tmpl | |
1917 | except Exception: |
|
1921 | except Exception: | |
1918 | # in any case if we call this outside of request context, |
|
1922 | # in any case if we call this outside of request context, | |
1919 | # ie, not having tmpl_context set up |
|
1923 | # ie, not having tmpl_context set up | |
1920 | pass |
|
1924 | pass | |
1921 |
|
1925 | |||
1922 | return get_clone_url(uri_tmpl=uri_tmpl, |
|
1926 | return get_clone_url(uri_tmpl=uri_tmpl, | |
1923 | qualifed_home_url=qualified_home_url, |
|
1927 | qualifed_home_url=qualified_home_url, | |
1924 | repo_name=self.repo_name, |
|
1928 | repo_name=self.repo_name, | |
1925 | repo_id=self.repo_id, **override) |
|
1929 | repo_id=self.repo_id, **override) | |
1926 |
|
1930 | |||
1927 | def set_state(self, state): |
|
1931 | def set_state(self, state): | |
1928 | self.repo_state = state |
|
1932 | self.repo_state = state | |
1929 | Session().add(self) |
|
1933 | Session().add(self) | |
1930 | #========================================================================== |
|
1934 | #========================================================================== | |
1931 | # SCM PROPERTIES |
|
1935 | # SCM PROPERTIES | |
1932 | #========================================================================== |
|
1936 | #========================================================================== | |
1933 |
|
1937 | |||
1934 | def get_commit(self, commit_id=None, commit_idx=None, pre_load=None): |
|
1938 | def get_commit(self, commit_id=None, commit_idx=None, pre_load=None): | |
1935 | return get_commit_safe( |
|
1939 | return get_commit_safe( | |
1936 | self.scm_instance(), commit_id, commit_idx, pre_load=pre_load) |
|
1940 | self.scm_instance(), commit_id, commit_idx, pre_load=pre_load) | |
1937 |
|
1941 | |||
1938 | def get_changeset(self, rev=None, pre_load=None): |
|
1942 | def get_changeset(self, rev=None, pre_load=None): | |
1939 | warnings.warn("Use get_commit", DeprecationWarning) |
|
1943 | warnings.warn("Use get_commit", DeprecationWarning) | |
1940 | commit_id = None |
|
1944 | commit_id = None | |
1941 | commit_idx = None |
|
1945 | commit_idx = None | |
1942 | if isinstance(rev, basestring): |
|
1946 | if isinstance(rev, basestring): | |
1943 | commit_id = rev |
|
1947 | commit_id = rev | |
1944 | else: |
|
1948 | else: | |
1945 | commit_idx = rev |
|
1949 | commit_idx = rev | |
1946 | return self.get_commit(commit_id=commit_id, commit_idx=commit_idx, |
|
1950 | return self.get_commit(commit_id=commit_id, commit_idx=commit_idx, | |
1947 | pre_load=pre_load) |
|
1951 | pre_load=pre_load) | |
1948 |
|
1952 | |||
1949 | def get_landing_commit(self): |
|
1953 | def get_landing_commit(self): | |
1950 | """ |
|
1954 | """ | |
1951 | Returns landing commit, or if that doesn't exist returns the tip |
|
1955 | Returns landing commit, or if that doesn't exist returns the tip | |
1952 | """ |
|
1956 | """ | |
1953 | _rev_type, _rev = self.landing_rev |
|
1957 | _rev_type, _rev = self.landing_rev | |
1954 | commit = self.get_commit(_rev) |
|
1958 | commit = self.get_commit(_rev) | |
1955 | if isinstance(commit, EmptyCommit): |
|
1959 | if isinstance(commit, EmptyCommit): | |
1956 | return self.get_commit() |
|
1960 | return self.get_commit() | |
1957 | return commit |
|
1961 | return commit | |
1958 |
|
1962 | |||
1959 | def update_commit_cache(self, cs_cache=None, config=None): |
|
1963 | def update_commit_cache(self, cs_cache=None, config=None): | |
1960 | """ |
|
1964 | """ | |
1961 | Update cache of last changeset for repository, keys should be:: |
|
1965 | Update cache of last changeset for repository, keys should be:: | |
1962 |
|
1966 | |||
1963 | short_id |
|
1967 | short_id | |
1964 | raw_id |
|
1968 | raw_id | |
1965 | revision |
|
1969 | revision | |
1966 | parents |
|
1970 | parents | |
1967 | message |
|
1971 | message | |
1968 | date |
|
1972 | date | |
1969 | author |
|
1973 | author | |
1970 |
|
1974 | |||
1971 | :param cs_cache: |
|
1975 | :param cs_cache: | |
1972 | """ |
|
1976 | """ | |
1973 | from rhodecode.lib.vcs.backends.base import BaseChangeset |
|
1977 | from rhodecode.lib.vcs.backends.base import BaseChangeset | |
1974 | if cs_cache is None: |
|
1978 | if cs_cache is None: | |
1975 | # use no-cache version here |
|
1979 | # use no-cache version here | |
1976 | scm_repo = self.scm_instance(cache=False, config=config) |
|
1980 | scm_repo = self.scm_instance(cache=False, config=config) | |
1977 | if scm_repo: |
|
1981 | if scm_repo: | |
1978 | cs_cache = scm_repo.get_commit( |
|
1982 | cs_cache = scm_repo.get_commit( | |
1979 | pre_load=["author", "date", "message", "parents"]) |
|
1983 | pre_load=["author", "date", "message", "parents"]) | |
1980 | else: |
|
1984 | else: | |
1981 | cs_cache = EmptyCommit() |
|
1985 | cs_cache = EmptyCommit() | |
1982 |
|
1986 | |||
1983 | if isinstance(cs_cache, BaseChangeset): |
|
1987 | if isinstance(cs_cache, BaseChangeset): | |
1984 | cs_cache = cs_cache.__json__() |
|
1988 | cs_cache = cs_cache.__json__() | |
1985 |
|
1989 | |||
1986 | def is_outdated(new_cs_cache): |
|
1990 | def is_outdated(new_cs_cache): | |
1987 | if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or |
|
1991 | if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or | |
1988 | new_cs_cache['revision'] != self.changeset_cache['revision']): |
|
1992 | new_cs_cache['revision'] != self.changeset_cache['revision']): | |
1989 | return True |
|
1993 | return True | |
1990 | return False |
|
1994 | return False | |
1991 |
|
1995 | |||
1992 | # check if we have maybe already latest cached revision |
|
1996 | # check if we have maybe already latest cached revision | |
1993 | if is_outdated(cs_cache) or not self.changeset_cache: |
|
1997 | if is_outdated(cs_cache) or not self.changeset_cache: | |
1994 | _default = datetime.datetime.fromtimestamp(0) |
|
1998 | _default = datetime.datetime.fromtimestamp(0) | |
1995 | last_change = cs_cache.get('date') or _default |
|
1999 | last_change = cs_cache.get('date') or _default | |
1996 | log.debug('updated repo %s with new cs cache %s', |
|
2000 | log.debug('updated repo %s with new cs cache %s', | |
1997 | self.repo_name, cs_cache) |
|
2001 | self.repo_name, cs_cache) | |
1998 | self.updated_on = last_change |
|
2002 | self.updated_on = last_change | |
1999 | self.changeset_cache = cs_cache |
|
2003 | self.changeset_cache = cs_cache | |
2000 | Session().add(self) |
|
2004 | Session().add(self) | |
2001 | Session().commit() |
|
2005 | Session().commit() | |
2002 | else: |
|
2006 | else: | |
2003 | log.debug('Skipping update_commit_cache for repo:`%s` ' |
|
2007 | log.debug('Skipping update_commit_cache for repo:`%s` ' | |
2004 | 'commit already with latest changes', self.repo_name) |
|
2008 | 'commit already with latest changes', self.repo_name) | |
2005 |
|
2009 | |||
2006 | @property |
|
2010 | @property | |
2007 | def tip(self): |
|
2011 | def tip(self): | |
2008 | return self.get_commit('tip') |
|
2012 | return self.get_commit('tip') | |
2009 |
|
2013 | |||
2010 | @property |
|
2014 | @property | |
2011 | def author(self): |
|
2015 | def author(self): | |
2012 | return self.tip.author |
|
2016 | return self.tip.author | |
2013 |
|
2017 | |||
2014 | @property |
|
2018 | @property | |
2015 | def last_change(self): |
|
2019 | def last_change(self): | |
2016 | return self.scm_instance().last_change |
|
2020 | return self.scm_instance().last_change | |
2017 |
|
2021 | |||
2018 | def get_comments(self, revisions=None): |
|
2022 | def get_comments(self, revisions=None): | |
2019 | """ |
|
2023 | """ | |
2020 | Returns comments for this repository grouped by revisions |
|
2024 | Returns comments for this repository grouped by revisions | |
2021 |
|
2025 | |||
2022 | :param revisions: filter query by revisions only |
|
2026 | :param revisions: filter query by revisions only | |
2023 | """ |
|
2027 | """ | |
2024 | cmts = ChangesetComment.query()\ |
|
2028 | cmts = ChangesetComment.query()\ | |
2025 | .filter(ChangesetComment.repo == self) |
|
2029 | .filter(ChangesetComment.repo == self) | |
2026 | if revisions: |
|
2030 | if revisions: | |
2027 | cmts = cmts.filter(ChangesetComment.revision.in_(revisions)) |
|
2031 | cmts = cmts.filter(ChangesetComment.revision.in_(revisions)) | |
2028 | grouped = collections.defaultdict(list) |
|
2032 | grouped = collections.defaultdict(list) | |
2029 | for cmt in cmts.all(): |
|
2033 | for cmt in cmts.all(): | |
2030 | grouped[cmt.revision].append(cmt) |
|
2034 | grouped[cmt.revision].append(cmt) | |
2031 | return grouped |
|
2035 | return grouped | |
2032 |
|
2036 | |||
2033 | def statuses(self, revisions=None): |
|
2037 | def statuses(self, revisions=None): | |
2034 | """ |
|
2038 | """ | |
2035 | Returns statuses for this repository |
|
2039 | Returns statuses for this repository | |
2036 |
|
2040 | |||
2037 | :param revisions: list of revisions to get statuses for |
|
2041 | :param revisions: list of revisions to get statuses for | |
2038 | """ |
|
2042 | """ | |
2039 | statuses = ChangesetStatus.query()\ |
|
2043 | statuses = ChangesetStatus.query()\ | |
2040 | .filter(ChangesetStatus.repo == self)\ |
|
2044 | .filter(ChangesetStatus.repo == self)\ | |
2041 | .filter(ChangesetStatus.version == 0) |
|
2045 | .filter(ChangesetStatus.version == 0) | |
2042 |
|
2046 | |||
2043 | if revisions: |
|
2047 | if revisions: | |
2044 | # Try doing the filtering in chunks to avoid hitting limits |
|
2048 | # Try doing the filtering in chunks to avoid hitting limits | |
2045 | size = 500 |
|
2049 | size = 500 | |
2046 | status_results = [] |
|
2050 | status_results = [] | |
2047 | for chunk in xrange(0, len(revisions), size): |
|
2051 | for chunk in xrange(0, len(revisions), size): | |
2048 | status_results += statuses.filter( |
|
2052 | status_results += statuses.filter( | |
2049 | ChangesetStatus.revision.in_( |
|
2053 | ChangesetStatus.revision.in_( | |
2050 | revisions[chunk: chunk+size]) |
|
2054 | revisions[chunk: chunk+size]) | |
2051 | ).all() |
|
2055 | ).all() | |
2052 | else: |
|
2056 | else: | |
2053 | status_results = statuses.all() |
|
2057 | status_results = statuses.all() | |
2054 |
|
2058 | |||
2055 | grouped = {} |
|
2059 | grouped = {} | |
2056 |
|
2060 | |||
2057 | # maybe we have open new pullrequest without a status? |
|
2061 | # maybe we have open new pullrequest without a status? | |
2058 | stat = ChangesetStatus.STATUS_UNDER_REVIEW |
|
2062 | stat = ChangesetStatus.STATUS_UNDER_REVIEW | |
2059 | status_lbl = ChangesetStatus.get_status_lbl(stat) |
|
2063 | status_lbl = ChangesetStatus.get_status_lbl(stat) | |
2060 | for pr in PullRequest.query().filter(PullRequest.source_repo == self).all(): |
|
2064 | for pr in PullRequest.query().filter(PullRequest.source_repo == self).all(): | |
2061 | for rev in pr.revisions: |
|
2065 | for rev in pr.revisions: | |
2062 | pr_id = pr.pull_request_id |
|
2066 | pr_id = pr.pull_request_id | |
2063 | pr_repo = pr.target_repo.repo_name |
|
2067 | pr_repo = pr.target_repo.repo_name | |
2064 | grouped[rev] = [stat, status_lbl, pr_id, pr_repo] |
|
2068 | grouped[rev] = [stat, status_lbl, pr_id, pr_repo] | |
2065 |
|
2069 | |||
2066 | for stat in status_results: |
|
2070 | for stat in status_results: | |
2067 | pr_id = pr_repo = None |
|
2071 | pr_id = pr_repo = None | |
2068 | if stat.pull_request: |
|
2072 | if stat.pull_request: | |
2069 | pr_id = stat.pull_request.pull_request_id |
|
2073 | pr_id = stat.pull_request.pull_request_id | |
2070 | pr_repo = stat.pull_request.target_repo.repo_name |
|
2074 | pr_repo = stat.pull_request.target_repo.repo_name | |
2071 | grouped[stat.revision] = [str(stat.status), stat.status_lbl, |
|
2075 | grouped[stat.revision] = [str(stat.status), stat.status_lbl, | |
2072 | pr_id, pr_repo] |
|
2076 | pr_id, pr_repo] | |
2073 | return grouped |
|
2077 | return grouped | |
2074 |
|
2078 | |||
2075 | # ========================================================================== |
|
2079 | # ========================================================================== | |
2076 | # SCM CACHE INSTANCE |
|
2080 | # SCM CACHE INSTANCE | |
2077 | # ========================================================================== |
|
2081 | # ========================================================================== | |
2078 |
|
2082 | |||
2079 | def scm_instance(self, **kwargs): |
|
2083 | def scm_instance(self, **kwargs): | |
2080 | import rhodecode |
|
2084 | import rhodecode | |
2081 |
|
2085 | |||
2082 | # Passing a config will not hit the cache currently only used |
|
2086 | # Passing a config will not hit the cache currently only used | |
2083 | # for repo2dbmapper |
|
2087 | # for repo2dbmapper | |
2084 | config = kwargs.pop('config', None) |
|
2088 | config = kwargs.pop('config', None) | |
2085 | cache = kwargs.pop('cache', None) |
|
2089 | cache = kwargs.pop('cache', None) | |
2086 | full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache')) |
|
2090 | full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache')) | |
2087 | # if cache is NOT defined use default global, else we have a full |
|
2091 | # if cache is NOT defined use default global, else we have a full | |
2088 | # control over cache behaviour |
|
2092 | # control over cache behaviour | |
2089 | if cache is None and full_cache and not config: |
|
2093 | if cache is None and full_cache and not config: | |
2090 | return self._get_instance_cached() |
|
2094 | return self._get_instance_cached() | |
2091 | return self._get_instance(cache=bool(cache), config=config) |
|
2095 | return self._get_instance(cache=bool(cache), config=config) | |
2092 |
|
2096 | |||
2093 | def _get_instance_cached(self): |
|
2097 | def _get_instance_cached(self): | |
2094 | @cache_region('long_term') |
|
2098 | @cache_region('long_term') | |
2095 | def _get_repo(cache_key): |
|
2099 | def _get_repo(cache_key): | |
2096 | return self._get_instance() |
|
2100 | return self._get_instance() | |
2097 |
|
2101 | |||
2098 | invalidator_context = CacheKey.repo_context_cache( |
|
2102 | invalidator_context = CacheKey.repo_context_cache( | |
2099 | _get_repo, self.repo_name, None, thread_scoped=True) |
|
2103 | _get_repo, self.repo_name, None, thread_scoped=True) | |
2100 |
|
2104 | |||
2101 | with invalidator_context as context: |
|
2105 | with invalidator_context as context: | |
2102 | context.invalidate() |
|
2106 | context.invalidate() | |
2103 | repo = context.compute() |
|
2107 | repo = context.compute() | |
2104 |
|
2108 | |||
2105 | return repo |
|
2109 | return repo | |
2106 |
|
2110 | |||
2107 | def _get_instance(self, cache=True, config=None): |
|
2111 | def _get_instance(self, cache=True, config=None): | |
2108 | config = config or self._config |
|
2112 | config = config or self._config | |
2109 | custom_wire = { |
|
2113 | custom_wire = { | |
2110 | 'cache': cache # controls the vcs.remote cache |
|
2114 | 'cache': cache # controls the vcs.remote cache | |
2111 | } |
|
2115 | } | |
2112 | repo = get_vcs_instance( |
|
2116 | repo = get_vcs_instance( | |
2113 | repo_path=safe_str(self.repo_full_path), |
|
2117 | repo_path=safe_str(self.repo_full_path), | |
2114 | config=config, |
|
2118 | config=config, | |
2115 | with_wire=custom_wire, |
|
2119 | with_wire=custom_wire, | |
2116 | create=False, |
|
2120 | create=False, | |
2117 | _vcs_alias=self.repo_type) |
|
2121 | _vcs_alias=self.repo_type) | |
2118 |
|
2122 | |||
2119 | return repo |
|
2123 | return repo | |
2120 |
|
2124 | |||
2121 | def __json__(self): |
|
2125 | def __json__(self): | |
2122 | return {'landing_rev': self.landing_rev} |
|
2126 | return {'landing_rev': self.landing_rev} | |
2123 |
|
2127 | |||
2124 | def get_dict(self): |
|
2128 | def get_dict(self): | |
2125 |
|
2129 | |||
2126 | # Since we transformed `repo_name` to a hybrid property, we need to |
|
2130 | # Since we transformed `repo_name` to a hybrid property, we need to | |
2127 | # keep compatibility with the code which uses `repo_name` field. |
|
2131 | # keep compatibility with the code which uses `repo_name` field. | |
2128 |
|
2132 | |||
2129 | result = super(Repository, self).get_dict() |
|
2133 | result = super(Repository, self).get_dict() | |
2130 | result['repo_name'] = result.pop('_repo_name', None) |
|
2134 | result['repo_name'] = result.pop('_repo_name', None) | |
2131 | return result |
|
2135 | return result | |
2132 |
|
2136 | |||
2133 |
|
2137 | |||
2134 | class RepoGroup(Base, BaseModel): |
|
2138 | class RepoGroup(Base, BaseModel): | |
2135 | __tablename__ = 'groups' |
|
2139 | __tablename__ = 'groups' | |
2136 | __table_args__ = ( |
|
2140 | __table_args__ = ( | |
2137 | UniqueConstraint('group_name', 'group_parent_id'), |
|
2141 | UniqueConstraint('group_name', 'group_parent_id'), | |
2138 | CheckConstraint('group_id != group_parent_id'), |
|
2142 | CheckConstraint('group_id != group_parent_id'), | |
2139 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2143 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2140 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
2144 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
2141 | ) |
|
2145 | ) | |
2142 | __mapper_args__ = {'order_by': 'group_name'} |
|
2146 | __mapper_args__ = {'order_by': 'group_name'} | |
2143 |
|
2147 | |||
2144 | CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups |
|
2148 | CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups | |
2145 |
|
2149 | |||
2146 | group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2150 | group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2147 | group_name = Column("group_name", String(255), nullable=False, unique=True, default=None) |
|
2151 | group_name = Column("group_name", String(255), nullable=False, unique=True, default=None) | |
2148 | group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None) |
|
2152 | group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None) | |
2149 | group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None) |
|
2153 | group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None) | |
2150 | enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False) |
|
2154 | enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False) | |
2151 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None) |
|
2155 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None) | |
2152 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
2156 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
2153 | personal = Column('personal', Boolean(), nullable=True, unique=None, default=None) |
|
2157 | personal = Column('personal', Boolean(), nullable=True, unique=None, default=None) | |
2154 |
|
2158 | |||
2155 | repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id') |
|
2159 | repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id') | |
2156 | users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all') |
|
2160 | users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all') | |
2157 | parent_group = relationship('RepoGroup', remote_side=group_id) |
|
2161 | parent_group = relationship('RepoGroup', remote_side=group_id) | |
2158 | user = relationship('User') |
|
2162 | user = relationship('User') | |
2159 | integrations = relationship('Integration', |
|
2163 | integrations = relationship('Integration', | |
2160 | cascade="all, delete, delete-orphan") |
|
2164 | cascade="all, delete, delete-orphan") | |
2161 |
|
2165 | |||
2162 | def __init__(self, group_name='', parent_group=None): |
|
2166 | def __init__(self, group_name='', parent_group=None): | |
2163 | self.group_name = group_name |
|
2167 | self.group_name = group_name | |
2164 | self.parent_group = parent_group |
|
2168 | self.parent_group = parent_group | |
2165 |
|
2169 | |||
2166 | def __unicode__(self): |
|
2170 | def __unicode__(self): | |
2167 | return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id, |
|
2171 | return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id, | |
2168 | self.group_name) |
|
2172 | self.group_name) | |
2169 |
|
2173 | |||
2170 | @classmethod |
|
2174 | @classmethod | |
2171 | def _generate_choice(cls, repo_group): |
|
2175 | def _generate_choice(cls, repo_group): | |
2172 | from webhelpers.html import literal as _literal |
|
2176 | from webhelpers.html import literal as _literal | |
2173 | _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k)) |
|
2177 | _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k)) | |
2174 | return repo_group.group_id, _name(repo_group.full_path_splitted) |
|
2178 | return repo_group.group_id, _name(repo_group.full_path_splitted) | |
2175 |
|
2179 | |||
2176 | @classmethod |
|
2180 | @classmethod | |
2177 | def groups_choices(cls, groups=None, show_empty_group=True): |
|
2181 | def groups_choices(cls, groups=None, show_empty_group=True): | |
2178 | if not groups: |
|
2182 | if not groups: | |
2179 | groups = cls.query().all() |
|
2183 | groups = cls.query().all() | |
2180 |
|
2184 | |||
2181 | repo_groups = [] |
|
2185 | repo_groups = [] | |
2182 | if show_empty_group: |
|
2186 | if show_empty_group: | |
2183 | repo_groups = [('-1', u'-- %s --' % _('No parent'))] |
|
2187 | repo_groups = [('-1', u'-- %s --' % _('No parent'))] | |
2184 |
|
2188 | |||
2185 | repo_groups.extend([cls._generate_choice(x) for x in groups]) |
|
2189 | repo_groups.extend([cls._generate_choice(x) for x in groups]) | |
2186 |
|
2190 | |||
2187 | repo_groups = sorted( |
|
2191 | repo_groups = sorted( | |
2188 | repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0]) |
|
2192 | repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0]) | |
2189 | return repo_groups |
|
2193 | return repo_groups | |
2190 |
|
2194 | |||
2191 | @classmethod |
|
2195 | @classmethod | |
2192 | def url_sep(cls): |
|
2196 | def url_sep(cls): | |
2193 | return URL_SEP |
|
2197 | return URL_SEP | |
2194 |
|
2198 | |||
2195 | @classmethod |
|
2199 | @classmethod | |
2196 | def get_by_group_name(cls, group_name, cache=False, case_insensitive=False): |
|
2200 | def get_by_group_name(cls, group_name, cache=False, case_insensitive=False): | |
2197 | if case_insensitive: |
|
2201 | if case_insensitive: | |
2198 | gr = cls.query().filter(func.lower(cls.group_name) |
|
2202 | gr = cls.query().filter(func.lower(cls.group_name) | |
2199 | == func.lower(group_name)) |
|
2203 | == func.lower(group_name)) | |
2200 | else: |
|
2204 | else: | |
2201 | gr = cls.query().filter(cls.group_name == group_name) |
|
2205 | gr = cls.query().filter(cls.group_name == group_name) | |
2202 | if cache: |
|
2206 | if cache: | |
2203 | gr = gr.options(FromCache( |
|
2207 | gr = gr.options(FromCache( | |
2204 | "sql_cache_short", |
|
2208 | "sql_cache_short", | |
2205 | "get_group_%s" % _hash_key(group_name))) |
|
2209 | "get_group_%s" % _hash_key(group_name))) | |
2206 | return gr.scalar() |
|
2210 | return gr.scalar() | |
2207 |
|
2211 | |||
2208 | @classmethod |
|
2212 | @classmethod | |
2209 | def get_user_personal_repo_group(cls, user_id): |
|
2213 | def get_user_personal_repo_group(cls, user_id): | |
2210 | user = User.get(user_id) |
|
2214 | user = User.get(user_id) | |
2211 | if user.username == User.DEFAULT_USER: |
|
2215 | if user.username == User.DEFAULT_USER: | |
2212 | return None |
|
2216 | return None | |
2213 |
|
2217 | |||
2214 | return cls.query()\ |
|
2218 | return cls.query()\ | |
2215 | .filter(cls.personal == true()) \ |
|
2219 | .filter(cls.personal == true()) \ | |
2216 | .filter(cls.user == user).scalar() |
|
2220 | .filter(cls.user == user).scalar() | |
2217 |
|
2221 | |||
2218 | @classmethod |
|
2222 | @classmethod | |
2219 | def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None), |
|
2223 | def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None), | |
2220 | case_insensitive=True): |
|
2224 | case_insensitive=True): | |
2221 | q = RepoGroup.query() |
|
2225 | q = RepoGroup.query() | |
2222 |
|
2226 | |||
2223 | if not isinstance(user_id, Optional): |
|
2227 | if not isinstance(user_id, Optional): | |
2224 | q = q.filter(RepoGroup.user_id == user_id) |
|
2228 | q = q.filter(RepoGroup.user_id == user_id) | |
2225 |
|
2229 | |||
2226 | if not isinstance(group_id, Optional): |
|
2230 | if not isinstance(group_id, Optional): | |
2227 | q = q.filter(RepoGroup.group_parent_id == group_id) |
|
2231 | q = q.filter(RepoGroup.group_parent_id == group_id) | |
2228 |
|
2232 | |||
2229 | if case_insensitive: |
|
2233 | if case_insensitive: | |
2230 | q = q.order_by(func.lower(RepoGroup.group_name)) |
|
2234 | q = q.order_by(func.lower(RepoGroup.group_name)) | |
2231 | else: |
|
2235 | else: | |
2232 | q = q.order_by(RepoGroup.group_name) |
|
2236 | q = q.order_by(RepoGroup.group_name) | |
2233 | return q.all() |
|
2237 | return q.all() | |
2234 |
|
2238 | |||
2235 | @property |
|
2239 | @property | |
2236 | def parents(self): |
|
2240 | def parents(self): | |
2237 | parents_recursion_limit = 10 |
|
2241 | parents_recursion_limit = 10 | |
2238 | groups = [] |
|
2242 | groups = [] | |
2239 | if self.parent_group is None: |
|
2243 | if self.parent_group is None: | |
2240 | return groups |
|
2244 | return groups | |
2241 | cur_gr = self.parent_group |
|
2245 | cur_gr = self.parent_group | |
2242 | groups.insert(0, cur_gr) |
|
2246 | groups.insert(0, cur_gr) | |
2243 | cnt = 0 |
|
2247 | cnt = 0 | |
2244 | while 1: |
|
2248 | while 1: | |
2245 | cnt += 1 |
|
2249 | cnt += 1 | |
2246 | gr = getattr(cur_gr, 'parent_group', None) |
|
2250 | gr = getattr(cur_gr, 'parent_group', None) | |
2247 | cur_gr = cur_gr.parent_group |
|
2251 | cur_gr = cur_gr.parent_group | |
2248 | if gr is None: |
|
2252 | if gr is None: | |
2249 | break |
|
2253 | break | |
2250 | if cnt == parents_recursion_limit: |
|
2254 | if cnt == parents_recursion_limit: | |
2251 | # this will prevent accidental infinit loops |
|
2255 | # this will prevent accidental infinit loops | |
2252 | log.error(('more than %s parents found for group %s, stopping ' |
|
2256 | log.error(('more than %s parents found for group %s, stopping ' | |
2253 | 'recursive parent fetching' % (parents_recursion_limit, self))) |
|
2257 | 'recursive parent fetching' % (parents_recursion_limit, self))) | |
2254 | break |
|
2258 | break | |
2255 |
|
2259 | |||
2256 | groups.insert(0, gr) |
|
2260 | groups.insert(0, gr) | |
2257 | return groups |
|
2261 | return groups | |
2258 |
|
2262 | |||
2259 | @property |
|
2263 | @property | |
2260 | def children(self): |
|
2264 | def children(self): | |
2261 | return RepoGroup.query().filter(RepoGroup.parent_group == self) |
|
2265 | return RepoGroup.query().filter(RepoGroup.parent_group == self) | |
2262 |
|
2266 | |||
2263 | @property |
|
2267 | @property | |
2264 | def name(self): |
|
2268 | def name(self): | |
2265 | return self.group_name.split(RepoGroup.url_sep())[-1] |
|
2269 | return self.group_name.split(RepoGroup.url_sep())[-1] | |
2266 |
|
2270 | |||
2267 | @property |
|
2271 | @property | |
2268 | def full_path(self): |
|
2272 | def full_path(self): | |
2269 | return self.group_name |
|
2273 | return self.group_name | |
2270 |
|
2274 | |||
2271 | @property |
|
2275 | @property | |
2272 | def full_path_splitted(self): |
|
2276 | def full_path_splitted(self): | |
2273 | return self.group_name.split(RepoGroup.url_sep()) |
|
2277 | return self.group_name.split(RepoGroup.url_sep()) | |
2274 |
|
2278 | |||
2275 | @property |
|
2279 | @property | |
2276 | def repositories(self): |
|
2280 | def repositories(self): | |
2277 | return Repository.query()\ |
|
2281 | return Repository.query()\ | |
2278 | .filter(Repository.group == self)\ |
|
2282 | .filter(Repository.group == self)\ | |
2279 | .order_by(Repository.repo_name) |
|
2283 | .order_by(Repository.repo_name) | |
2280 |
|
2284 | |||
2281 | @property |
|
2285 | @property | |
2282 | def repositories_recursive_count(self): |
|
2286 | def repositories_recursive_count(self): | |
2283 | cnt = self.repositories.count() |
|
2287 | cnt = self.repositories.count() | |
2284 |
|
2288 | |||
2285 | def children_count(group): |
|
2289 | def children_count(group): | |
2286 | cnt = 0 |
|
2290 | cnt = 0 | |
2287 | for child in group.children: |
|
2291 | for child in group.children: | |
2288 | cnt += child.repositories.count() |
|
2292 | cnt += child.repositories.count() | |
2289 | cnt += children_count(child) |
|
2293 | cnt += children_count(child) | |
2290 | return cnt |
|
2294 | return cnt | |
2291 |
|
2295 | |||
2292 | return cnt + children_count(self) |
|
2296 | return cnt + children_count(self) | |
2293 |
|
2297 | |||
2294 | def _recursive_objects(self, include_repos=True): |
|
2298 | def _recursive_objects(self, include_repos=True): | |
2295 | all_ = [] |
|
2299 | all_ = [] | |
2296 |
|
2300 | |||
2297 | def _get_members(root_gr): |
|
2301 | def _get_members(root_gr): | |
2298 | if include_repos: |
|
2302 | if include_repos: | |
2299 | for r in root_gr.repositories: |
|
2303 | for r in root_gr.repositories: | |
2300 | all_.append(r) |
|
2304 | all_.append(r) | |
2301 | childs = root_gr.children.all() |
|
2305 | childs = root_gr.children.all() | |
2302 | if childs: |
|
2306 | if childs: | |
2303 | for gr in childs: |
|
2307 | for gr in childs: | |
2304 | all_.append(gr) |
|
2308 | all_.append(gr) | |
2305 | _get_members(gr) |
|
2309 | _get_members(gr) | |
2306 |
|
2310 | |||
2307 | _get_members(self) |
|
2311 | _get_members(self) | |
2308 | return [self] + all_ |
|
2312 | return [self] + all_ | |
2309 |
|
2313 | |||
2310 | def recursive_groups_and_repos(self): |
|
2314 | def recursive_groups_and_repos(self): | |
2311 | """ |
|
2315 | """ | |
2312 | Recursive return all groups, with repositories in those groups |
|
2316 | Recursive return all groups, with repositories in those groups | |
2313 | """ |
|
2317 | """ | |
2314 | return self._recursive_objects() |
|
2318 | return self._recursive_objects() | |
2315 |
|
2319 | |||
2316 | def recursive_groups(self): |
|
2320 | def recursive_groups(self): | |
2317 | """ |
|
2321 | """ | |
2318 | Returns all children groups for this group including children of children |
|
2322 | Returns all children groups for this group including children of children | |
2319 | """ |
|
2323 | """ | |
2320 | return self._recursive_objects(include_repos=False) |
|
2324 | return self._recursive_objects(include_repos=False) | |
2321 |
|
2325 | |||
2322 | def get_new_name(self, group_name): |
|
2326 | def get_new_name(self, group_name): | |
2323 | """ |
|
2327 | """ | |
2324 | returns new full group name based on parent and new name |
|
2328 | returns new full group name based on parent and new name | |
2325 |
|
2329 | |||
2326 | :param group_name: |
|
2330 | :param group_name: | |
2327 | """ |
|
2331 | """ | |
2328 | path_prefix = (self.parent_group.full_path_splitted if |
|
2332 | path_prefix = (self.parent_group.full_path_splitted if | |
2329 | self.parent_group else []) |
|
2333 | self.parent_group else []) | |
2330 | return RepoGroup.url_sep().join(path_prefix + [group_name]) |
|
2334 | return RepoGroup.url_sep().join(path_prefix + [group_name]) | |
2331 |
|
2335 | |||
2332 | def permissions(self, with_admins=True, with_owner=True): |
|
2336 | def permissions(self, with_admins=True, with_owner=True): | |
2333 | q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self) |
|
2337 | q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self) | |
2334 | q = q.options(joinedload(UserRepoGroupToPerm.group), |
|
2338 | q = q.options(joinedload(UserRepoGroupToPerm.group), | |
2335 | joinedload(UserRepoGroupToPerm.user), |
|
2339 | joinedload(UserRepoGroupToPerm.user), | |
2336 | joinedload(UserRepoGroupToPerm.permission),) |
|
2340 | joinedload(UserRepoGroupToPerm.permission),) | |
2337 |
|
2341 | |||
2338 | # get owners and admins and permissions. We do a trick of re-writing |
|
2342 | # get owners and admins and permissions. We do a trick of re-writing | |
2339 | # objects from sqlalchemy to named-tuples due to sqlalchemy session |
|
2343 | # objects from sqlalchemy to named-tuples due to sqlalchemy session | |
2340 | # has a global reference and changing one object propagates to all |
|
2344 | # has a global reference and changing one object propagates to all | |
2341 | # others. This means if admin is also an owner admin_row that change |
|
2345 | # others. This means if admin is also an owner admin_row that change | |
2342 | # would propagate to both objects |
|
2346 | # would propagate to both objects | |
2343 | perm_rows = [] |
|
2347 | perm_rows = [] | |
2344 | for _usr in q.all(): |
|
2348 | for _usr in q.all(): | |
2345 | usr = AttributeDict(_usr.user.get_dict()) |
|
2349 | usr = AttributeDict(_usr.user.get_dict()) | |
2346 | usr.permission = _usr.permission.permission_name |
|
2350 | usr.permission = _usr.permission.permission_name | |
2347 | perm_rows.append(usr) |
|
2351 | perm_rows.append(usr) | |
2348 |
|
2352 | |||
2349 | # filter the perm rows by 'default' first and then sort them by |
|
2353 | # filter the perm rows by 'default' first and then sort them by | |
2350 | # admin,write,read,none permissions sorted again alphabetically in |
|
2354 | # admin,write,read,none permissions sorted again alphabetically in | |
2351 | # each group |
|
2355 | # each group | |
2352 | perm_rows = sorted(perm_rows, key=display_sort) |
|
2356 | perm_rows = sorted(perm_rows, key=display_sort) | |
2353 |
|
2357 | |||
2354 | _admin_perm = 'group.admin' |
|
2358 | _admin_perm = 'group.admin' | |
2355 | owner_row = [] |
|
2359 | owner_row = [] | |
2356 | if with_owner: |
|
2360 | if with_owner: | |
2357 | usr = AttributeDict(self.user.get_dict()) |
|
2361 | usr = AttributeDict(self.user.get_dict()) | |
2358 | usr.owner_row = True |
|
2362 | usr.owner_row = True | |
2359 | usr.permission = _admin_perm |
|
2363 | usr.permission = _admin_perm | |
2360 | owner_row.append(usr) |
|
2364 | owner_row.append(usr) | |
2361 |
|
2365 | |||
2362 | super_admin_rows = [] |
|
2366 | super_admin_rows = [] | |
2363 | if with_admins: |
|
2367 | if with_admins: | |
2364 | for usr in User.get_all_super_admins(): |
|
2368 | for usr in User.get_all_super_admins(): | |
2365 | # if this admin is also owner, don't double the record |
|
2369 | # if this admin is also owner, don't double the record | |
2366 | if usr.user_id == owner_row[0].user_id: |
|
2370 | if usr.user_id == owner_row[0].user_id: | |
2367 | owner_row[0].admin_row = True |
|
2371 | owner_row[0].admin_row = True | |
2368 | else: |
|
2372 | else: | |
2369 | usr = AttributeDict(usr.get_dict()) |
|
2373 | usr = AttributeDict(usr.get_dict()) | |
2370 | usr.admin_row = True |
|
2374 | usr.admin_row = True | |
2371 | usr.permission = _admin_perm |
|
2375 | usr.permission = _admin_perm | |
2372 | super_admin_rows.append(usr) |
|
2376 | super_admin_rows.append(usr) | |
2373 |
|
2377 | |||
2374 | return super_admin_rows + owner_row + perm_rows |
|
2378 | return super_admin_rows + owner_row + perm_rows | |
2375 |
|
2379 | |||
2376 | def permission_user_groups(self): |
|
2380 | def permission_user_groups(self): | |
2377 | q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self) |
|
2381 | q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self) | |
2378 | q = q.options(joinedload(UserGroupRepoGroupToPerm.group), |
|
2382 | q = q.options(joinedload(UserGroupRepoGroupToPerm.group), | |
2379 | joinedload(UserGroupRepoGroupToPerm.users_group), |
|
2383 | joinedload(UserGroupRepoGroupToPerm.users_group), | |
2380 | joinedload(UserGroupRepoGroupToPerm.permission),) |
|
2384 | joinedload(UserGroupRepoGroupToPerm.permission),) | |
2381 |
|
2385 | |||
2382 | perm_rows = [] |
|
2386 | perm_rows = [] | |
2383 | for _user_group in q.all(): |
|
2387 | for _user_group in q.all(): | |
2384 | usr = AttributeDict(_user_group.users_group.get_dict()) |
|
2388 | usr = AttributeDict(_user_group.users_group.get_dict()) | |
2385 | usr.permission = _user_group.permission.permission_name |
|
2389 | usr.permission = _user_group.permission.permission_name | |
2386 | perm_rows.append(usr) |
|
2390 | perm_rows.append(usr) | |
2387 |
|
2391 | |||
2388 | return perm_rows |
|
2392 | return perm_rows | |
2389 |
|
2393 | |||
2390 | def get_api_data(self): |
|
2394 | def get_api_data(self): | |
2391 | """ |
|
2395 | """ | |
2392 | Common function for generating api data |
|
2396 | Common function for generating api data | |
2393 |
|
2397 | |||
2394 | """ |
|
2398 | """ | |
2395 | group = self |
|
2399 | group = self | |
2396 | data = { |
|
2400 | data = { | |
2397 | 'group_id': group.group_id, |
|
2401 | 'group_id': group.group_id, | |
2398 | 'group_name': group.group_name, |
|
2402 | 'group_name': group.group_name, | |
2399 | 'group_description': group.group_description, |
|
2403 | 'group_description': group.group_description, | |
2400 | 'parent_group': group.parent_group.group_name if group.parent_group else None, |
|
2404 | 'parent_group': group.parent_group.group_name if group.parent_group else None, | |
2401 | 'repositories': [x.repo_name for x in group.repositories], |
|
2405 | 'repositories': [x.repo_name for x in group.repositories], | |
2402 | 'owner': group.user.username, |
|
2406 | 'owner': group.user.username, | |
2403 | } |
|
2407 | } | |
2404 | return data |
|
2408 | return data | |
2405 |
|
2409 | |||
2406 |
|
2410 | |||
2407 | class Permission(Base, BaseModel): |
|
2411 | class Permission(Base, BaseModel): | |
2408 | __tablename__ = 'permissions' |
|
2412 | __tablename__ = 'permissions' | |
2409 | __table_args__ = ( |
|
2413 | __table_args__ = ( | |
2410 | Index('p_perm_name_idx', 'permission_name'), |
|
2414 | Index('p_perm_name_idx', 'permission_name'), | |
2411 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2415 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2412 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
2416 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
2413 | ) |
|
2417 | ) | |
2414 | PERMS = [ |
|
2418 | PERMS = [ | |
2415 | ('hg.admin', _('RhodeCode Super Administrator')), |
|
2419 | ('hg.admin', _('RhodeCode Super Administrator')), | |
2416 |
|
2420 | |||
2417 | ('repository.none', _('Repository no access')), |
|
2421 | ('repository.none', _('Repository no access')), | |
2418 | ('repository.read', _('Repository read access')), |
|
2422 | ('repository.read', _('Repository read access')), | |
2419 | ('repository.write', _('Repository write access')), |
|
2423 | ('repository.write', _('Repository write access')), | |
2420 | ('repository.admin', _('Repository admin access')), |
|
2424 | ('repository.admin', _('Repository admin access')), | |
2421 |
|
2425 | |||
2422 | ('group.none', _('Repository group no access')), |
|
2426 | ('group.none', _('Repository group no access')), | |
2423 | ('group.read', _('Repository group read access')), |
|
2427 | ('group.read', _('Repository group read access')), | |
2424 | ('group.write', _('Repository group write access')), |
|
2428 | ('group.write', _('Repository group write access')), | |
2425 | ('group.admin', _('Repository group admin access')), |
|
2429 | ('group.admin', _('Repository group admin access')), | |
2426 |
|
2430 | |||
2427 | ('usergroup.none', _('User group no access')), |
|
2431 | ('usergroup.none', _('User group no access')), | |
2428 | ('usergroup.read', _('User group read access')), |
|
2432 | ('usergroup.read', _('User group read access')), | |
2429 | ('usergroup.write', _('User group write access')), |
|
2433 | ('usergroup.write', _('User group write access')), | |
2430 | ('usergroup.admin', _('User group admin access')), |
|
2434 | ('usergroup.admin', _('User group admin access')), | |
2431 |
|
2435 | |||
2432 | ('hg.repogroup.create.false', _('Repository Group creation disabled')), |
|
2436 | ('hg.repogroup.create.false', _('Repository Group creation disabled')), | |
2433 | ('hg.repogroup.create.true', _('Repository Group creation enabled')), |
|
2437 | ('hg.repogroup.create.true', _('Repository Group creation enabled')), | |
2434 |
|
2438 | |||
2435 | ('hg.usergroup.create.false', _('User Group creation disabled')), |
|
2439 | ('hg.usergroup.create.false', _('User Group creation disabled')), | |
2436 | ('hg.usergroup.create.true', _('User Group creation enabled')), |
|
2440 | ('hg.usergroup.create.true', _('User Group creation enabled')), | |
2437 |
|
2441 | |||
2438 | ('hg.create.none', _('Repository creation disabled')), |
|
2442 | ('hg.create.none', _('Repository creation disabled')), | |
2439 | ('hg.create.repository', _('Repository creation enabled')), |
|
2443 | ('hg.create.repository', _('Repository creation enabled')), | |
2440 | ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')), |
|
2444 | ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')), | |
2441 | ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')), |
|
2445 | ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')), | |
2442 |
|
2446 | |||
2443 | ('hg.fork.none', _('Repository forking disabled')), |
|
2447 | ('hg.fork.none', _('Repository forking disabled')), | |
2444 | ('hg.fork.repository', _('Repository forking enabled')), |
|
2448 | ('hg.fork.repository', _('Repository forking enabled')), | |
2445 |
|
2449 | |||
2446 | ('hg.register.none', _('Registration disabled')), |
|
2450 | ('hg.register.none', _('Registration disabled')), | |
2447 | ('hg.register.manual_activate', _('User Registration with manual account activation')), |
|
2451 | ('hg.register.manual_activate', _('User Registration with manual account activation')), | |
2448 | ('hg.register.auto_activate', _('User Registration with automatic account activation')), |
|
2452 | ('hg.register.auto_activate', _('User Registration with automatic account activation')), | |
2449 |
|
2453 | |||
2450 | ('hg.password_reset.enabled', _('Password reset enabled')), |
|
2454 | ('hg.password_reset.enabled', _('Password reset enabled')), | |
2451 | ('hg.password_reset.hidden', _('Password reset hidden')), |
|
2455 | ('hg.password_reset.hidden', _('Password reset hidden')), | |
2452 | ('hg.password_reset.disabled', _('Password reset disabled')), |
|
2456 | ('hg.password_reset.disabled', _('Password reset disabled')), | |
2453 |
|
2457 | |||
2454 | ('hg.extern_activate.manual', _('Manual activation of external account')), |
|
2458 | ('hg.extern_activate.manual', _('Manual activation of external account')), | |
2455 | ('hg.extern_activate.auto', _('Automatic activation of external account')), |
|
2459 | ('hg.extern_activate.auto', _('Automatic activation of external account')), | |
2456 |
|
2460 | |||
2457 | ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')), |
|
2461 | ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')), | |
2458 | ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')), |
|
2462 | ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')), | |
2459 | ] |
|
2463 | ] | |
2460 |
|
2464 | |||
2461 | # definition of system default permissions for DEFAULT user |
|
2465 | # definition of system default permissions for DEFAULT user | |
2462 | DEFAULT_USER_PERMISSIONS = [ |
|
2466 | DEFAULT_USER_PERMISSIONS = [ | |
2463 | 'repository.read', |
|
2467 | 'repository.read', | |
2464 | 'group.read', |
|
2468 | 'group.read', | |
2465 | 'usergroup.read', |
|
2469 | 'usergroup.read', | |
2466 | 'hg.create.repository', |
|
2470 | 'hg.create.repository', | |
2467 | 'hg.repogroup.create.false', |
|
2471 | 'hg.repogroup.create.false', | |
2468 | 'hg.usergroup.create.false', |
|
2472 | 'hg.usergroup.create.false', | |
2469 | 'hg.create.write_on_repogroup.true', |
|
2473 | 'hg.create.write_on_repogroup.true', | |
2470 | 'hg.fork.repository', |
|
2474 | 'hg.fork.repository', | |
2471 | 'hg.register.manual_activate', |
|
2475 | 'hg.register.manual_activate', | |
2472 | 'hg.password_reset.enabled', |
|
2476 | 'hg.password_reset.enabled', | |
2473 | 'hg.extern_activate.auto', |
|
2477 | 'hg.extern_activate.auto', | |
2474 | 'hg.inherit_default_perms.true', |
|
2478 | 'hg.inherit_default_perms.true', | |
2475 | ] |
|
2479 | ] | |
2476 |
|
2480 | |||
2477 | # defines which permissions are more important higher the more important |
|
2481 | # defines which permissions are more important higher the more important | |
2478 | # Weight defines which permissions are more important. |
|
2482 | # Weight defines which permissions are more important. | |
2479 | # The higher number the more important. |
|
2483 | # The higher number the more important. | |
2480 | PERM_WEIGHTS = { |
|
2484 | PERM_WEIGHTS = { | |
2481 | 'repository.none': 0, |
|
2485 | 'repository.none': 0, | |
2482 | 'repository.read': 1, |
|
2486 | 'repository.read': 1, | |
2483 | 'repository.write': 3, |
|
2487 | 'repository.write': 3, | |
2484 | 'repository.admin': 4, |
|
2488 | 'repository.admin': 4, | |
2485 |
|
2489 | |||
2486 | 'group.none': 0, |
|
2490 | 'group.none': 0, | |
2487 | 'group.read': 1, |
|
2491 | 'group.read': 1, | |
2488 | 'group.write': 3, |
|
2492 | 'group.write': 3, | |
2489 | 'group.admin': 4, |
|
2493 | 'group.admin': 4, | |
2490 |
|
2494 | |||
2491 | 'usergroup.none': 0, |
|
2495 | 'usergroup.none': 0, | |
2492 | 'usergroup.read': 1, |
|
2496 | 'usergroup.read': 1, | |
2493 | 'usergroup.write': 3, |
|
2497 | 'usergroup.write': 3, | |
2494 | 'usergroup.admin': 4, |
|
2498 | 'usergroup.admin': 4, | |
2495 |
|
2499 | |||
2496 | 'hg.repogroup.create.false': 0, |
|
2500 | 'hg.repogroup.create.false': 0, | |
2497 | 'hg.repogroup.create.true': 1, |
|
2501 | 'hg.repogroup.create.true': 1, | |
2498 |
|
2502 | |||
2499 | 'hg.usergroup.create.false': 0, |
|
2503 | 'hg.usergroup.create.false': 0, | |
2500 | 'hg.usergroup.create.true': 1, |
|
2504 | 'hg.usergroup.create.true': 1, | |
2501 |
|
2505 | |||
2502 | 'hg.fork.none': 0, |
|
2506 | 'hg.fork.none': 0, | |
2503 | 'hg.fork.repository': 1, |
|
2507 | 'hg.fork.repository': 1, | |
2504 | 'hg.create.none': 0, |
|
2508 | 'hg.create.none': 0, | |
2505 | 'hg.create.repository': 1 |
|
2509 | 'hg.create.repository': 1 | |
2506 | } |
|
2510 | } | |
2507 |
|
2511 | |||
2508 | permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2512 | permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2509 | permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None) |
|
2513 | permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None) | |
2510 | permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None) |
|
2514 | permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None) | |
2511 |
|
2515 | |||
2512 | def __unicode__(self): |
|
2516 | def __unicode__(self): | |
2513 | return u"<%s('%s:%s')>" % ( |
|
2517 | return u"<%s('%s:%s')>" % ( | |
2514 | self.__class__.__name__, self.permission_id, self.permission_name |
|
2518 | self.__class__.__name__, self.permission_id, self.permission_name | |
2515 | ) |
|
2519 | ) | |
2516 |
|
2520 | |||
2517 | @classmethod |
|
2521 | @classmethod | |
2518 | def get_by_key(cls, key): |
|
2522 | def get_by_key(cls, key): | |
2519 | return cls.query().filter(cls.permission_name == key).scalar() |
|
2523 | return cls.query().filter(cls.permission_name == key).scalar() | |
2520 |
|
2524 | |||
2521 | @classmethod |
|
2525 | @classmethod | |
2522 | def get_default_repo_perms(cls, user_id, repo_id=None): |
|
2526 | def get_default_repo_perms(cls, user_id, repo_id=None): | |
2523 | q = Session().query(UserRepoToPerm, Repository, Permission)\ |
|
2527 | q = Session().query(UserRepoToPerm, Repository, Permission)\ | |
2524 | .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\ |
|
2528 | .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\ | |
2525 | .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\ |
|
2529 | .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\ | |
2526 | .filter(UserRepoToPerm.user_id == user_id) |
|
2530 | .filter(UserRepoToPerm.user_id == user_id) | |
2527 | if repo_id: |
|
2531 | if repo_id: | |
2528 | q = q.filter(UserRepoToPerm.repository_id == repo_id) |
|
2532 | q = q.filter(UserRepoToPerm.repository_id == repo_id) | |
2529 | return q.all() |
|
2533 | return q.all() | |
2530 |
|
2534 | |||
2531 | @classmethod |
|
2535 | @classmethod | |
2532 | def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None): |
|
2536 | def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None): | |
2533 | q = Session().query(UserGroupRepoToPerm, Repository, Permission)\ |
|
2537 | q = Session().query(UserGroupRepoToPerm, Repository, Permission)\ | |
2534 | .join( |
|
2538 | .join( | |
2535 | Permission, |
|
2539 | Permission, | |
2536 | UserGroupRepoToPerm.permission_id == Permission.permission_id)\ |
|
2540 | UserGroupRepoToPerm.permission_id == Permission.permission_id)\ | |
2537 | .join( |
|
2541 | .join( | |
2538 | Repository, |
|
2542 | Repository, | |
2539 | UserGroupRepoToPerm.repository_id == Repository.repo_id)\ |
|
2543 | UserGroupRepoToPerm.repository_id == Repository.repo_id)\ | |
2540 | .join( |
|
2544 | .join( | |
2541 | UserGroup, |
|
2545 | UserGroup, | |
2542 | UserGroupRepoToPerm.users_group_id == |
|
2546 | UserGroupRepoToPerm.users_group_id == | |
2543 | UserGroup.users_group_id)\ |
|
2547 | UserGroup.users_group_id)\ | |
2544 | .join( |
|
2548 | .join( | |
2545 | UserGroupMember, |
|
2549 | UserGroupMember, | |
2546 | UserGroupRepoToPerm.users_group_id == |
|
2550 | UserGroupRepoToPerm.users_group_id == | |
2547 | UserGroupMember.users_group_id)\ |
|
2551 | UserGroupMember.users_group_id)\ | |
2548 | .filter( |
|
2552 | .filter( | |
2549 | UserGroupMember.user_id == user_id, |
|
2553 | UserGroupMember.user_id == user_id, | |
2550 | UserGroup.users_group_active == true()) |
|
2554 | UserGroup.users_group_active == true()) | |
2551 | if repo_id: |
|
2555 | if repo_id: | |
2552 | q = q.filter(UserGroupRepoToPerm.repository_id == repo_id) |
|
2556 | q = q.filter(UserGroupRepoToPerm.repository_id == repo_id) | |
2553 | return q.all() |
|
2557 | return q.all() | |
2554 |
|
2558 | |||
2555 | @classmethod |
|
2559 | @classmethod | |
2556 | def get_default_group_perms(cls, user_id, repo_group_id=None): |
|
2560 | def get_default_group_perms(cls, user_id, repo_group_id=None): | |
2557 | q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\ |
|
2561 | q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\ | |
2558 | .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\ |
|
2562 | .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\ | |
2559 | .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\ |
|
2563 | .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\ | |
2560 | .filter(UserRepoGroupToPerm.user_id == user_id) |
|
2564 | .filter(UserRepoGroupToPerm.user_id == user_id) | |
2561 | if repo_group_id: |
|
2565 | if repo_group_id: | |
2562 | q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id) |
|
2566 | q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id) | |
2563 | return q.all() |
|
2567 | return q.all() | |
2564 |
|
2568 | |||
2565 | @classmethod |
|
2569 | @classmethod | |
2566 | def get_default_group_perms_from_user_group( |
|
2570 | def get_default_group_perms_from_user_group( | |
2567 | cls, user_id, repo_group_id=None): |
|
2571 | cls, user_id, repo_group_id=None): | |
2568 | q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\ |
|
2572 | q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\ | |
2569 | .join( |
|
2573 | .join( | |
2570 | Permission, |
|
2574 | Permission, | |
2571 | UserGroupRepoGroupToPerm.permission_id == |
|
2575 | UserGroupRepoGroupToPerm.permission_id == | |
2572 | Permission.permission_id)\ |
|
2576 | Permission.permission_id)\ | |
2573 | .join( |
|
2577 | .join( | |
2574 | RepoGroup, |
|
2578 | RepoGroup, | |
2575 | UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\ |
|
2579 | UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\ | |
2576 | .join( |
|
2580 | .join( | |
2577 | UserGroup, |
|
2581 | UserGroup, | |
2578 | UserGroupRepoGroupToPerm.users_group_id == |
|
2582 | UserGroupRepoGroupToPerm.users_group_id == | |
2579 | UserGroup.users_group_id)\ |
|
2583 | UserGroup.users_group_id)\ | |
2580 | .join( |
|
2584 | .join( | |
2581 | UserGroupMember, |
|
2585 | UserGroupMember, | |
2582 | UserGroupRepoGroupToPerm.users_group_id == |
|
2586 | UserGroupRepoGroupToPerm.users_group_id == | |
2583 | UserGroupMember.users_group_id)\ |
|
2587 | UserGroupMember.users_group_id)\ | |
2584 | .filter( |
|
2588 | .filter( | |
2585 | UserGroupMember.user_id == user_id, |
|
2589 | UserGroupMember.user_id == user_id, | |
2586 | UserGroup.users_group_active == true()) |
|
2590 | UserGroup.users_group_active == true()) | |
2587 | if repo_group_id: |
|
2591 | if repo_group_id: | |
2588 | q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id) |
|
2592 | q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id) | |
2589 | return q.all() |
|
2593 | return q.all() | |
2590 |
|
2594 | |||
2591 | @classmethod |
|
2595 | @classmethod | |
2592 | def get_default_user_group_perms(cls, user_id, user_group_id=None): |
|
2596 | def get_default_user_group_perms(cls, user_id, user_group_id=None): | |
2593 | q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\ |
|
2597 | q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\ | |
2594 | .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\ |
|
2598 | .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\ | |
2595 | .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\ |
|
2599 | .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\ | |
2596 | .filter(UserUserGroupToPerm.user_id == user_id) |
|
2600 | .filter(UserUserGroupToPerm.user_id == user_id) | |
2597 | if user_group_id: |
|
2601 | if user_group_id: | |
2598 | q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id) |
|
2602 | q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id) | |
2599 | return q.all() |
|
2603 | return q.all() | |
2600 |
|
2604 | |||
2601 | @classmethod |
|
2605 | @classmethod | |
2602 | def get_default_user_group_perms_from_user_group( |
|
2606 | def get_default_user_group_perms_from_user_group( | |
2603 | cls, user_id, user_group_id=None): |
|
2607 | cls, user_id, user_group_id=None): | |
2604 | TargetUserGroup = aliased(UserGroup, name='target_user_group') |
|
2608 | TargetUserGroup = aliased(UserGroup, name='target_user_group') | |
2605 | q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\ |
|
2609 | q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\ | |
2606 | .join( |
|
2610 | .join( | |
2607 | Permission, |
|
2611 | Permission, | |
2608 | UserGroupUserGroupToPerm.permission_id == |
|
2612 | UserGroupUserGroupToPerm.permission_id == | |
2609 | Permission.permission_id)\ |
|
2613 | Permission.permission_id)\ | |
2610 | .join( |
|
2614 | .join( | |
2611 | TargetUserGroup, |
|
2615 | TargetUserGroup, | |
2612 | UserGroupUserGroupToPerm.target_user_group_id == |
|
2616 | UserGroupUserGroupToPerm.target_user_group_id == | |
2613 | TargetUserGroup.users_group_id)\ |
|
2617 | TargetUserGroup.users_group_id)\ | |
2614 | .join( |
|
2618 | .join( | |
2615 | UserGroup, |
|
2619 | UserGroup, | |
2616 | UserGroupUserGroupToPerm.user_group_id == |
|
2620 | UserGroupUserGroupToPerm.user_group_id == | |
2617 | UserGroup.users_group_id)\ |
|
2621 | UserGroup.users_group_id)\ | |
2618 | .join( |
|
2622 | .join( | |
2619 | UserGroupMember, |
|
2623 | UserGroupMember, | |
2620 | UserGroupUserGroupToPerm.user_group_id == |
|
2624 | UserGroupUserGroupToPerm.user_group_id == | |
2621 | UserGroupMember.users_group_id)\ |
|
2625 | UserGroupMember.users_group_id)\ | |
2622 | .filter( |
|
2626 | .filter( | |
2623 | UserGroupMember.user_id == user_id, |
|
2627 | UserGroupMember.user_id == user_id, | |
2624 | UserGroup.users_group_active == true()) |
|
2628 | UserGroup.users_group_active == true()) | |
2625 | if user_group_id: |
|
2629 | if user_group_id: | |
2626 | q = q.filter( |
|
2630 | q = q.filter( | |
2627 | UserGroupUserGroupToPerm.user_group_id == user_group_id) |
|
2631 | UserGroupUserGroupToPerm.user_group_id == user_group_id) | |
2628 |
|
2632 | |||
2629 | return q.all() |
|
2633 | return q.all() | |
2630 |
|
2634 | |||
2631 |
|
2635 | |||
2632 | class UserRepoToPerm(Base, BaseModel): |
|
2636 | class UserRepoToPerm(Base, BaseModel): | |
2633 | __tablename__ = 'repo_to_perm' |
|
2637 | __tablename__ = 'repo_to_perm' | |
2634 | __table_args__ = ( |
|
2638 | __table_args__ = ( | |
2635 | UniqueConstraint('user_id', 'repository_id', 'permission_id'), |
|
2639 | UniqueConstraint('user_id', 'repository_id', 'permission_id'), | |
2636 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2640 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2637 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2641 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2638 | ) |
|
2642 | ) | |
2639 | repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2643 | repo_to_perm_id = Column("repo_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) |
|
2644 | 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) |
|
2645 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) | |
2642 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None) |
|
2646 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None) | |
2643 |
|
2647 | |||
2644 | user = relationship('User') |
|
2648 | user = relationship('User') | |
2645 | repository = relationship('Repository') |
|
2649 | repository = relationship('Repository') | |
2646 | permission = relationship('Permission') |
|
2650 | permission = relationship('Permission') | |
2647 |
|
2651 | |||
2648 | @classmethod |
|
2652 | @classmethod | |
2649 | def create(cls, user, repository, permission): |
|
2653 | def create(cls, user, repository, permission): | |
2650 | n = cls() |
|
2654 | n = cls() | |
2651 | n.user = user |
|
2655 | n.user = user | |
2652 | n.repository = repository |
|
2656 | n.repository = repository | |
2653 | n.permission = permission |
|
2657 | n.permission = permission | |
2654 | Session().add(n) |
|
2658 | Session().add(n) | |
2655 | return n |
|
2659 | return n | |
2656 |
|
2660 | |||
2657 | def __unicode__(self): |
|
2661 | def __unicode__(self): | |
2658 | return u'<%s => %s >' % (self.user, self.repository) |
|
2662 | return u'<%s => %s >' % (self.user, self.repository) | |
2659 |
|
2663 | |||
2660 |
|
2664 | |||
2661 | class UserUserGroupToPerm(Base, BaseModel): |
|
2665 | class UserUserGroupToPerm(Base, BaseModel): | |
2662 | __tablename__ = 'user_user_group_to_perm' |
|
2666 | __tablename__ = 'user_user_group_to_perm' | |
2663 | __table_args__ = ( |
|
2667 | __table_args__ = ( | |
2664 | UniqueConstraint('user_id', 'user_group_id', 'permission_id'), |
|
2668 | UniqueConstraint('user_id', 'user_group_id', 'permission_id'), | |
2665 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2669 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2666 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2670 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2667 | ) |
|
2671 | ) | |
2668 | user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2672 | user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2669 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
2673 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) | |
2670 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2674 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) | |
2671 | user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2675 | user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) | |
2672 |
|
2676 | |||
2673 | user = relationship('User') |
|
2677 | user = relationship('User') | |
2674 | user_group = relationship('UserGroup') |
|
2678 | user_group = relationship('UserGroup') | |
2675 | permission = relationship('Permission') |
|
2679 | permission = relationship('Permission') | |
2676 |
|
2680 | |||
2677 | @classmethod |
|
2681 | @classmethod | |
2678 | def create(cls, user, user_group, permission): |
|
2682 | def create(cls, user, user_group, permission): | |
2679 | n = cls() |
|
2683 | n = cls() | |
2680 | n.user = user |
|
2684 | n.user = user | |
2681 | n.user_group = user_group |
|
2685 | n.user_group = user_group | |
2682 | n.permission = permission |
|
2686 | n.permission = permission | |
2683 | Session().add(n) |
|
2687 | Session().add(n) | |
2684 | return n |
|
2688 | return n | |
2685 |
|
2689 | |||
2686 | def __unicode__(self): |
|
2690 | def __unicode__(self): | |
2687 | return u'<%s => %s >' % (self.user, self.user_group) |
|
2691 | return u'<%s => %s >' % (self.user, self.user_group) | |
2688 |
|
2692 | |||
2689 |
|
2693 | |||
2690 | class UserToPerm(Base, BaseModel): |
|
2694 | class UserToPerm(Base, BaseModel): | |
2691 | __tablename__ = 'user_to_perm' |
|
2695 | __tablename__ = 'user_to_perm' | |
2692 | __table_args__ = ( |
|
2696 | __table_args__ = ( | |
2693 | UniqueConstraint('user_id', 'permission_id'), |
|
2697 | UniqueConstraint('user_id', 'permission_id'), | |
2694 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2698 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2695 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2699 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2696 | ) |
|
2700 | ) | |
2697 | user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2701 | user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2698 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
2702 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) | |
2699 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2703 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) | |
2700 |
|
2704 | |||
2701 | user = relationship('User') |
|
2705 | user = relationship('User') | |
2702 | permission = relationship('Permission', lazy='joined') |
|
2706 | permission = relationship('Permission', lazy='joined') | |
2703 |
|
2707 | |||
2704 | def __unicode__(self): |
|
2708 | def __unicode__(self): | |
2705 | return u'<%s => %s >' % (self.user, self.permission) |
|
2709 | return u'<%s => %s >' % (self.user, self.permission) | |
2706 |
|
2710 | |||
2707 |
|
2711 | |||
2708 | class UserGroupRepoToPerm(Base, BaseModel): |
|
2712 | class UserGroupRepoToPerm(Base, BaseModel): | |
2709 | __tablename__ = 'users_group_repo_to_perm' |
|
2713 | __tablename__ = 'users_group_repo_to_perm' | |
2710 | __table_args__ = ( |
|
2714 | __table_args__ = ( | |
2711 | UniqueConstraint('repository_id', 'users_group_id', 'permission_id'), |
|
2715 | UniqueConstraint('repository_id', 'users_group_id', 'permission_id'), | |
2712 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2716 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2713 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2717 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2714 | ) |
|
2718 | ) | |
2715 | users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2719 | users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2716 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2720 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) | |
2717 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2721 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) | |
2718 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None) |
|
2722 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None) | |
2719 |
|
2723 | |||
2720 | users_group = relationship('UserGroup') |
|
2724 | users_group = relationship('UserGroup') | |
2721 | permission = relationship('Permission') |
|
2725 | permission = relationship('Permission') | |
2722 | repository = relationship('Repository') |
|
2726 | repository = relationship('Repository') | |
2723 |
|
2727 | |||
2724 | @classmethod |
|
2728 | @classmethod | |
2725 | def create(cls, users_group, repository, permission): |
|
2729 | def create(cls, users_group, repository, permission): | |
2726 | n = cls() |
|
2730 | n = cls() | |
2727 | n.users_group = users_group |
|
2731 | n.users_group = users_group | |
2728 | n.repository = repository |
|
2732 | n.repository = repository | |
2729 | n.permission = permission |
|
2733 | n.permission = permission | |
2730 | Session().add(n) |
|
2734 | Session().add(n) | |
2731 | return n |
|
2735 | return n | |
2732 |
|
2736 | |||
2733 | def __unicode__(self): |
|
2737 | def __unicode__(self): | |
2734 | return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository) |
|
2738 | return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository) | |
2735 |
|
2739 | |||
2736 |
|
2740 | |||
2737 | class UserGroupUserGroupToPerm(Base, BaseModel): |
|
2741 | class UserGroupUserGroupToPerm(Base, BaseModel): | |
2738 | __tablename__ = 'user_group_user_group_to_perm' |
|
2742 | __tablename__ = 'user_group_user_group_to_perm' | |
2739 | __table_args__ = ( |
|
2743 | __table_args__ = ( | |
2740 | UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'), |
|
2744 | UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'), | |
2741 | CheckConstraint('target_user_group_id != user_group_id'), |
|
2745 | CheckConstraint('target_user_group_id != user_group_id'), | |
2742 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2746 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2743 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2747 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2744 | ) |
|
2748 | ) | |
2745 | 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) |
|
2749 | 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) | |
2746 | target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2750 | target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) | |
2747 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2751 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) | |
2748 | user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2752 | user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) | |
2749 |
|
2753 | |||
2750 | target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id') |
|
2754 | target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id') | |
2751 | user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id') |
|
2755 | user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id') | |
2752 | permission = relationship('Permission') |
|
2756 | permission = relationship('Permission') | |
2753 |
|
2757 | |||
2754 | @classmethod |
|
2758 | @classmethod | |
2755 | def create(cls, target_user_group, user_group, permission): |
|
2759 | def create(cls, target_user_group, user_group, permission): | |
2756 | n = cls() |
|
2760 | n = cls() | |
2757 | n.target_user_group = target_user_group |
|
2761 | n.target_user_group = target_user_group | |
2758 | n.user_group = user_group |
|
2762 | n.user_group = user_group | |
2759 | n.permission = permission |
|
2763 | n.permission = permission | |
2760 | Session().add(n) |
|
2764 | Session().add(n) | |
2761 | return n |
|
2765 | return n | |
2762 |
|
2766 | |||
2763 | def __unicode__(self): |
|
2767 | def __unicode__(self): | |
2764 | return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group) |
|
2768 | return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group) | |
2765 |
|
2769 | |||
2766 |
|
2770 | |||
2767 | class UserGroupToPerm(Base, BaseModel): |
|
2771 | class UserGroupToPerm(Base, BaseModel): | |
2768 | __tablename__ = 'users_group_to_perm' |
|
2772 | __tablename__ = 'users_group_to_perm' | |
2769 | __table_args__ = ( |
|
2773 | __table_args__ = ( | |
2770 | UniqueConstraint('users_group_id', 'permission_id',), |
|
2774 | UniqueConstraint('users_group_id', 'permission_id',), | |
2771 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2775 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2772 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2776 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2773 | ) |
|
2777 | ) | |
2774 | users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2778 | users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2775 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2779 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) | |
2776 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2780 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) | |
2777 |
|
2781 | |||
2778 | users_group = relationship('UserGroup') |
|
2782 | users_group = relationship('UserGroup') | |
2779 | permission = relationship('Permission') |
|
2783 | permission = relationship('Permission') | |
2780 |
|
2784 | |||
2781 |
|
2785 | |||
2782 | class UserRepoGroupToPerm(Base, BaseModel): |
|
2786 | class UserRepoGroupToPerm(Base, BaseModel): | |
2783 | __tablename__ = 'user_repo_group_to_perm' |
|
2787 | __tablename__ = 'user_repo_group_to_perm' | |
2784 | __table_args__ = ( |
|
2788 | __table_args__ = ( | |
2785 | UniqueConstraint('user_id', 'group_id', 'permission_id'), |
|
2789 | UniqueConstraint('user_id', 'group_id', 'permission_id'), | |
2786 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2790 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2787 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2791 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2788 | ) |
|
2792 | ) | |
2789 |
|
2793 | |||
2790 | group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2794 | group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2791 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
2795 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) | |
2792 | group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None) |
|
2796 | group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None) | |
2793 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2797 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) | |
2794 |
|
2798 | |||
2795 | user = relationship('User') |
|
2799 | user = relationship('User') | |
2796 | group = relationship('RepoGroup') |
|
2800 | group = relationship('RepoGroup') | |
2797 | permission = relationship('Permission') |
|
2801 | permission = relationship('Permission') | |
2798 |
|
2802 | |||
2799 | @classmethod |
|
2803 | @classmethod | |
2800 | def create(cls, user, repository_group, permission): |
|
2804 | def create(cls, user, repository_group, permission): | |
2801 | n = cls() |
|
2805 | n = cls() | |
2802 | n.user = user |
|
2806 | n.user = user | |
2803 | n.group = repository_group |
|
2807 | n.group = repository_group | |
2804 | n.permission = permission |
|
2808 | n.permission = permission | |
2805 | Session().add(n) |
|
2809 | Session().add(n) | |
2806 | return n |
|
2810 | return n | |
2807 |
|
2811 | |||
2808 |
|
2812 | |||
2809 | class UserGroupRepoGroupToPerm(Base, BaseModel): |
|
2813 | class UserGroupRepoGroupToPerm(Base, BaseModel): | |
2810 | __tablename__ = 'users_group_repo_group_to_perm' |
|
2814 | __tablename__ = 'users_group_repo_group_to_perm' | |
2811 | __table_args__ = ( |
|
2815 | __table_args__ = ( | |
2812 | UniqueConstraint('users_group_id', 'group_id'), |
|
2816 | UniqueConstraint('users_group_id', 'group_id'), | |
2813 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2817 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2814 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2818 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2815 | ) |
|
2819 | ) | |
2816 |
|
2820 | |||
2817 | 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) |
|
2821 | 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) | |
2818 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) |
|
2822 | users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None) | |
2819 | group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None) |
|
2823 | group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None) | |
2820 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) |
|
2824 | permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None) | |
2821 |
|
2825 | |||
2822 | users_group = relationship('UserGroup') |
|
2826 | users_group = relationship('UserGroup') | |
2823 | permission = relationship('Permission') |
|
2827 | permission = relationship('Permission') | |
2824 | group = relationship('RepoGroup') |
|
2828 | group = relationship('RepoGroup') | |
2825 |
|
2829 | |||
2826 | @classmethod |
|
2830 | @classmethod | |
2827 | def create(cls, user_group, repository_group, permission): |
|
2831 | def create(cls, user_group, repository_group, permission): | |
2828 | n = cls() |
|
2832 | n = cls() | |
2829 | n.users_group = user_group |
|
2833 | n.users_group = user_group | |
2830 | n.group = repository_group |
|
2834 | n.group = repository_group | |
2831 | n.permission = permission |
|
2835 | n.permission = permission | |
2832 | Session().add(n) |
|
2836 | Session().add(n) | |
2833 | return n |
|
2837 | return n | |
2834 |
|
2838 | |||
2835 | def __unicode__(self): |
|
2839 | def __unicode__(self): | |
2836 | return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group) |
|
2840 | return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group) | |
2837 |
|
2841 | |||
2838 |
|
2842 | |||
2839 | class Statistics(Base, BaseModel): |
|
2843 | class Statistics(Base, BaseModel): | |
2840 | __tablename__ = 'statistics' |
|
2844 | __tablename__ = 'statistics' | |
2841 | __table_args__ = ( |
|
2845 | __table_args__ = ( | |
2842 | UniqueConstraint('repository_id'), |
|
2846 | UniqueConstraint('repository_id'), | |
2843 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2847 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2844 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2848 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2845 | ) |
|
2849 | ) | |
2846 | stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2850 | stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2847 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None) |
|
2851 | repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None) | |
2848 | stat_on_revision = Column("stat_on_revision", Integer(), nullable=False) |
|
2852 | stat_on_revision = Column("stat_on_revision", Integer(), nullable=False) | |
2849 | commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data |
|
2853 | commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data | |
2850 | commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data |
|
2854 | commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data | |
2851 | languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data |
|
2855 | languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data | |
2852 |
|
2856 | |||
2853 | repository = relationship('Repository', single_parent=True) |
|
2857 | repository = relationship('Repository', single_parent=True) | |
2854 |
|
2858 | |||
2855 |
|
2859 | |||
2856 | class UserFollowing(Base, BaseModel): |
|
2860 | class UserFollowing(Base, BaseModel): | |
2857 | __tablename__ = 'user_followings' |
|
2861 | __tablename__ = 'user_followings' | |
2858 | __table_args__ = ( |
|
2862 | __table_args__ = ( | |
2859 | UniqueConstraint('user_id', 'follows_repository_id'), |
|
2863 | UniqueConstraint('user_id', 'follows_repository_id'), | |
2860 | UniqueConstraint('user_id', 'follows_user_id'), |
|
2864 | UniqueConstraint('user_id', 'follows_user_id'), | |
2861 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2865 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2862 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
2866 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
2863 | ) |
|
2867 | ) | |
2864 |
|
2868 | |||
2865 | user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2869 | user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2866 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) |
|
2870 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None) | |
2867 | follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None) |
|
2871 | follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None) | |
2868 | follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) |
|
2872 | follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None) | |
2869 | follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now) |
|
2873 | follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now) | |
2870 |
|
2874 | |||
2871 | user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id') |
|
2875 | user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id') | |
2872 |
|
2876 | |||
2873 | follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id') |
|
2877 | follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id') | |
2874 | follows_repository = relationship('Repository', order_by='Repository.repo_name') |
|
2878 | follows_repository = relationship('Repository', order_by='Repository.repo_name') | |
2875 |
|
2879 | |||
2876 | @classmethod |
|
2880 | @classmethod | |
2877 | def get_repo_followers(cls, repo_id): |
|
2881 | def get_repo_followers(cls, repo_id): | |
2878 | return cls.query().filter(cls.follows_repo_id == repo_id) |
|
2882 | return cls.query().filter(cls.follows_repo_id == repo_id) | |
2879 |
|
2883 | |||
2880 |
|
2884 | |||
2881 | class CacheKey(Base, BaseModel): |
|
2885 | class CacheKey(Base, BaseModel): | |
2882 | __tablename__ = 'cache_invalidation' |
|
2886 | __tablename__ = 'cache_invalidation' | |
2883 | __table_args__ = ( |
|
2887 | __table_args__ = ( | |
2884 | UniqueConstraint('cache_key'), |
|
2888 | UniqueConstraint('cache_key'), | |
2885 | Index('key_idx', 'cache_key'), |
|
2889 | Index('key_idx', 'cache_key'), | |
2886 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
2890 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
2887 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
2891 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
2888 | ) |
|
2892 | ) | |
2889 | CACHE_TYPE_ATOM = 'ATOM' |
|
2893 | CACHE_TYPE_ATOM = 'ATOM' | |
2890 | CACHE_TYPE_RSS = 'RSS' |
|
2894 | CACHE_TYPE_RSS = 'RSS' | |
2891 | CACHE_TYPE_README = 'README' |
|
2895 | CACHE_TYPE_README = 'README' | |
2892 |
|
2896 | |||
2893 | cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) |
|
2897 | cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True) | |
2894 | cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None) |
|
2898 | cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None) | |
2895 | cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None) |
|
2899 | cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None) | |
2896 | cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False) |
|
2900 | cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False) | |
2897 |
|
2901 | |||
2898 | def __init__(self, cache_key, cache_args=''): |
|
2902 | def __init__(self, cache_key, cache_args=''): | |
2899 | self.cache_key = cache_key |
|
2903 | self.cache_key = cache_key | |
2900 | self.cache_args = cache_args |
|
2904 | self.cache_args = cache_args | |
2901 | self.cache_active = False |
|
2905 | self.cache_active = False | |
2902 |
|
2906 | |||
2903 | def __unicode__(self): |
|
2907 | def __unicode__(self): | |
2904 | return u"<%s('%s:%s[%s]')>" % ( |
|
2908 | return u"<%s('%s:%s[%s]')>" % ( | |
2905 | self.__class__.__name__, |
|
2909 | self.__class__.__name__, | |
2906 | self.cache_id, self.cache_key, self.cache_active) |
|
2910 | self.cache_id, self.cache_key, self.cache_active) | |
2907 |
|
2911 | |||
2908 | def _cache_key_partition(self): |
|
2912 | def _cache_key_partition(self): | |
2909 | prefix, repo_name, suffix = self.cache_key.partition(self.cache_args) |
|
2913 | prefix, repo_name, suffix = self.cache_key.partition(self.cache_args) | |
2910 | return prefix, repo_name, suffix |
|
2914 | return prefix, repo_name, suffix | |
2911 |
|
2915 | |||
2912 | def get_prefix(self): |
|
2916 | def get_prefix(self): | |
2913 | """ |
|
2917 | """ | |
2914 | Try to extract prefix from existing cache key. The key could consist |
|
2918 | Try to extract prefix from existing cache key. The key could consist | |
2915 | of prefix, repo_name, suffix |
|
2919 | of prefix, repo_name, suffix | |
2916 | """ |
|
2920 | """ | |
2917 | # this returns prefix, repo_name, suffix |
|
2921 | # this returns prefix, repo_name, suffix | |
2918 | return self._cache_key_partition()[0] |
|
2922 | return self._cache_key_partition()[0] | |
2919 |
|
2923 | |||
2920 | def get_suffix(self): |
|
2924 | def get_suffix(self): | |
2921 | """ |
|
2925 | """ | |
2922 | get suffix that might have been used in _get_cache_key to |
|
2926 | get suffix that might have been used in _get_cache_key to | |
2923 | generate self.cache_key. Only used for informational purposes |
|
2927 | generate self.cache_key. Only used for informational purposes | |
2924 | in repo_edit.mako. |
|
2928 | in repo_edit.mako. | |
2925 | """ |
|
2929 | """ | |
2926 | # prefix, repo_name, suffix |
|
2930 | # prefix, repo_name, suffix | |
2927 | return self._cache_key_partition()[2] |
|
2931 | return self._cache_key_partition()[2] | |
2928 |
|
2932 | |||
2929 | @classmethod |
|
2933 | @classmethod | |
2930 | def delete_all_cache(cls): |
|
2934 | def delete_all_cache(cls): | |
2931 | """ |
|
2935 | """ | |
2932 | Delete all cache keys from database. |
|
2936 | Delete all cache keys from database. | |
2933 | Should only be run when all instances are down and all entries |
|
2937 | Should only be run when all instances are down and all entries | |
2934 | thus stale. |
|
2938 | thus stale. | |
2935 | """ |
|
2939 | """ | |
2936 | cls.query().delete() |
|
2940 | cls.query().delete() | |
2937 | Session().commit() |
|
2941 | Session().commit() | |
2938 |
|
2942 | |||
2939 | @classmethod |
|
2943 | @classmethod | |
2940 | def get_cache_key(cls, repo_name, cache_type): |
|
2944 | def get_cache_key(cls, repo_name, cache_type): | |
2941 | """ |
|
2945 | """ | |
2942 |
|
2946 | |||
2943 | Generate a cache key for this process of RhodeCode instance. |
|
2947 | Generate a cache key for this process of RhodeCode instance. | |
2944 | Prefix most likely will be process id or maybe explicitly set |
|
2948 | Prefix most likely will be process id or maybe explicitly set | |
2945 | instance_id from .ini file. |
|
2949 | instance_id from .ini file. | |
2946 | """ |
|
2950 | """ | |
2947 | import rhodecode |
|
2951 | import rhodecode | |
2948 | prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '') |
|
2952 | prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '') | |
2949 |
|
2953 | |||
2950 | repo_as_unicode = safe_unicode(repo_name) |
|
2954 | repo_as_unicode = safe_unicode(repo_name) | |
2951 | key = u'{}_{}'.format(repo_as_unicode, cache_type) \ |
|
2955 | key = u'{}_{}'.format(repo_as_unicode, cache_type) \ | |
2952 | if cache_type else repo_as_unicode |
|
2956 | if cache_type else repo_as_unicode | |
2953 |
|
2957 | |||
2954 | return u'{}{}'.format(prefix, key) |
|
2958 | return u'{}{}'.format(prefix, key) | |
2955 |
|
2959 | |||
2956 | @classmethod |
|
2960 | @classmethod | |
2957 | def set_invalidate(cls, repo_name, delete=False): |
|
2961 | def set_invalidate(cls, repo_name, delete=False): | |
2958 | """ |
|
2962 | """ | |
2959 | Mark all caches of a repo as invalid in the database. |
|
2963 | Mark all caches of a repo as invalid in the database. | |
2960 | """ |
|
2964 | """ | |
2961 |
|
2965 | |||
2962 | try: |
|
2966 | try: | |
2963 | qry = Session().query(cls).filter(cls.cache_args == repo_name) |
|
2967 | qry = Session().query(cls).filter(cls.cache_args == repo_name) | |
2964 | if delete: |
|
2968 | if delete: | |
2965 | log.debug('cache objects deleted for repo %s', |
|
2969 | log.debug('cache objects deleted for repo %s', | |
2966 | safe_str(repo_name)) |
|
2970 | safe_str(repo_name)) | |
2967 | qry.delete() |
|
2971 | qry.delete() | |
2968 | else: |
|
2972 | else: | |
2969 | log.debug('cache objects marked as invalid for repo %s', |
|
2973 | log.debug('cache objects marked as invalid for repo %s', | |
2970 | safe_str(repo_name)) |
|
2974 | safe_str(repo_name)) | |
2971 | qry.update({"cache_active": False}) |
|
2975 | qry.update({"cache_active": False}) | |
2972 |
|
2976 | |||
2973 | Session().commit() |
|
2977 | Session().commit() | |
2974 | except Exception: |
|
2978 | except Exception: | |
2975 | log.exception( |
|
2979 | log.exception( | |
2976 | 'Cache key invalidation failed for repository %s', |
|
2980 | 'Cache key invalidation failed for repository %s', | |
2977 | safe_str(repo_name)) |
|
2981 | safe_str(repo_name)) | |
2978 | Session().rollback() |
|
2982 | Session().rollback() | |
2979 |
|
2983 | |||
2980 | @classmethod |
|
2984 | @classmethod | |
2981 | def get_active_cache(cls, cache_key): |
|
2985 | def get_active_cache(cls, cache_key): | |
2982 | inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar() |
|
2986 | inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar() | |
2983 | if inv_obj: |
|
2987 | if inv_obj: | |
2984 | return inv_obj |
|
2988 | return inv_obj | |
2985 | return None |
|
2989 | return None | |
2986 |
|
2990 | |||
2987 | @classmethod |
|
2991 | @classmethod | |
2988 | def repo_context_cache(cls, compute_func, repo_name, cache_type, |
|
2992 | def repo_context_cache(cls, compute_func, repo_name, cache_type, | |
2989 | thread_scoped=False): |
|
2993 | thread_scoped=False): | |
2990 | """ |
|
2994 | """ | |
2991 | @cache_region('long_term') |
|
2995 | @cache_region('long_term') | |
2992 | def _heavy_calculation(cache_key): |
|
2996 | def _heavy_calculation(cache_key): | |
2993 | return 'result' |
|
2997 | return 'result' | |
2994 |
|
2998 | |||
2995 | cache_context = CacheKey.repo_context_cache( |
|
2999 | cache_context = CacheKey.repo_context_cache( | |
2996 | _heavy_calculation, repo_name, cache_type) |
|
3000 | _heavy_calculation, repo_name, cache_type) | |
2997 |
|
3001 | |||
2998 | with cache_context as context: |
|
3002 | with cache_context as context: | |
2999 | context.invalidate() |
|
3003 | context.invalidate() | |
3000 | computed = context.compute() |
|
3004 | computed = context.compute() | |
3001 |
|
3005 | |||
3002 | assert computed == 'result' |
|
3006 | assert computed == 'result' | |
3003 | """ |
|
3007 | """ | |
3004 | from rhodecode.lib import caches |
|
3008 | from rhodecode.lib import caches | |
3005 | return caches.InvalidationContext( |
|
3009 | return caches.InvalidationContext( | |
3006 | compute_func, repo_name, cache_type, thread_scoped=thread_scoped) |
|
3010 | compute_func, repo_name, cache_type, thread_scoped=thread_scoped) | |
3007 |
|
3011 | |||
3008 |
|
3012 | |||
3009 | class ChangesetComment(Base, BaseModel): |
|
3013 | class ChangesetComment(Base, BaseModel): | |
3010 | __tablename__ = 'changeset_comments' |
|
3014 | __tablename__ = 'changeset_comments' | |
3011 | __table_args__ = ( |
|
3015 | __table_args__ = ( | |
3012 | Index('cc_revision_idx', 'revision'), |
|
3016 | Index('cc_revision_idx', 'revision'), | |
3013 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3017 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3014 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3018 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
3015 | ) |
|
3019 | ) | |
3016 |
|
3020 | |||
3017 | COMMENT_OUTDATED = u'comment_outdated' |
|
3021 | COMMENT_OUTDATED = u'comment_outdated' | |
3018 | COMMENT_TYPE_NOTE = u'note' |
|
3022 | COMMENT_TYPE_NOTE = u'note' | |
3019 | COMMENT_TYPE_TODO = u'todo' |
|
3023 | COMMENT_TYPE_TODO = u'todo' | |
3020 | COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO] |
|
3024 | COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO] | |
3021 |
|
3025 | |||
3022 | comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True) |
|
3026 | comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True) | |
3023 | repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False) |
|
3027 | repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False) | |
3024 | revision = Column('revision', String(40), nullable=True) |
|
3028 | revision = Column('revision', String(40), nullable=True) | |
3025 | pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True) |
|
3029 | pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True) | |
3026 | pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True) |
|
3030 | pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True) | |
3027 | line_no = Column('line_no', Unicode(10), nullable=True) |
|
3031 | line_no = Column('line_no', Unicode(10), nullable=True) | |
3028 | hl_lines = Column('hl_lines', Unicode(512), nullable=True) |
|
3032 | hl_lines = Column('hl_lines', Unicode(512), nullable=True) | |
3029 | f_path = Column('f_path', Unicode(1000), nullable=True) |
|
3033 | f_path = Column('f_path', Unicode(1000), nullable=True) | |
3030 | user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False) |
|
3034 | user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False) | |
3031 | text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False) |
|
3035 | text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False) | |
3032 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3036 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
3033 | modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3037 | modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
3034 | renderer = Column('renderer', Unicode(64), nullable=True) |
|
3038 | renderer = Column('renderer', Unicode(64), nullable=True) | |
3035 | display_state = Column('display_state', Unicode(128), nullable=True) |
|
3039 | display_state = Column('display_state', Unicode(128), nullable=True) | |
3036 |
|
3040 | |||
3037 | comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE) |
|
3041 | comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE) | |
3038 | resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True) |
|
3042 | resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True) | |
3039 | resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by') |
|
3043 | resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by') | |
3040 | author = relationship('User', lazy='joined') |
|
3044 | author = relationship('User', lazy='joined') | |
3041 | repo = relationship('Repository') |
|
3045 | repo = relationship('Repository') | |
3042 | status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined') |
|
3046 | status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined') | |
3043 | pull_request = relationship('PullRequest', lazy='joined') |
|
3047 | pull_request = relationship('PullRequest', lazy='joined') | |
3044 | pull_request_version = relationship('PullRequestVersion') |
|
3048 | pull_request_version = relationship('PullRequestVersion') | |
3045 |
|
3049 | |||
3046 | @classmethod |
|
3050 | @classmethod | |
3047 | def get_users(cls, revision=None, pull_request_id=None): |
|
3051 | def get_users(cls, revision=None, pull_request_id=None): | |
3048 | """ |
|
3052 | """ | |
3049 | Returns user associated with this ChangesetComment. ie those |
|
3053 | Returns user associated with this ChangesetComment. ie those | |
3050 | who actually commented |
|
3054 | who actually commented | |
3051 |
|
3055 | |||
3052 | :param cls: |
|
3056 | :param cls: | |
3053 | :param revision: |
|
3057 | :param revision: | |
3054 | """ |
|
3058 | """ | |
3055 | q = Session().query(User)\ |
|
3059 | q = Session().query(User)\ | |
3056 | .join(ChangesetComment.author) |
|
3060 | .join(ChangesetComment.author) | |
3057 | if revision: |
|
3061 | if revision: | |
3058 | q = q.filter(cls.revision == revision) |
|
3062 | q = q.filter(cls.revision == revision) | |
3059 | elif pull_request_id: |
|
3063 | elif pull_request_id: | |
3060 | q = q.filter(cls.pull_request_id == pull_request_id) |
|
3064 | q = q.filter(cls.pull_request_id == pull_request_id) | |
3061 | return q.all() |
|
3065 | return q.all() | |
3062 |
|
3066 | |||
3063 | @classmethod |
|
3067 | @classmethod | |
3064 | def get_index_from_version(cls, pr_version, versions): |
|
3068 | def get_index_from_version(cls, pr_version, versions): | |
3065 | num_versions = [x.pull_request_version_id for x in versions] |
|
3069 | num_versions = [x.pull_request_version_id for x in versions] | |
3066 | try: |
|
3070 | try: | |
3067 | return num_versions.index(pr_version) +1 |
|
3071 | return num_versions.index(pr_version) +1 | |
3068 | except (IndexError, ValueError): |
|
3072 | except (IndexError, ValueError): | |
3069 | return |
|
3073 | return | |
3070 |
|
3074 | |||
3071 | @property |
|
3075 | @property | |
3072 | def outdated(self): |
|
3076 | def outdated(self): | |
3073 | return self.display_state == self.COMMENT_OUTDATED |
|
3077 | return self.display_state == self.COMMENT_OUTDATED | |
3074 |
|
3078 | |||
3075 | def outdated_at_version(self, version): |
|
3079 | def outdated_at_version(self, version): | |
3076 | """ |
|
3080 | """ | |
3077 | Checks if comment is outdated for given pull request version |
|
3081 | Checks if comment is outdated for given pull request version | |
3078 | """ |
|
3082 | """ | |
3079 | return self.outdated and self.pull_request_version_id != version |
|
3083 | return self.outdated and self.pull_request_version_id != version | |
3080 |
|
3084 | |||
3081 | def older_than_version(self, version): |
|
3085 | def older_than_version(self, version): | |
3082 | """ |
|
3086 | """ | |
3083 | Checks if comment is made from previous version than given |
|
3087 | Checks if comment is made from previous version than given | |
3084 | """ |
|
3088 | """ | |
3085 | if version is None: |
|
3089 | if version is None: | |
3086 | return self.pull_request_version_id is not None |
|
3090 | return self.pull_request_version_id is not None | |
3087 |
|
3091 | |||
3088 | return self.pull_request_version_id < version |
|
3092 | return self.pull_request_version_id < version | |
3089 |
|
3093 | |||
3090 | @property |
|
3094 | @property | |
3091 | def resolved(self): |
|
3095 | def resolved(self): | |
3092 | return self.resolved_by[0] if self.resolved_by else None |
|
3096 | return self.resolved_by[0] if self.resolved_by else None | |
3093 |
|
3097 | |||
3094 | @property |
|
3098 | @property | |
3095 | def is_todo(self): |
|
3099 | def is_todo(self): | |
3096 | return self.comment_type == self.COMMENT_TYPE_TODO |
|
3100 | return self.comment_type == self.COMMENT_TYPE_TODO | |
3097 |
|
3101 | |||
3098 | def get_index_version(self, versions): |
|
3102 | def get_index_version(self, versions): | |
3099 | return self.get_index_from_version( |
|
3103 | return self.get_index_from_version( | |
3100 | self.pull_request_version_id, versions) |
|
3104 | self.pull_request_version_id, versions) | |
3101 |
|
3105 | |||
3102 | def __repr__(self): |
|
3106 | def __repr__(self): | |
3103 | if self.comment_id: |
|
3107 | if self.comment_id: | |
3104 | return '<DB:Comment #%s>' % self.comment_id |
|
3108 | return '<DB:Comment #%s>' % self.comment_id | |
3105 | else: |
|
3109 | else: | |
3106 | return '<DB:Comment at %#x>' % id(self) |
|
3110 | return '<DB:Comment at %#x>' % id(self) | |
3107 |
|
3111 | |||
3108 |
|
3112 | |||
3109 | class ChangesetStatus(Base, BaseModel): |
|
3113 | class ChangesetStatus(Base, BaseModel): | |
3110 | __tablename__ = 'changeset_statuses' |
|
3114 | __tablename__ = 'changeset_statuses' | |
3111 | __table_args__ = ( |
|
3115 | __table_args__ = ( | |
3112 | Index('cs_revision_idx', 'revision'), |
|
3116 | Index('cs_revision_idx', 'revision'), | |
3113 | Index('cs_version_idx', 'version'), |
|
3117 | Index('cs_version_idx', 'version'), | |
3114 | UniqueConstraint('repo_id', 'revision', 'version'), |
|
3118 | UniqueConstraint('repo_id', 'revision', 'version'), | |
3115 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3119 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3116 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
3120 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
3117 | ) |
|
3121 | ) | |
3118 | STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed' |
|
3122 | STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed' | |
3119 | STATUS_APPROVED = 'approved' |
|
3123 | STATUS_APPROVED = 'approved' | |
3120 | STATUS_REJECTED = 'rejected' |
|
3124 | STATUS_REJECTED = 'rejected' | |
3121 | STATUS_UNDER_REVIEW = 'under_review' |
|
3125 | STATUS_UNDER_REVIEW = 'under_review' | |
3122 |
|
3126 | |||
3123 | STATUSES = [ |
|
3127 | STATUSES = [ | |
3124 | (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default |
|
3128 | (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default | |
3125 | (STATUS_APPROVED, _("Approved")), |
|
3129 | (STATUS_APPROVED, _("Approved")), | |
3126 | (STATUS_REJECTED, _("Rejected")), |
|
3130 | (STATUS_REJECTED, _("Rejected")), | |
3127 | (STATUS_UNDER_REVIEW, _("Under Review")), |
|
3131 | (STATUS_UNDER_REVIEW, _("Under Review")), | |
3128 | ] |
|
3132 | ] | |
3129 |
|
3133 | |||
3130 | changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True) |
|
3134 | changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True) | |
3131 | repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False) |
|
3135 | repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False) | |
3132 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None) |
|
3136 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None) | |
3133 | revision = Column('revision', String(40), nullable=False) |
|
3137 | revision = Column('revision', String(40), nullable=False) | |
3134 | status = Column('status', String(128), nullable=False, default=DEFAULT) |
|
3138 | status = Column('status', String(128), nullable=False, default=DEFAULT) | |
3135 | changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id')) |
|
3139 | changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id')) | |
3136 | modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now) |
|
3140 | modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now) | |
3137 | version = Column('version', Integer(), nullable=False, default=0) |
|
3141 | version = Column('version', Integer(), nullable=False, default=0) | |
3138 | pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True) |
|
3142 | pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True) | |
3139 |
|
3143 | |||
3140 | author = relationship('User', lazy='joined') |
|
3144 | author = relationship('User', lazy='joined') | |
3141 | repo = relationship('Repository') |
|
3145 | repo = relationship('Repository') | |
3142 | comment = relationship('ChangesetComment', lazy='joined') |
|
3146 | comment = relationship('ChangesetComment', lazy='joined') | |
3143 | pull_request = relationship('PullRequest', lazy='joined') |
|
3147 | pull_request = relationship('PullRequest', lazy='joined') | |
3144 |
|
3148 | |||
3145 | def __unicode__(self): |
|
3149 | def __unicode__(self): | |
3146 | return u"<%s('%s[v%s]:%s')>" % ( |
|
3150 | return u"<%s('%s[v%s]:%s')>" % ( | |
3147 | self.__class__.__name__, |
|
3151 | self.__class__.__name__, | |
3148 | self.status, self.version, self.author |
|
3152 | self.status, self.version, self.author | |
3149 | ) |
|
3153 | ) | |
3150 |
|
3154 | |||
3151 | @classmethod |
|
3155 | @classmethod | |
3152 | def get_status_lbl(cls, value): |
|
3156 | def get_status_lbl(cls, value): | |
3153 | return dict(cls.STATUSES).get(value) |
|
3157 | return dict(cls.STATUSES).get(value) | |
3154 |
|
3158 | |||
3155 | @property |
|
3159 | @property | |
3156 | def status_lbl(self): |
|
3160 | def status_lbl(self): | |
3157 | return ChangesetStatus.get_status_lbl(self.status) |
|
3161 | return ChangesetStatus.get_status_lbl(self.status) | |
3158 |
|
3162 | |||
3159 |
|
3163 | |||
3160 | class _PullRequestBase(BaseModel): |
|
3164 | class _PullRequestBase(BaseModel): | |
3161 | """ |
|
3165 | """ | |
3162 | Common attributes of pull request and version entries. |
|
3166 | Common attributes of pull request and version entries. | |
3163 | """ |
|
3167 | """ | |
3164 |
|
3168 | |||
3165 | # .status values |
|
3169 | # .status values | |
3166 | STATUS_NEW = u'new' |
|
3170 | STATUS_NEW = u'new' | |
3167 | STATUS_OPEN = u'open' |
|
3171 | STATUS_OPEN = u'open' | |
3168 | STATUS_CLOSED = u'closed' |
|
3172 | STATUS_CLOSED = u'closed' | |
3169 |
|
3173 | |||
3170 | title = Column('title', Unicode(255), nullable=True) |
|
3174 | title = Column('title', Unicode(255), nullable=True) | |
3171 | description = Column( |
|
3175 | description = Column( | |
3172 | 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), |
|
3176 | 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), | |
3173 | nullable=True) |
|
3177 | nullable=True) | |
3174 | # new/open/closed status of pull request (not approve/reject/etc) |
|
3178 | # new/open/closed status of pull request (not approve/reject/etc) | |
3175 | status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW) |
|
3179 | status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW) | |
3176 | created_on = Column( |
|
3180 | created_on = Column( | |
3177 | 'created_on', DateTime(timezone=False), nullable=False, |
|
3181 | 'created_on', DateTime(timezone=False), nullable=False, | |
3178 | default=datetime.datetime.now) |
|
3182 | default=datetime.datetime.now) | |
3179 | updated_on = Column( |
|
3183 | updated_on = Column( | |
3180 | 'updated_on', DateTime(timezone=False), nullable=False, |
|
3184 | 'updated_on', DateTime(timezone=False), nullable=False, | |
3181 | default=datetime.datetime.now) |
|
3185 | default=datetime.datetime.now) | |
3182 |
|
3186 | |||
3183 | @declared_attr |
|
3187 | @declared_attr | |
3184 | def user_id(cls): |
|
3188 | def user_id(cls): | |
3185 | return Column( |
|
3189 | return Column( | |
3186 | "user_id", Integer(), ForeignKey('users.user_id'), nullable=False, |
|
3190 | "user_id", Integer(), ForeignKey('users.user_id'), nullable=False, | |
3187 | unique=None) |
|
3191 | unique=None) | |
3188 |
|
3192 | |||
3189 | # 500 revisions max |
|
3193 | # 500 revisions max | |
3190 | _revisions = Column( |
|
3194 | _revisions = Column( | |
3191 | 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql')) |
|
3195 | 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql')) | |
3192 |
|
3196 | |||
3193 | @declared_attr |
|
3197 | @declared_attr | |
3194 | def source_repo_id(cls): |
|
3198 | def source_repo_id(cls): | |
3195 | # TODO: dan: rename column to source_repo_id |
|
3199 | # TODO: dan: rename column to source_repo_id | |
3196 | return Column( |
|
3200 | return Column( | |
3197 | 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'), |
|
3201 | 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'), | |
3198 | nullable=False) |
|
3202 | nullable=False) | |
3199 |
|
3203 | |||
3200 | source_ref = Column('org_ref', Unicode(255), nullable=False) |
|
3204 | source_ref = Column('org_ref', Unicode(255), nullable=False) | |
3201 |
|
3205 | |||
3202 | @declared_attr |
|
3206 | @declared_attr | |
3203 | def target_repo_id(cls): |
|
3207 | def target_repo_id(cls): | |
3204 | # TODO: dan: rename column to target_repo_id |
|
3208 | # TODO: dan: rename column to target_repo_id | |
3205 | return Column( |
|
3209 | return Column( | |
3206 | 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'), |
|
3210 | 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'), | |
3207 | nullable=False) |
|
3211 | nullable=False) | |
3208 |
|
3212 | |||
3209 | target_ref = Column('other_ref', Unicode(255), nullable=False) |
|
3213 | target_ref = Column('other_ref', Unicode(255), nullable=False) | |
3210 | _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True) |
|
3214 | _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True) | |
3211 |
|
3215 | |||
3212 | # TODO: dan: rename column to last_merge_source_rev |
|
3216 | # TODO: dan: rename column to last_merge_source_rev | |
3213 | _last_merge_source_rev = Column( |
|
3217 | _last_merge_source_rev = Column( | |
3214 | 'last_merge_org_rev', String(40), nullable=True) |
|
3218 | 'last_merge_org_rev', String(40), nullable=True) | |
3215 | # TODO: dan: rename column to last_merge_target_rev |
|
3219 | # TODO: dan: rename column to last_merge_target_rev | |
3216 | _last_merge_target_rev = Column( |
|
3220 | _last_merge_target_rev = Column( | |
3217 | 'last_merge_other_rev', String(40), nullable=True) |
|
3221 | 'last_merge_other_rev', String(40), nullable=True) | |
3218 | _last_merge_status = Column('merge_status', Integer(), nullable=True) |
|
3222 | _last_merge_status = Column('merge_status', Integer(), nullable=True) | |
3219 | merge_rev = Column('merge_rev', String(40), nullable=True) |
|
3223 | merge_rev = Column('merge_rev', String(40), nullable=True) | |
3220 |
|
3224 | |||
3221 | @hybrid_property |
|
3225 | @hybrid_property | |
3222 | def revisions(self): |
|
3226 | def revisions(self): | |
3223 | return self._revisions.split(':') if self._revisions else [] |
|
3227 | return self._revisions.split(':') if self._revisions else [] | |
3224 |
|
3228 | |||
3225 | @revisions.setter |
|
3229 | @revisions.setter | |
3226 | def revisions(self, val): |
|
3230 | def revisions(self, val): | |
3227 | self._revisions = ':'.join(val) |
|
3231 | self._revisions = ':'.join(val) | |
3228 |
|
3232 | |||
3229 | @declared_attr |
|
3233 | @declared_attr | |
3230 | def author(cls): |
|
3234 | def author(cls): | |
3231 | return relationship('User', lazy='joined') |
|
3235 | return relationship('User', lazy='joined') | |
3232 |
|
3236 | |||
3233 | @declared_attr |
|
3237 | @declared_attr | |
3234 | def source_repo(cls): |
|
3238 | def source_repo(cls): | |
3235 | return relationship( |
|
3239 | return relationship( | |
3236 | 'Repository', |
|
3240 | 'Repository', | |
3237 | primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__) |
|
3241 | primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__) | |
3238 |
|
3242 | |||
3239 | @property |
|
3243 | @property | |
3240 | def source_ref_parts(self): |
|
3244 | def source_ref_parts(self): | |
3241 | return self.unicode_to_reference(self.source_ref) |
|
3245 | return self.unicode_to_reference(self.source_ref) | |
3242 |
|
3246 | |||
3243 | @declared_attr |
|
3247 | @declared_attr | |
3244 | def target_repo(cls): |
|
3248 | def target_repo(cls): | |
3245 | return relationship( |
|
3249 | return relationship( | |
3246 | 'Repository', |
|
3250 | 'Repository', | |
3247 | primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__) |
|
3251 | primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__) | |
3248 |
|
3252 | |||
3249 | @property |
|
3253 | @property | |
3250 | def target_ref_parts(self): |
|
3254 | def target_ref_parts(self): | |
3251 | return self.unicode_to_reference(self.target_ref) |
|
3255 | return self.unicode_to_reference(self.target_ref) | |
3252 |
|
3256 | |||
3253 | @property |
|
3257 | @property | |
3254 | def shadow_merge_ref(self): |
|
3258 | def shadow_merge_ref(self): | |
3255 | return self.unicode_to_reference(self._shadow_merge_ref) |
|
3259 | return self.unicode_to_reference(self._shadow_merge_ref) | |
3256 |
|
3260 | |||
3257 | @shadow_merge_ref.setter |
|
3261 | @shadow_merge_ref.setter | |
3258 | def shadow_merge_ref(self, ref): |
|
3262 | def shadow_merge_ref(self, ref): | |
3259 | self._shadow_merge_ref = self.reference_to_unicode(ref) |
|
3263 | self._shadow_merge_ref = self.reference_to_unicode(ref) | |
3260 |
|
3264 | |||
3261 | def unicode_to_reference(self, raw): |
|
3265 | def unicode_to_reference(self, raw): | |
3262 | """ |
|
3266 | """ | |
3263 | Convert a unicode (or string) to a reference object. |
|
3267 | Convert a unicode (or string) to a reference object. | |
3264 | If unicode evaluates to False it returns None. |
|
3268 | If unicode evaluates to False it returns None. | |
3265 | """ |
|
3269 | """ | |
3266 | if raw: |
|
3270 | if raw: | |
3267 | refs = raw.split(':') |
|
3271 | refs = raw.split(':') | |
3268 | return Reference(*refs) |
|
3272 | return Reference(*refs) | |
3269 | else: |
|
3273 | else: | |
3270 | return None |
|
3274 | return None | |
3271 |
|
3275 | |||
3272 | def reference_to_unicode(self, ref): |
|
3276 | def reference_to_unicode(self, ref): | |
3273 | """ |
|
3277 | """ | |
3274 | Convert a reference object to unicode. |
|
3278 | Convert a reference object to unicode. | |
3275 | If reference is None it returns None. |
|
3279 | If reference is None it returns None. | |
3276 | """ |
|
3280 | """ | |
3277 | if ref: |
|
3281 | if ref: | |
3278 | return u':'.join(ref) |
|
3282 | return u':'.join(ref) | |
3279 | else: |
|
3283 | else: | |
3280 | return None |
|
3284 | return None | |
3281 |
|
3285 | |||
3282 | def get_api_data(self): |
|
3286 | def get_api_data(self): | |
3283 | from rhodecode.model.pull_request import PullRequestModel |
|
3287 | from rhodecode.model.pull_request import PullRequestModel | |
3284 | pull_request = self |
|
3288 | pull_request = self | |
3285 | merge_status = PullRequestModel().merge_status(pull_request) |
|
3289 | merge_status = PullRequestModel().merge_status(pull_request) | |
3286 |
|
3290 | |||
3287 | pull_request_url = url( |
|
3291 | pull_request_url = url( | |
3288 | 'pullrequest_show', repo_name=self.target_repo.repo_name, |
|
3292 | 'pullrequest_show', repo_name=self.target_repo.repo_name, | |
3289 | pull_request_id=self.pull_request_id, qualified=True) |
|
3293 | pull_request_id=self.pull_request_id, qualified=True) | |
3290 |
|
3294 | |||
3291 | merge_data = { |
|
3295 | merge_data = { | |
3292 | 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request), |
|
3296 | 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request), | |
3293 | 'reference': ( |
|
3297 | 'reference': ( | |
3294 | pull_request.shadow_merge_ref._asdict() |
|
3298 | pull_request.shadow_merge_ref._asdict() | |
3295 | if pull_request.shadow_merge_ref else None), |
|
3299 | if pull_request.shadow_merge_ref else None), | |
3296 | } |
|
3300 | } | |
3297 |
|
3301 | |||
3298 | data = { |
|
3302 | data = { | |
3299 | 'pull_request_id': pull_request.pull_request_id, |
|
3303 | 'pull_request_id': pull_request.pull_request_id, | |
3300 | 'url': pull_request_url, |
|
3304 | 'url': pull_request_url, | |
3301 | 'title': pull_request.title, |
|
3305 | 'title': pull_request.title, | |
3302 | 'description': pull_request.description, |
|
3306 | 'description': pull_request.description, | |
3303 | 'status': pull_request.status, |
|
3307 | 'status': pull_request.status, | |
3304 | 'created_on': pull_request.created_on, |
|
3308 | 'created_on': pull_request.created_on, | |
3305 | 'updated_on': pull_request.updated_on, |
|
3309 | 'updated_on': pull_request.updated_on, | |
3306 | 'commit_ids': pull_request.revisions, |
|
3310 | 'commit_ids': pull_request.revisions, | |
3307 | 'review_status': pull_request.calculated_review_status(), |
|
3311 | 'review_status': pull_request.calculated_review_status(), | |
3308 | 'mergeable': { |
|
3312 | 'mergeable': { | |
3309 | 'status': merge_status[0], |
|
3313 | 'status': merge_status[0], | |
3310 | 'message': unicode(merge_status[1]), |
|
3314 | 'message': unicode(merge_status[1]), | |
3311 | }, |
|
3315 | }, | |
3312 | 'source': { |
|
3316 | 'source': { | |
3313 | 'clone_url': pull_request.source_repo.clone_url(), |
|
3317 | 'clone_url': pull_request.source_repo.clone_url(), | |
3314 | 'repository': pull_request.source_repo.repo_name, |
|
3318 | 'repository': pull_request.source_repo.repo_name, | |
3315 | 'reference': { |
|
3319 | 'reference': { | |
3316 | 'name': pull_request.source_ref_parts.name, |
|
3320 | 'name': pull_request.source_ref_parts.name, | |
3317 | 'type': pull_request.source_ref_parts.type, |
|
3321 | 'type': pull_request.source_ref_parts.type, | |
3318 | 'commit_id': pull_request.source_ref_parts.commit_id, |
|
3322 | 'commit_id': pull_request.source_ref_parts.commit_id, | |
3319 | }, |
|
3323 | }, | |
3320 | }, |
|
3324 | }, | |
3321 | 'target': { |
|
3325 | 'target': { | |
3322 | 'clone_url': pull_request.target_repo.clone_url(), |
|
3326 | 'clone_url': pull_request.target_repo.clone_url(), | |
3323 | 'repository': pull_request.target_repo.repo_name, |
|
3327 | 'repository': pull_request.target_repo.repo_name, | |
3324 | 'reference': { |
|
3328 | 'reference': { | |
3325 | 'name': pull_request.target_ref_parts.name, |
|
3329 | 'name': pull_request.target_ref_parts.name, | |
3326 | 'type': pull_request.target_ref_parts.type, |
|
3330 | 'type': pull_request.target_ref_parts.type, | |
3327 | 'commit_id': pull_request.target_ref_parts.commit_id, |
|
3331 | 'commit_id': pull_request.target_ref_parts.commit_id, | |
3328 | }, |
|
3332 | }, | |
3329 | }, |
|
3333 | }, | |
3330 | 'merge': merge_data, |
|
3334 | 'merge': merge_data, | |
3331 | 'author': pull_request.author.get_api_data(include_secrets=False, |
|
3335 | 'author': pull_request.author.get_api_data(include_secrets=False, | |
3332 | details='basic'), |
|
3336 | details='basic'), | |
3333 | 'reviewers': [ |
|
3337 | 'reviewers': [ | |
3334 | { |
|
3338 | { | |
3335 | 'user': reviewer.get_api_data(include_secrets=False, |
|
3339 | 'user': reviewer.get_api_data(include_secrets=False, | |
3336 | details='basic'), |
|
3340 | details='basic'), | |
3337 | 'reasons': reasons, |
|
3341 | 'reasons': reasons, | |
3338 | 'review_status': st[0][1].status if st else 'not_reviewed', |
|
3342 | 'review_status': st[0][1].status if st else 'not_reviewed', | |
3339 | } |
|
3343 | } | |
3340 | for reviewer, reasons, st in pull_request.reviewers_statuses() |
|
3344 | for reviewer, reasons, st in pull_request.reviewers_statuses() | |
3341 | ] |
|
3345 | ] | |
3342 | } |
|
3346 | } | |
3343 |
|
3347 | |||
3344 | return data |
|
3348 | return data | |
3345 |
|
3349 | |||
3346 |
|
3350 | |||
3347 | class PullRequest(Base, _PullRequestBase): |
|
3351 | class PullRequest(Base, _PullRequestBase): | |
3348 | __tablename__ = 'pull_requests' |
|
3352 | __tablename__ = 'pull_requests' | |
3349 | __table_args__ = ( |
|
3353 | __table_args__ = ( | |
3350 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3354 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3351 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3355 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
3352 | ) |
|
3356 | ) | |
3353 |
|
3357 | |||
3354 | pull_request_id = Column( |
|
3358 | pull_request_id = Column( | |
3355 | 'pull_request_id', Integer(), nullable=False, primary_key=True) |
|
3359 | 'pull_request_id', Integer(), nullable=False, primary_key=True) | |
3356 |
|
3360 | |||
3357 | def __repr__(self): |
|
3361 | def __repr__(self): | |
3358 | if self.pull_request_id: |
|
3362 | if self.pull_request_id: | |
3359 | return '<DB:PullRequest #%s>' % self.pull_request_id |
|
3363 | return '<DB:PullRequest #%s>' % self.pull_request_id | |
3360 | else: |
|
3364 | else: | |
3361 | return '<DB:PullRequest at %#x>' % id(self) |
|
3365 | return '<DB:PullRequest at %#x>' % id(self) | |
3362 |
|
3366 | |||
3363 | reviewers = relationship('PullRequestReviewers', |
|
3367 | reviewers = relationship('PullRequestReviewers', | |
3364 | cascade="all, delete, delete-orphan") |
|
3368 | cascade="all, delete, delete-orphan") | |
3365 | statuses = relationship('ChangesetStatus') |
|
3369 | statuses = relationship('ChangesetStatus') | |
3366 | comments = relationship('ChangesetComment', |
|
3370 | comments = relationship('ChangesetComment', | |
3367 | cascade="all, delete, delete-orphan") |
|
3371 | cascade="all, delete, delete-orphan") | |
3368 | versions = relationship('PullRequestVersion', |
|
3372 | versions = relationship('PullRequestVersion', | |
3369 | cascade="all, delete, delete-orphan", |
|
3373 | cascade="all, delete, delete-orphan", | |
3370 | lazy='dynamic') |
|
3374 | lazy='dynamic') | |
3371 |
|
3375 | |||
3372 | @classmethod |
|
3376 | @classmethod | |
3373 | def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj, |
|
3377 | def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj, | |
3374 | internal_methods=None): |
|
3378 | internal_methods=None): | |
3375 |
|
3379 | |||
3376 | class PullRequestDisplay(object): |
|
3380 | class PullRequestDisplay(object): | |
3377 | """ |
|
3381 | """ | |
3378 | Special object wrapper for showing PullRequest data via Versions |
|
3382 | Special object wrapper for showing PullRequest data via Versions | |
3379 | It mimics PR object as close as possible. This is read only object |
|
3383 | It mimics PR object as close as possible. This is read only object | |
3380 | just for display |
|
3384 | just for display | |
3381 | """ |
|
3385 | """ | |
3382 |
|
3386 | |||
3383 | def __init__(self, attrs, internal=None): |
|
3387 | def __init__(self, attrs, internal=None): | |
3384 | self.attrs = attrs |
|
3388 | self.attrs = attrs | |
3385 | # internal have priority over the given ones via attrs |
|
3389 | # internal have priority over the given ones via attrs | |
3386 | self.internal = internal or ['versions'] |
|
3390 | self.internal = internal or ['versions'] | |
3387 |
|
3391 | |||
3388 | def __getattr__(self, item): |
|
3392 | def __getattr__(self, item): | |
3389 | if item in self.internal: |
|
3393 | if item in self.internal: | |
3390 | return getattr(self, item) |
|
3394 | return getattr(self, item) | |
3391 | try: |
|
3395 | try: | |
3392 | return self.attrs[item] |
|
3396 | return self.attrs[item] | |
3393 | except KeyError: |
|
3397 | except KeyError: | |
3394 | raise AttributeError( |
|
3398 | raise AttributeError( | |
3395 | '%s object has no attribute %s' % (self, item)) |
|
3399 | '%s object has no attribute %s' % (self, item)) | |
3396 |
|
3400 | |||
3397 | def __repr__(self): |
|
3401 | def __repr__(self): | |
3398 | return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id') |
|
3402 | return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id') | |
3399 |
|
3403 | |||
3400 | def versions(self): |
|
3404 | def versions(self): | |
3401 | return pull_request_obj.versions.order_by( |
|
3405 | return pull_request_obj.versions.order_by( | |
3402 | PullRequestVersion.pull_request_version_id).all() |
|
3406 | PullRequestVersion.pull_request_version_id).all() | |
3403 |
|
3407 | |||
3404 | def is_closed(self): |
|
3408 | def is_closed(self): | |
3405 | return pull_request_obj.is_closed() |
|
3409 | return pull_request_obj.is_closed() | |
3406 |
|
3410 | |||
3407 | @property |
|
3411 | @property | |
3408 | def pull_request_version_id(self): |
|
3412 | def pull_request_version_id(self): | |
3409 | return getattr(pull_request_obj, 'pull_request_version_id', None) |
|
3413 | return getattr(pull_request_obj, 'pull_request_version_id', None) | |
3410 |
|
3414 | |||
3411 | attrs = StrictAttributeDict(pull_request_obj.get_api_data()) |
|
3415 | attrs = StrictAttributeDict(pull_request_obj.get_api_data()) | |
3412 |
|
3416 | |||
3413 | attrs.author = StrictAttributeDict( |
|
3417 | attrs.author = StrictAttributeDict( | |
3414 | pull_request_obj.author.get_api_data()) |
|
3418 | pull_request_obj.author.get_api_data()) | |
3415 | if pull_request_obj.target_repo: |
|
3419 | if pull_request_obj.target_repo: | |
3416 | attrs.target_repo = StrictAttributeDict( |
|
3420 | attrs.target_repo = StrictAttributeDict( | |
3417 | pull_request_obj.target_repo.get_api_data()) |
|
3421 | pull_request_obj.target_repo.get_api_data()) | |
3418 | attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url |
|
3422 | attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url | |
3419 |
|
3423 | |||
3420 | if pull_request_obj.source_repo: |
|
3424 | if pull_request_obj.source_repo: | |
3421 | attrs.source_repo = StrictAttributeDict( |
|
3425 | attrs.source_repo = StrictAttributeDict( | |
3422 | pull_request_obj.source_repo.get_api_data()) |
|
3426 | pull_request_obj.source_repo.get_api_data()) | |
3423 | attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url |
|
3427 | attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url | |
3424 |
|
3428 | |||
3425 | attrs.source_ref_parts = pull_request_obj.source_ref_parts |
|
3429 | attrs.source_ref_parts = pull_request_obj.source_ref_parts | |
3426 | attrs.target_ref_parts = pull_request_obj.target_ref_parts |
|
3430 | attrs.target_ref_parts = pull_request_obj.target_ref_parts | |
3427 | attrs.revisions = pull_request_obj.revisions |
|
3431 | attrs.revisions = pull_request_obj.revisions | |
3428 |
|
3432 | |||
3429 | attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref |
|
3433 | attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref | |
3430 |
|
3434 | |||
3431 | return PullRequestDisplay(attrs, internal=internal_methods) |
|
3435 | return PullRequestDisplay(attrs, internal=internal_methods) | |
3432 |
|
3436 | |||
3433 | def is_closed(self): |
|
3437 | def is_closed(self): | |
3434 | return self.status == self.STATUS_CLOSED |
|
3438 | return self.status == self.STATUS_CLOSED | |
3435 |
|
3439 | |||
3436 | def __json__(self): |
|
3440 | def __json__(self): | |
3437 | return { |
|
3441 | return { | |
3438 | 'revisions': self.revisions, |
|
3442 | 'revisions': self.revisions, | |
3439 | } |
|
3443 | } | |
3440 |
|
3444 | |||
3441 | def calculated_review_status(self): |
|
3445 | def calculated_review_status(self): | |
3442 | from rhodecode.model.changeset_status import ChangesetStatusModel |
|
3446 | from rhodecode.model.changeset_status import ChangesetStatusModel | |
3443 | return ChangesetStatusModel().calculated_review_status(self) |
|
3447 | return ChangesetStatusModel().calculated_review_status(self) | |
3444 |
|
3448 | |||
3445 | def reviewers_statuses(self): |
|
3449 | def reviewers_statuses(self): | |
3446 | from rhodecode.model.changeset_status import ChangesetStatusModel |
|
3450 | from rhodecode.model.changeset_status import ChangesetStatusModel | |
3447 | return ChangesetStatusModel().reviewers_statuses(self) |
|
3451 | return ChangesetStatusModel().reviewers_statuses(self) | |
3448 |
|
3452 | |||
3449 | @property |
|
3453 | @property | |
3450 | def workspace_id(self): |
|
3454 | def workspace_id(self): | |
3451 | from rhodecode.model.pull_request import PullRequestModel |
|
3455 | from rhodecode.model.pull_request import PullRequestModel | |
3452 | return PullRequestModel()._workspace_id(self) |
|
3456 | return PullRequestModel()._workspace_id(self) | |
3453 |
|
3457 | |||
3454 | def get_shadow_repo(self): |
|
3458 | def get_shadow_repo(self): | |
3455 | workspace_id = self.workspace_id |
|
3459 | workspace_id = self.workspace_id | |
3456 | vcs_obj = self.target_repo.scm_instance() |
|
3460 | vcs_obj = self.target_repo.scm_instance() | |
3457 | shadow_repository_path = vcs_obj._get_shadow_repository_path( |
|
3461 | shadow_repository_path = vcs_obj._get_shadow_repository_path( | |
3458 | workspace_id) |
|
3462 | workspace_id) | |
3459 | return vcs_obj._get_shadow_instance(shadow_repository_path) |
|
3463 | return vcs_obj._get_shadow_instance(shadow_repository_path) | |
3460 |
|
3464 | |||
3461 |
|
3465 | |||
3462 | class PullRequestVersion(Base, _PullRequestBase): |
|
3466 | class PullRequestVersion(Base, _PullRequestBase): | |
3463 | __tablename__ = 'pull_request_versions' |
|
3467 | __tablename__ = 'pull_request_versions' | |
3464 | __table_args__ = ( |
|
3468 | __table_args__ = ( | |
3465 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3469 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3466 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3470 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
3467 | ) |
|
3471 | ) | |
3468 |
|
3472 | |||
3469 | pull_request_version_id = Column( |
|
3473 | pull_request_version_id = Column( | |
3470 | 'pull_request_version_id', Integer(), nullable=False, primary_key=True) |
|
3474 | 'pull_request_version_id', Integer(), nullable=False, primary_key=True) | |
3471 | pull_request_id = Column( |
|
3475 | pull_request_id = Column( | |
3472 | 'pull_request_id', Integer(), |
|
3476 | 'pull_request_id', Integer(), | |
3473 | ForeignKey('pull_requests.pull_request_id'), nullable=False) |
|
3477 | ForeignKey('pull_requests.pull_request_id'), nullable=False) | |
3474 | pull_request = relationship('PullRequest') |
|
3478 | pull_request = relationship('PullRequest') | |
3475 |
|
3479 | |||
3476 | def __repr__(self): |
|
3480 | def __repr__(self): | |
3477 | if self.pull_request_version_id: |
|
3481 | if self.pull_request_version_id: | |
3478 | return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id |
|
3482 | return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id | |
3479 | else: |
|
3483 | else: | |
3480 | return '<DB:PullRequestVersion at %#x>' % id(self) |
|
3484 | return '<DB:PullRequestVersion at %#x>' % id(self) | |
3481 |
|
3485 | |||
3482 | @property |
|
3486 | @property | |
3483 | def reviewers(self): |
|
3487 | def reviewers(self): | |
3484 | return self.pull_request.reviewers |
|
3488 | return self.pull_request.reviewers | |
3485 |
|
3489 | |||
3486 | @property |
|
3490 | @property | |
3487 | def versions(self): |
|
3491 | def versions(self): | |
3488 | return self.pull_request.versions |
|
3492 | return self.pull_request.versions | |
3489 |
|
3493 | |||
3490 | def is_closed(self): |
|
3494 | def is_closed(self): | |
3491 | # calculate from original |
|
3495 | # calculate from original | |
3492 | return self.pull_request.status == self.STATUS_CLOSED |
|
3496 | return self.pull_request.status == self.STATUS_CLOSED | |
3493 |
|
3497 | |||
3494 | def calculated_review_status(self): |
|
3498 | def calculated_review_status(self): | |
3495 | return self.pull_request.calculated_review_status() |
|
3499 | return self.pull_request.calculated_review_status() | |
3496 |
|
3500 | |||
3497 | def reviewers_statuses(self): |
|
3501 | def reviewers_statuses(self): | |
3498 | return self.pull_request.reviewers_statuses() |
|
3502 | return self.pull_request.reviewers_statuses() | |
3499 |
|
3503 | |||
3500 |
|
3504 | |||
3501 | class PullRequestReviewers(Base, BaseModel): |
|
3505 | class PullRequestReviewers(Base, BaseModel): | |
3502 | __tablename__ = 'pull_request_reviewers' |
|
3506 | __tablename__ = 'pull_request_reviewers' | |
3503 | __table_args__ = ( |
|
3507 | __table_args__ = ( | |
3504 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3508 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3505 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3509 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
3506 | ) |
|
3510 | ) | |
3507 |
|
3511 | |||
3508 | def __init__(self, user=None, pull_request=None, reasons=None): |
|
3512 | def __init__(self, user=None, pull_request=None, reasons=None): | |
3509 | self.user = user |
|
3513 | self.user = user | |
3510 | self.pull_request = pull_request |
|
3514 | self.pull_request = pull_request | |
3511 | self.reasons = reasons or [] |
|
3515 | self.reasons = reasons or [] | |
3512 |
|
3516 | |||
3513 | @hybrid_property |
|
3517 | @hybrid_property | |
3514 | def reasons(self): |
|
3518 | def reasons(self): | |
3515 | if not self._reasons: |
|
3519 | if not self._reasons: | |
3516 | return [] |
|
3520 | return [] | |
3517 | return self._reasons |
|
3521 | return self._reasons | |
3518 |
|
3522 | |||
3519 | @reasons.setter |
|
3523 | @reasons.setter | |
3520 | def reasons(self, val): |
|
3524 | def reasons(self, val): | |
3521 | val = val or [] |
|
3525 | val = val or [] | |
3522 | if any(not isinstance(x, basestring) for x in val): |
|
3526 | if any(not isinstance(x, basestring) for x in val): | |
3523 | raise Exception('invalid reasons type, must be list of strings') |
|
3527 | raise Exception('invalid reasons type, must be list of strings') | |
3524 | self._reasons = val |
|
3528 | self._reasons = val | |
3525 |
|
3529 | |||
3526 | pull_requests_reviewers_id = Column( |
|
3530 | pull_requests_reviewers_id = Column( | |
3527 | 'pull_requests_reviewers_id', Integer(), nullable=False, |
|
3531 | 'pull_requests_reviewers_id', Integer(), nullable=False, | |
3528 | primary_key=True) |
|
3532 | primary_key=True) | |
3529 | pull_request_id = Column( |
|
3533 | pull_request_id = Column( | |
3530 | "pull_request_id", Integer(), |
|
3534 | "pull_request_id", Integer(), | |
3531 | ForeignKey('pull_requests.pull_request_id'), nullable=False) |
|
3535 | ForeignKey('pull_requests.pull_request_id'), nullable=False) | |
3532 | user_id = Column( |
|
3536 | user_id = Column( | |
3533 | "user_id", Integer(), ForeignKey('users.user_id'), nullable=True) |
|
3537 | "user_id", Integer(), ForeignKey('users.user_id'), nullable=True) | |
3534 | _reasons = Column( |
|
3538 | _reasons = Column( | |
3535 | 'reason', MutationList.as_mutable( |
|
3539 | 'reason', MutationList.as_mutable( | |
3536 | JsonType('list', dialect_map=dict(mysql=UnicodeText(16384))))) |
|
3540 | JsonType('list', dialect_map=dict(mysql=UnicodeText(16384))))) | |
3537 |
|
3541 | |||
3538 | user = relationship('User') |
|
3542 | user = relationship('User') | |
3539 | pull_request = relationship('PullRequest') |
|
3543 | pull_request = relationship('PullRequest') | |
3540 |
|
3544 | |||
3541 |
|
3545 | |||
3542 | class Notification(Base, BaseModel): |
|
3546 | class Notification(Base, BaseModel): | |
3543 | __tablename__ = 'notifications' |
|
3547 | __tablename__ = 'notifications' | |
3544 | __table_args__ = ( |
|
3548 | __table_args__ = ( | |
3545 | Index('notification_type_idx', 'type'), |
|
3549 | Index('notification_type_idx', 'type'), | |
3546 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3550 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3547 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3551 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
3548 | ) |
|
3552 | ) | |
3549 |
|
3553 | |||
3550 | TYPE_CHANGESET_COMMENT = u'cs_comment' |
|
3554 | TYPE_CHANGESET_COMMENT = u'cs_comment' | |
3551 | TYPE_MESSAGE = u'message' |
|
3555 | TYPE_MESSAGE = u'message' | |
3552 | TYPE_MENTION = u'mention' |
|
3556 | TYPE_MENTION = u'mention' | |
3553 | TYPE_REGISTRATION = u'registration' |
|
3557 | TYPE_REGISTRATION = u'registration' | |
3554 | TYPE_PULL_REQUEST = u'pull_request' |
|
3558 | TYPE_PULL_REQUEST = u'pull_request' | |
3555 | TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment' |
|
3559 | TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment' | |
3556 |
|
3560 | |||
3557 | notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True) |
|
3561 | notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True) | |
3558 | subject = Column('subject', Unicode(512), nullable=True) |
|
3562 | subject = Column('subject', Unicode(512), nullable=True) | |
3559 | body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True) |
|
3563 | body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True) | |
3560 | created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True) |
|
3564 | created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True) | |
3561 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3565 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
3562 | type_ = Column('type', Unicode(255)) |
|
3566 | type_ = Column('type', Unicode(255)) | |
3563 |
|
3567 | |||
3564 | created_by_user = relationship('User') |
|
3568 | created_by_user = relationship('User') | |
3565 | notifications_to_users = relationship('UserNotification', lazy='joined', |
|
3569 | notifications_to_users = relationship('UserNotification', lazy='joined', | |
3566 | cascade="all, delete, delete-orphan") |
|
3570 | cascade="all, delete, delete-orphan") | |
3567 |
|
3571 | |||
3568 | @property |
|
3572 | @property | |
3569 | def recipients(self): |
|
3573 | def recipients(self): | |
3570 | return [x.user for x in UserNotification.query()\ |
|
3574 | return [x.user for x in UserNotification.query()\ | |
3571 | .filter(UserNotification.notification == self)\ |
|
3575 | .filter(UserNotification.notification == self)\ | |
3572 | .order_by(UserNotification.user_id.asc()).all()] |
|
3576 | .order_by(UserNotification.user_id.asc()).all()] | |
3573 |
|
3577 | |||
3574 | @classmethod |
|
3578 | @classmethod | |
3575 | def create(cls, created_by, subject, body, recipients, type_=None): |
|
3579 | def create(cls, created_by, subject, body, recipients, type_=None): | |
3576 | if type_ is None: |
|
3580 | if type_ is None: | |
3577 | type_ = Notification.TYPE_MESSAGE |
|
3581 | type_ = Notification.TYPE_MESSAGE | |
3578 |
|
3582 | |||
3579 | notification = cls() |
|
3583 | notification = cls() | |
3580 | notification.created_by_user = created_by |
|
3584 | notification.created_by_user = created_by | |
3581 | notification.subject = subject |
|
3585 | notification.subject = subject | |
3582 | notification.body = body |
|
3586 | notification.body = body | |
3583 | notification.type_ = type_ |
|
3587 | notification.type_ = type_ | |
3584 | notification.created_on = datetime.datetime.now() |
|
3588 | notification.created_on = datetime.datetime.now() | |
3585 |
|
3589 | |||
3586 | for u in recipients: |
|
3590 | for u in recipients: | |
3587 | assoc = UserNotification() |
|
3591 | assoc = UserNotification() | |
3588 | assoc.notification = notification |
|
3592 | assoc.notification = notification | |
3589 |
|
3593 | |||
3590 | # if created_by is inside recipients mark his notification |
|
3594 | # if created_by is inside recipients mark his notification | |
3591 | # as read |
|
3595 | # as read | |
3592 | if u.user_id == created_by.user_id: |
|
3596 | if u.user_id == created_by.user_id: | |
3593 | assoc.read = True |
|
3597 | assoc.read = True | |
3594 |
|
3598 | |||
3595 | u.notifications.append(assoc) |
|
3599 | u.notifications.append(assoc) | |
3596 | Session().add(notification) |
|
3600 | Session().add(notification) | |
3597 |
|
3601 | |||
3598 | return notification |
|
3602 | return notification | |
3599 |
|
3603 | |||
3600 | @property |
|
3604 | @property | |
3601 | def description(self): |
|
3605 | def description(self): | |
3602 | from rhodecode.model.notification import NotificationModel |
|
3606 | from rhodecode.model.notification import NotificationModel | |
3603 | return NotificationModel().make_description(self) |
|
3607 | return NotificationModel().make_description(self) | |
3604 |
|
3608 | |||
3605 |
|
3609 | |||
3606 | class UserNotification(Base, BaseModel): |
|
3610 | class UserNotification(Base, BaseModel): | |
3607 | __tablename__ = 'user_to_notification' |
|
3611 | __tablename__ = 'user_to_notification' | |
3608 | __table_args__ = ( |
|
3612 | __table_args__ = ( | |
3609 | UniqueConstraint('user_id', 'notification_id'), |
|
3613 | UniqueConstraint('user_id', 'notification_id'), | |
3610 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3614 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3611 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
3615 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
3612 | ) |
|
3616 | ) | |
3613 | user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True) |
|
3617 | user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True) | |
3614 | notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True) |
|
3618 | notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True) | |
3615 | read = Column('read', Boolean, default=False) |
|
3619 | read = Column('read', Boolean, default=False) | |
3616 | sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None) |
|
3620 | sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None) | |
3617 |
|
3621 | |||
3618 | user = relationship('User', lazy="joined") |
|
3622 | user = relationship('User', lazy="joined") | |
3619 | notification = relationship('Notification', lazy="joined", |
|
3623 | notification = relationship('Notification', lazy="joined", | |
3620 | order_by=lambda: Notification.created_on.desc(),) |
|
3624 | order_by=lambda: Notification.created_on.desc(),) | |
3621 |
|
3625 | |||
3622 | def mark_as_read(self): |
|
3626 | def mark_as_read(self): | |
3623 | self.read = True |
|
3627 | self.read = True | |
3624 | Session().add(self) |
|
3628 | Session().add(self) | |
3625 |
|
3629 | |||
3626 |
|
3630 | |||
3627 | class Gist(Base, BaseModel): |
|
3631 | class Gist(Base, BaseModel): | |
3628 | __tablename__ = 'gists' |
|
3632 | __tablename__ = 'gists' | |
3629 | __table_args__ = ( |
|
3633 | __table_args__ = ( | |
3630 | Index('g_gist_access_id_idx', 'gist_access_id'), |
|
3634 | Index('g_gist_access_id_idx', 'gist_access_id'), | |
3631 | Index('g_created_on_idx', 'created_on'), |
|
3635 | Index('g_created_on_idx', 'created_on'), | |
3632 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3636 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3633 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
3637 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
3634 | ) |
|
3638 | ) | |
3635 | GIST_PUBLIC = u'public' |
|
3639 | GIST_PUBLIC = u'public' | |
3636 | GIST_PRIVATE = u'private' |
|
3640 | GIST_PRIVATE = u'private' | |
3637 | DEFAULT_FILENAME = u'gistfile1.txt' |
|
3641 | DEFAULT_FILENAME = u'gistfile1.txt' | |
3638 |
|
3642 | |||
3639 | ACL_LEVEL_PUBLIC = u'acl_public' |
|
3643 | ACL_LEVEL_PUBLIC = u'acl_public' | |
3640 | ACL_LEVEL_PRIVATE = u'acl_private' |
|
3644 | ACL_LEVEL_PRIVATE = u'acl_private' | |
3641 |
|
3645 | |||
3642 | gist_id = Column('gist_id', Integer(), primary_key=True) |
|
3646 | gist_id = Column('gist_id', Integer(), primary_key=True) | |
3643 | gist_access_id = Column('gist_access_id', Unicode(250)) |
|
3647 | gist_access_id = Column('gist_access_id', Unicode(250)) | |
3644 | gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql')) |
|
3648 | gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql')) | |
3645 | gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True) |
|
3649 | gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True) | |
3646 | gist_expires = Column('gist_expires', Float(53), nullable=False) |
|
3650 | gist_expires = Column('gist_expires', Float(53), nullable=False) | |
3647 | gist_type = Column('gist_type', Unicode(128), nullable=False) |
|
3651 | gist_type = Column('gist_type', Unicode(128), nullable=False) | |
3648 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3652 | created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
3649 | modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) |
|
3653 | modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now) | |
3650 | acl_level = Column('acl_level', Unicode(128), nullable=True) |
|
3654 | acl_level = Column('acl_level', Unicode(128), nullable=True) | |
3651 |
|
3655 | |||
3652 | owner = relationship('User') |
|
3656 | owner = relationship('User') | |
3653 |
|
3657 | |||
3654 | def __repr__(self): |
|
3658 | def __repr__(self): | |
3655 | return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id) |
|
3659 | return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id) | |
3656 |
|
3660 | |||
3657 | @classmethod |
|
3661 | @classmethod | |
3658 | def get_or_404(cls, id_, pyramid_exc=False): |
|
3662 | def get_or_404(cls, id_, pyramid_exc=False): | |
3659 |
|
3663 | |||
3660 | if pyramid_exc: |
|
3664 | if pyramid_exc: | |
3661 | from pyramid.httpexceptions import HTTPNotFound |
|
3665 | from pyramid.httpexceptions import HTTPNotFound | |
3662 | else: |
|
3666 | else: | |
3663 | from webob.exc import HTTPNotFound |
|
3667 | from webob.exc import HTTPNotFound | |
3664 |
|
3668 | |||
3665 | res = cls.query().filter(cls.gist_access_id == id_).scalar() |
|
3669 | res = cls.query().filter(cls.gist_access_id == id_).scalar() | |
3666 | if not res: |
|
3670 | if not res: | |
3667 | raise HTTPNotFound |
|
3671 | raise HTTPNotFound | |
3668 | return res |
|
3672 | return res | |
3669 |
|
3673 | |||
3670 | @classmethod |
|
3674 | @classmethod | |
3671 | def get_by_access_id(cls, gist_access_id): |
|
3675 | def get_by_access_id(cls, gist_access_id): | |
3672 | return cls.query().filter(cls.gist_access_id == gist_access_id).scalar() |
|
3676 | return cls.query().filter(cls.gist_access_id == gist_access_id).scalar() | |
3673 |
|
3677 | |||
3674 | def gist_url(self): |
|
3678 | def gist_url(self): | |
3675 | import rhodecode |
|
3679 | import rhodecode | |
3676 | alias_url = rhodecode.CONFIG.get('gist_alias_url') |
|
3680 | alias_url = rhodecode.CONFIG.get('gist_alias_url') | |
3677 | if alias_url: |
|
3681 | if alias_url: | |
3678 | return alias_url.replace('{gistid}', self.gist_access_id) |
|
3682 | return alias_url.replace('{gistid}', self.gist_access_id) | |
3679 |
|
3683 | |||
3680 | return url('gist', gist_id=self.gist_access_id, qualified=True) |
|
3684 | return url('gist', gist_id=self.gist_access_id, qualified=True) | |
3681 |
|
3685 | |||
3682 | @classmethod |
|
3686 | @classmethod | |
3683 | def base_path(cls): |
|
3687 | def base_path(cls): | |
3684 | """ |
|
3688 | """ | |
3685 | Returns base path when all gists are stored |
|
3689 | Returns base path when all gists are stored | |
3686 |
|
3690 | |||
3687 | :param cls: |
|
3691 | :param cls: | |
3688 | """ |
|
3692 | """ | |
3689 | from rhodecode.model.gist import GIST_STORE_LOC |
|
3693 | from rhodecode.model.gist import GIST_STORE_LOC | |
3690 | q = Session().query(RhodeCodeUi)\ |
|
3694 | q = Session().query(RhodeCodeUi)\ | |
3691 | .filter(RhodeCodeUi.ui_key == URL_SEP) |
|
3695 | .filter(RhodeCodeUi.ui_key == URL_SEP) | |
3692 | q = q.options(FromCache("sql_cache_short", "repository_repo_path")) |
|
3696 | q = q.options(FromCache("sql_cache_short", "repository_repo_path")) | |
3693 | return os.path.join(q.one().ui_value, GIST_STORE_LOC) |
|
3697 | return os.path.join(q.one().ui_value, GIST_STORE_LOC) | |
3694 |
|
3698 | |||
3695 | def get_api_data(self): |
|
3699 | def get_api_data(self): | |
3696 | """ |
|
3700 | """ | |
3697 | Common function for generating gist related data for API |
|
3701 | Common function for generating gist related data for API | |
3698 | """ |
|
3702 | """ | |
3699 | gist = self |
|
3703 | gist = self | |
3700 | data = { |
|
3704 | data = { | |
3701 | 'gist_id': gist.gist_id, |
|
3705 | 'gist_id': gist.gist_id, | |
3702 | 'type': gist.gist_type, |
|
3706 | 'type': gist.gist_type, | |
3703 | 'access_id': gist.gist_access_id, |
|
3707 | 'access_id': gist.gist_access_id, | |
3704 | 'description': gist.gist_description, |
|
3708 | 'description': gist.gist_description, | |
3705 | 'url': gist.gist_url(), |
|
3709 | 'url': gist.gist_url(), | |
3706 | 'expires': gist.gist_expires, |
|
3710 | 'expires': gist.gist_expires, | |
3707 | 'created_on': gist.created_on, |
|
3711 | 'created_on': gist.created_on, | |
3708 | 'modified_at': gist.modified_at, |
|
3712 | 'modified_at': gist.modified_at, | |
3709 | 'content': None, |
|
3713 | 'content': None, | |
3710 | 'acl_level': gist.acl_level, |
|
3714 | 'acl_level': gist.acl_level, | |
3711 | } |
|
3715 | } | |
3712 | return data |
|
3716 | return data | |
3713 |
|
3717 | |||
3714 | def __json__(self): |
|
3718 | def __json__(self): | |
3715 | data = dict( |
|
3719 | data = dict( | |
3716 | ) |
|
3720 | ) | |
3717 | data.update(self.get_api_data()) |
|
3721 | data.update(self.get_api_data()) | |
3718 | return data |
|
3722 | return data | |
3719 | # SCM functions |
|
3723 | # SCM functions | |
3720 |
|
3724 | |||
3721 | def scm_instance(self, **kwargs): |
|
3725 | def scm_instance(self, **kwargs): | |
3722 | full_repo_path = os.path.join(self.base_path(), self.gist_access_id) |
|
3726 | full_repo_path = os.path.join(self.base_path(), self.gist_access_id) | |
3723 | return get_vcs_instance( |
|
3727 | return get_vcs_instance( | |
3724 | repo_path=safe_str(full_repo_path), create=False) |
|
3728 | repo_path=safe_str(full_repo_path), create=False) | |
3725 |
|
3729 | |||
3726 |
|
3730 | |||
3727 | class ExternalIdentity(Base, BaseModel): |
|
3731 | class ExternalIdentity(Base, BaseModel): | |
3728 | __tablename__ = 'external_identities' |
|
3732 | __tablename__ = 'external_identities' | |
3729 | __table_args__ = ( |
|
3733 | __table_args__ = ( | |
3730 | Index('local_user_id_idx', 'local_user_id'), |
|
3734 | Index('local_user_id_idx', 'local_user_id'), | |
3731 | Index('external_id_idx', 'external_id'), |
|
3735 | Index('external_id_idx', 'external_id'), | |
3732 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3736 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3733 | 'mysql_charset': 'utf8'}) |
|
3737 | 'mysql_charset': 'utf8'}) | |
3734 |
|
3738 | |||
3735 | external_id = Column('external_id', Unicode(255), default=u'', |
|
3739 | external_id = Column('external_id', Unicode(255), default=u'', | |
3736 | primary_key=True) |
|
3740 | primary_key=True) | |
3737 | external_username = Column('external_username', Unicode(1024), default=u'') |
|
3741 | external_username = Column('external_username', Unicode(1024), default=u'') | |
3738 | local_user_id = Column('local_user_id', Integer(), |
|
3742 | local_user_id = Column('local_user_id', Integer(), | |
3739 | ForeignKey('users.user_id'), primary_key=True) |
|
3743 | ForeignKey('users.user_id'), primary_key=True) | |
3740 | provider_name = Column('provider_name', Unicode(255), default=u'', |
|
3744 | provider_name = Column('provider_name', Unicode(255), default=u'', | |
3741 | primary_key=True) |
|
3745 | primary_key=True) | |
3742 | access_token = Column('access_token', String(1024), default=u'') |
|
3746 | access_token = Column('access_token', String(1024), default=u'') | |
3743 | alt_token = Column('alt_token', String(1024), default=u'') |
|
3747 | alt_token = Column('alt_token', String(1024), default=u'') | |
3744 | token_secret = Column('token_secret', String(1024), default=u'') |
|
3748 | token_secret = Column('token_secret', String(1024), default=u'') | |
3745 |
|
3749 | |||
3746 | @classmethod |
|
3750 | @classmethod | |
3747 | def by_external_id_and_provider(cls, external_id, provider_name, |
|
3751 | def by_external_id_and_provider(cls, external_id, provider_name, | |
3748 | local_user_id=None): |
|
3752 | local_user_id=None): | |
3749 | """ |
|
3753 | """ | |
3750 | Returns ExternalIdentity instance based on search params |
|
3754 | Returns ExternalIdentity instance based on search params | |
3751 |
|
3755 | |||
3752 | :param external_id: |
|
3756 | :param external_id: | |
3753 | :param provider_name: |
|
3757 | :param provider_name: | |
3754 | :return: ExternalIdentity |
|
3758 | :return: ExternalIdentity | |
3755 | """ |
|
3759 | """ | |
3756 | query = cls.query() |
|
3760 | query = cls.query() | |
3757 | query = query.filter(cls.external_id == external_id) |
|
3761 | query = query.filter(cls.external_id == external_id) | |
3758 | query = query.filter(cls.provider_name == provider_name) |
|
3762 | query = query.filter(cls.provider_name == provider_name) | |
3759 | if local_user_id: |
|
3763 | if local_user_id: | |
3760 | query = query.filter(cls.local_user_id == local_user_id) |
|
3764 | query = query.filter(cls.local_user_id == local_user_id) | |
3761 | return query.first() |
|
3765 | return query.first() | |
3762 |
|
3766 | |||
3763 | @classmethod |
|
3767 | @classmethod | |
3764 | def user_by_external_id_and_provider(cls, external_id, provider_name): |
|
3768 | def user_by_external_id_and_provider(cls, external_id, provider_name): | |
3765 | """ |
|
3769 | """ | |
3766 | Returns User instance based on search params |
|
3770 | Returns User instance based on search params | |
3767 |
|
3771 | |||
3768 | :param external_id: |
|
3772 | :param external_id: | |
3769 | :param provider_name: |
|
3773 | :param provider_name: | |
3770 | :return: User |
|
3774 | :return: User | |
3771 | """ |
|
3775 | """ | |
3772 | query = User.query() |
|
3776 | query = User.query() | |
3773 | query = query.filter(cls.external_id == external_id) |
|
3777 | query = query.filter(cls.external_id == external_id) | |
3774 | query = query.filter(cls.provider_name == provider_name) |
|
3778 | query = query.filter(cls.provider_name == provider_name) | |
3775 | query = query.filter(User.user_id == cls.local_user_id) |
|
3779 | query = query.filter(User.user_id == cls.local_user_id) | |
3776 | return query.first() |
|
3780 | return query.first() | |
3777 |
|
3781 | |||
3778 | @classmethod |
|
3782 | @classmethod | |
3779 | def by_local_user_id(cls, local_user_id): |
|
3783 | def by_local_user_id(cls, local_user_id): | |
3780 | """ |
|
3784 | """ | |
3781 | Returns all tokens for user |
|
3785 | Returns all tokens for user | |
3782 |
|
3786 | |||
3783 | :param local_user_id: |
|
3787 | :param local_user_id: | |
3784 | :return: ExternalIdentity |
|
3788 | :return: ExternalIdentity | |
3785 | """ |
|
3789 | """ | |
3786 | query = cls.query() |
|
3790 | query = cls.query() | |
3787 | query = query.filter(cls.local_user_id == local_user_id) |
|
3791 | query = query.filter(cls.local_user_id == local_user_id) | |
3788 | return query |
|
3792 | return query | |
3789 |
|
3793 | |||
3790 |
|
3794 | |||
3791 | class Integration(Base, BaseModel): |
|
3795 | class Integration(Base, BaseModel): | |
3792 | __tablename__ = 'integrations' |
|
3796 | __tablename__ = 'integrations' | |
3793 | __table_args__ = ( |
|
3797 | __table_args__ = ( | |
3794 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3798 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3795 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} |
|
3799 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True} | |
3796 | ) |
|
3800 | ) | |
3797 |
|
3801 | |||
3798 | integration_id = Column('integration_id', Integer(), primary_key=True) |
|
3802 | integration_id = Column('integration_id', Integer(), primary_key=True) | |
3799 | integration_type = Column('integration_type', String(255)) |
|
3803 | integration_type = Column('integration_type', String(255)) | |
3800 | enabled = Column('enabled', Boolean(), nullable=False) |
|
3804 | enabled = Column('enabled', Boolean(), nullable=False) | |
3801 | name = Column('name', String(255), nullable=False) |
|
3805 | name = Column('name', String(255), nullable=False) | |
3802 | child_repos_only = Column('child_repos_only', Boolean(), nullable=False, |
|
3806 | child_repos_only = Column('child_repos_only', Boolean(), nullable=False, | |
3803 | default=False) |
|
3807 | default=False) | |
3804 |
|
3808 | |||
3805 | settings = Column( |
|
3809 | settings = Column( | |
3806 | 'settings_json', MutationObj.as_mutable( |
|
3810 | 'settings_json', MutationObj.as_mutable( | |
3807 | JsonType(dialect_map=dict(mysql=UnicodeText(16384))))) |
|
3811 | JsonType(dialect_map=dict(mysql=UnicodeText(16384))))) | |
3808 | repo_id = Column( |
|
3812 | repo_id = Column( | |
3809 | 'repo_id', Integer(), ForeignKey('repositories.repo_id'), |
|
3813 | 'repo_id', Integer(), ForeignKey('repositories.repo_id'), | |
3810 | nullable=True, unique=None, default=None) |
|
3814 | nullable=True, unique=None, default=None) | |
3811 | repo = relationship('Repository', lazy='joined') |
|
3815 | repo = relationship('Repository', lazy='joined') | |
3812 |
|
3816 | |||
3813 | repo_group_id = Column( |
|
3817 | repo_group_id = Column( | |
3814 | 'repo_group_id', Integer(), ForeignKey('groups.group_id'), |
|
3818 | 'repo_group_id', Integer(), ForeignKey('groups.group_id'), | |
3815 | nullable=True, unique=None, default=None) |
|
3819 | nullable=True, unique=None, default=None) | |
3816 | repo_group = relationship('RepoGroup', lazy='joined') |
|
3820 | repo_group = relationship('RepoGroup', lazy='joined') | |
3817 |
|
3821 | |||
3818 | @property |
|
3822 | @property | |
3819 | def scope(self): |
|
3823 | def scope(self): | |
3820 | if self.repo: |
|
3824 | if self.repo: | |
3821 | return repr(self.repo) |
|
3825 | return repr(self.repo) | |
3822 | if self.repo_group: |
|
3826 | if self.repo_group: | |
3823 | if self.child_repos_only: |
|
3827 | if self.child_repos_only: | |
3824 | return repr(self.repo_group) + ' (child repos only)' |
|
3828 | return repr(self.repo_group) + ' (child repos only)' | |
3825 | else: |
|
3829 | else: | |
3826 | return repr(self.repo_group) + ' (recursive)' |
|
3830 | return repr(self.repo_group) + ' (recursive)' | |
3827 | if self.child_repos_only: |
|
3831 | if self.child_repos_only: | |
3828 | return 'root_repos' |
|
3832 | return 'root_repos' | |
3829 | return 'global' |
|
3833 | return 'global' | |
3830 |
|
3834 | |||
3831 | def __repr__(self): |
|
3835 | def __repr__(self): | |
3832 | return '<Integration(%r, %r)>' % (self.integration_type, self.scope) |
|
3836 | return '<Integration(%r, %r)>' % (self.integration_type, self.scope) | |
3833 |
|
3837 | |||
3834 |
|
3838 | |||
3835 | class RepoReviewRuleUser(Base, BaseModel): |
|
3839 | class RepoReviewRuleUser(Base, BaseModel): | |
3836 | __tablename__ = 'repo_review_rules_users' |
|
3840 | __tablename__ = 'repo_review_rules_users' | |
3837 | __table_args__ = ( |
|
3841 | __table_args__ = ( | |
3838 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3842 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3839 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,} |
|
3843 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,} | |
3840 | ) |
|
3844 | ) | |
3841 | repo_review_rule_user_id = Column( |
|
3845 | repo_review_rule_user_id = Column( | |
3842 | 'repo_review_rule_user_id', Integer(), primary_key=True) |
|
3846 | 'repo_review_rule_user_id', Integer(), primary_key=True) | |
3843 | repo_review_rule_id = Column("repo_review_rule_id", |
|
3847 | repo_review_rule_id = Column("repo_review_rule_id", | |
3844 | Integer(), ForeignKey('repo_review_rules.repo_review_rule_id')) |
|
3848 | Integer(), ForeignKey('repo_review_rules.repo_review_rule_id')) | |
3845 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), |
|
3849 | user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), | |
3846 | nullable=False) |
|
3850 | nullable=False) | |
3847 | user = relationship('User') |
|
3851 | user = relationship('User') | |
3848 |
|
3852 | |||
3849 |
|
3853 | |||
3850 | class RepoReviewRuleUserGroup(Base, BaseModel): |
|
3854 | class RepoReviewRuleUserGroup(Base, BaseModel): | |
3851 | __tablename__ = 'repo_review_rules_users_groups' |
|
3855 | __tablename__ = 'repo_review_rules_users_groups' | |
3852 | __table_args__ = ( |
|
3856 | __table_args__ = ( | |
3853 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3857 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3854 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,} |
|
3858 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,} | |
3855 | ) |
|
3859 | ) | |
3856 | repo_review_rule_users_group_id = Column( |
|
3860 | repo_review_rule_users_group_id = Column( | |
3857 | 'repo_review_rule_users_group_id', Integer(), primary_key=True) |
|
3861 | 'repo_review_rule_users_group_id', Integer(), primary_key=True) | |
3858 | repo_review_rule_id = Column("repo_review_rule_id", |
|
3862 | repo_review_rule_id = Column("repo_review_rule_id", | |
3859 | Integer(), ForeignKey('repo_review_rules.repo_review_rule_id')) |
|
3863 | Integer(), ForeignKey('repo_review_rules.repo_review_rule_id')) | |
3860 | users_group_id = Column("users_group_id", Integer(), |
|
3864 | users_group_id = Column("users_group_id", Integer(), | |
3861 | ForeignKey('users_groups.users_group_id'), nullable=False) |
|
3865 | ForeignKey('users_groups.users_group_id'), nullable=False) | |
3862 | users_group = relationship('UserGroup') |
|
3866 | users_group = relationship('UserGroup') | |
3863 |
|
3867 | |||
3864 |
|
3868 | |||
3865 | class RepoReviewRule(Base, BaseModel): |
|
3869 | class RepoReviewRule(Base, BaseModel): | |
3866 | __tablename__ = 'repo_review_rules' |
|
3870 | __tablename__ = 'repo_review_rules' | |
3867 | __table_args__ = ( |
|
3871 | __table_args__ = ( | |
3868 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3872 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3869 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,} |
|
3873 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,} | |
3870 | ) |
|
3874 | ) | |
3871 |
|
3875 | |||
3872 | repo_review_rule_id = Column( |
|
3876 | repo_review_rule_id = Column( | |
3873 | 'repo_review_rule_id', Integer(), primary_key=True) |
|
3877 | 'repo_review_rule_id', Integer(), primary_key=True) | |
3874 | repo_id = Column( |
|
3878 | repo_id = Column( | |
3875 | "repo_id", Integer(), ForeignKey('repositories.repo_id')) |
|
3879 | "repo_id", Integer(), ForeignKey('repositories.repo_id')) | |
3876 | repo = relationship('Repository', backref='review_rules') |
|
3880 | repo = relationship('Repository', backref='review_rules') | |
3877 |
|
3881 | |||
3878 | _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), |
|
3882 | _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), | |
3879 | default=u'*') # glob |
|
3883 | default=u'*') # glob | |
3880 | _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), |
|
3884 | _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), | |
3881 | default=u'*') # glob |
|
3885 | default=u'*') # glob | |
3882 |
|
3886 | |||
3883 | use_authors_for_review = Column("use_authors_for_review", Boolean(), |
|
3887 | use_authors_for_review = Column("use_authors_for_review", Boolean(), | |
3884 | nullable=False, default=False) |
|
3888 | nullable=False, default=False) | |
3885 | rule_users = relationship('RepoReviewRuleUser') |
|
3889 | rule_users = relationship('RepoReviewRuleUser') | |
3886 | rule_user_groups = relationship('RepoReviewRuleUserGroup') |
|
3890 | rule_user_groups = relationship('RepoReviewRuleUserGroup') | |
3887 |
|
3891 | |||
3888 | @hybrid_property |
|
3892 | @hybrid_property | |
3889 | def branch_pattern(self): |
|
3893 | def branch_pattern(self): | |
3890 | return self._branch_pattern or '*' |
|
3894 | return self._branch_pattern or '*' | |
3891 |
|
3895 | |||
3892 | def _validate_glob(self, value): |
|
3896 | def _validate_glob(self, value): | |
3893 | re.compile('^' + glob2re(value) + '$') |
|
3897 | re.compile('^' + glob2re(value) + '$') | |
3894 |
|
3898 | |||
3895 | @branch_pattern.setter |
|
3899 | @branch_pattern.setter | |
3896 | def branch_pattern(self, value): |
|
3900 | def branch_pattern(self, value): | |
3897 | self._validate_glob(value) |
|
3901 | self._validate_glob(value) | |
3898 | self._branch_pattern = value or '*' |
|
3902 | self._branch_pattern = value or '*' | |
3899 |
|
3903 | |||
3900 | @hybrid_property |
|
3904 | @hybrid_property | |
3901 | def file_pattern(self): |
|
3905 | def file_pattern(self): | |
3902 | return self._file_pattern or '*' |
|
3906 | return self._file_pattern or '*' | |
3903 |
|
3907 | |||
3904 | @file_pattern.setter |
|
3908 | @file_pattern.setter | |
3905 | def file_pattern(self, value): |
|
3909 | def file_pattern(self, value): | |
3906 | self._validate_glob(value) |
|
3910 | self._validate_glob(value) | |
3907 | self._file_pattern = value or '*' |
|
3911 | self._file_pattern = value or '*' | |
3908 |
|
3912 | |||
3909 | def matches(self, branch, files_changed): |
|
3913 | def matches(self, branch, files_changed): | |
3910 | """ |
|
3914 | """ | |
3911 | Check if this review rule matches a branch/files in a pull request |
|
3915 | Check if this review rule matches a branch/files in a pull request | |
3912 |
|
3916 | |||
3913 | :param branch: branch name for the commit |
|
3917 | :param branch: branch name for the commit | |
3914 | :param files_changed: list of file paths changed in the pull request |
|
3918 | :param files_changed: list of file paths changed in the pull request | |
3915 | """ |
|
3919 | """ | |
3916 |
|
3920 | |||
3917 | branch = branch or '' |
|
3921 | branch = branch or '' | |
3918 | files_changed = files_changed or [] |
|
3922 | files_changed = files_changed or [] | |
3919 |
|
3923 | |||
3920 | branch_matches = True |
|
3924 | branch_matches = True | |
3921 | if branch: |
|
3925 | if branch: | |
3922 | branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$') |
|
3926 | branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$') | |
3923 | branch_matches = bool(branch_regex.search(branch)) |
|
3927 | branch_matches = bool(branch_regex.search(branch)) | |
3924 |
|
3928 | |||
3925 | files_matches = True |
|
3929 | files_matches = True | |
3926 | if self.file_pattern != '*': |
|
3930 | if self.file_pattern != '*': | |
3927 | files_matches = False |
|
3931 | files_matches = False | |
3928 | file_regex = re.compile(glob2re(self.file_pattern)) |
|
3932 | file_regex = re.compile(glob2re(self.file_pattern)) | |
3929 | for filename in files_changed: |
|
3933 | for filename in files_changed: | |
3930 | if file_regex.search(filename): |
|
3934 | if file_regex.search(filename): | |
3931 | files_matches = True |
|
3935 | files_matches = True | |
3932 | break |
|
3936 | break | |
3933 |
|
3937 | |||
3934 | return branch_matches and files_matches |
|
3938 | return branch_matches and files_matches | |
3935 |
|
3939 | |||
3936 | @property |
|
3940 | @property | |
3937 | def review_users(self): |
|
3941 | def review_users(self): | |
3938 | """ Returns the users which this rule applies to """ |
|
3942 | """ Returns the users which this rule applies to """ | |
3939 |
|
3943 | |||
3940 | users = set() |
|
3944 | users = set() | |
3941 | users |= set([ |
|
3945 | users |= set([ | |
3942 | rule_user.user for rule_user in self.rule_users |
|
3946 | rule_user.user for rule_user in self.rule_users | |
3943 | if rule_user.user.active]) |
|
3947 | if rule_user.user.active]) | |
3944 | users |= set( |
|
3948 | users |= set( | |
3945 | member.user |
|
3949 | member.user | |
3946 | for rule_user_group in self.rule_user_groups |
|
3950 | for rule_user_group in self.rule_user_groups | |
3947 | for member in rule_user_group.users_group.members |
|
3951 | for member in rule_user_group.users_group.members | |
3948 | if member.user.active |
|
3952 | if member.user.active | |
3949 | ) |
|
3953 | ) | |
3950 | return users |
|
3954 | return users | |
3951 |
|
3955 | |||
3952 | def __repr__(self): |
|
3956 | def __repr__(self): | |
3953 | return '<RepoReviewerRule(id=%r, repo=%r)>' % ( |
|
3957 | return '<RepoReviewerRule(id=%r, repo=%r)>' % ( | |
3954 | self.repo_review_rule_id, self.repo) |
|
3958 | self.repo_review_rule_id, self.repo) | |
3955 |
|
3959 | |||
3956 |
|
3960 | |||
3957 | class DbMigrateVersion(Base, BaseModel): |
|
3961 | class DbMigrateVersion(Base, BaseModel): | |
3958 | __tablename__ = 'db_migrate_version' |
|
3962 | __tablename__ = 'db_migrate_version' | |
3959 | __table_args__ = ( |
|
3963 | __table_args__ = ( | |
3960 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3964 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3961 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3965 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
3962 | ) |
|
3966 | ) | |
3963 | repository_id = Column('repository_id', String(250), primary_key=True) |
|
3967 | repository_id = Column('repository_id', String(250), primary_key=True) | |
3964 | repository_path = Column('repository_path', Text) |
|
3968 | repository_path = Column('repository_path', Text) | |
3965 | version = Column('version', Integer) |
|
3969 | version = Column('version', Integer) | |
3966 |
|
3970 | |||
3967 |
|
3971 | |||
3968 | class DbSession(Base, BaseModel): |
|
3972 | class DbSession(Base, BaseModel): | |
3969 | __tablename__ = 'db_session' |
|
3973 | __tablename__ = 'db_session' | |
3970 | __table_args__ = ( |
|
3974 | __table_args__ = ( | |
3971 | {'extend_existing': True, 'mysql_engine': 'InnoDB', |
|
3975 | {'extend_existing': True, 'mysql_engine': 'InnoDB', | |
3972 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, |
|
3976 | 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}, | |
3973 | ) |
|
3977 | ) | |
3974 |
|
3978 | |||
3975 | def __repr__(self): |
|
3979 | def __repr__(self): | |
3976 | return '<DB:DbSession({})>'.format(self.id) |
|
3980 | return '<DB:DbSession({})>'.format(self.id) | |
3977 |
|
3981 | |||
3978 | id = Column('id', Integer()) |
|
3982 | id = Column('id', Integer()) | |
3979 | namespace = Column('namespace', String(255), primary_key=True) |
|
3983 | namespace = Column('namespace', String(255), primary_key=True) | |
3980 | accessed = Column('accessed', DateTime, nullable=False) |
|
3984 | accessed = Column('accessed', DateTime, nullable=False) | |
3981 | created = Column('created', DateTime, nullable=False) |
|
3985 | created = Column('created', DateTime, nullable=False) | |
3982 | data = Column('data', PickleType, nullable=False) |
|
3986 | data = Column('data', PickleType, nullable=False) |
General Comments 0
You need to be logged in to leave comments.
Login now