##// END OF EJS Templates
users: description edit fixes...
marcink -
r4024:dbba29ef default
parent child Browse files
Show More
@@ -1,206 +1,207 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import mock
22 22 import pytest
23 23
24 24 from rhodecode.lib.auth import check_password
25 25 from rhodecode.model.user import UserModel
26 26 from rhodecode.tests import (
27 27 TEST_USER_ADMIN_LOGIN, TEST_USER_REGULAR_EMAIL)
28 28 from rhodecode.api.tests.utils import (
29 29 build_data, api_call, assert_ok, assert_error, jsonify, crash)
30 30 from rhodecode.tests.fixture import Fixture
31 31 from rhodecode.model.db import RepoGroup
32 32
33 33
34 34 # TODO: mikhail: remove fixture from here
35 35 fixture = Fixture()
36 36
37 37
38 38 @pytest.mark.usefixtures("testuser_api", "app")
39 39 class TestCreateUser(object):
40 40 def test_api_create_existing_user(self):
41 41 id_, params = build_data(
42 42 self.apikey, 'create_user',
43 43 username=TEST_USER_ADMIN_LOGIN,
44 44 email='test@foo.com',
45 45 password='trololo')
46 46 response = api_call(self.app, params)
47 47
48 48 expected = "user `%s` already exist" % (TEST_USER_ADMIN_LOGIN,)
49 49 assert_error(id_, expected, given=response.body)
50 50
51 51 def test_api_create_user_with_existing_email(self):
52 52 id_, params = build_data(
53 53 self.apikey, 'create_user',
54 54 username=TEST_USER_ADMIN_LOGIN + 'new',
55 55 email=TEST_USER_REGULAR_EMAIL,
56 56 password='trololo')
57 57 response = api_call(self.app, params)
58 58
59 59 expected = "email `%s` already exist" % (TEST_USER_REGULAR_EMAIL,)
60 60 assert_error(id_, expected, given=response.body)
61 61
62 62 def test_api_create_user_with_wrong_username(self):
63 63 bad_username = '<> HELLO WORLD <>'
64 64 id_, params = build_data(
65 65 self.apikey, 'create_user',
66 66 username=bad_username,
67 67 email='new@email.com',
68 68 password='trololo')
69 69 response = api_call(self.app, params)
70 70
71 71 expected = {'username':
72 72 "Username may only contain alphanumeric characters "
73 73 "underscores, periods or dashes and must begin with "
74 74 "alphanumeric character or underscore"}
75 75 assert_error(id_, expected, given=response.body)
76 76
77 77 def test_api_create_user(self):
78 78 username = 'test_new_api_user'
79 79 email = username + "@foo.com"
80 80
81 81 id_, params = build_data(
82 82 self.apikey, 'create_user',
83 83 username=username,
84 84 email=email,
85 description='CTO of Things',
85 86 password='example')
86 87 response = api_call(self.app, params)
87 88
88 89 usr = UserModel().get_by_username(username)
89 90 ret = {
90 91 'msg': 'created new user `%s`' % (username,),
91 92 'user': jsonify(usr.get_api_data(include_secrets=True)),
92 93 }
93 94 try:
94 95 expected = ret
95 96 assert check_password('example', usr.password)
96 97 assert_ok(id_, expected, given=response.body)
97 98 finally:
98 99 fixture.destroy_user(usr.user_id)
99 100
100 101 def test_api_create_user_without_password(self):
101 102 username = 'test_new_api_user_passwordless'
102 103 email = username + "@foo.com"
103 104
104 105 id_, params = build_data(
105 106 self.apikey, 'create_user',
106 107 username=username,
107 108 email=email)
108 109 response = api_call(self.app, params)
109 110
110 111 usr = UserModel().get_by_username(username)
111 112 ret = {
112 113 'msg': 'created new user `%s`' % (username,),
113 114 'user': jsonify(usr.get_api_data(include_secrets=True)),
114 115 }
115 116 try:
116 117 expected = ret
117 118 assert_ok(id_, expected, given=response.body)
118 119 finally:
119 120 fixture.destroy_user(usr.user_id)
120 121
121 122 def test_api_create_user_with_extern_name(self):
122 123 username = 'test_new_api_user_passwordless'
123 124 email = username + "@foo.com"
124 125
125 126 id_, params = build_data(
126 127 self.apikey, 'create_user',
127 128 username=username,
128 129 email=email, extern_name='rhodecode')
129 130 response = api_call(self.app, params)
130 131
131 132 usr = UserModel().get_by_username(username)
132 133 ret = {
133 134 'msg': 'created new user `%s`' % (username,),
134 135 'user': jsonify(usr.get_api_data(include_secrets=True)),
135 136 }
136 137 try:
137 138 expected = ret
138 139 assert_ok(id_, expected, given=response.body)
139 140 finally:
140 141 fixture.destroy_user(usr.user_id)
141 142
142 143 def test_api_create_user_with_password_change(self):
143 144 username = 'test_new_api_user_password_change'
144 145 email = username + "@foo.com"
145 146
146 147 id_, params = build_data(
147 148 self.apikey, 'create_user',
148 149 username=username,
149 150 email=email, extern_name='rhodecode',
150 151 force_password_change=True)
151 152 response = api_call(self.app, params)
152 153
153 154 usr = UserModel().get_by_username(username)
154 155 ret = {
155 156 'msg': 'created new user `%s`' % (username,),
156 157 'user': jsonify(usr.get_api_data(include_secrets=True)),
157 158 }
158 159 try:
159 160 expected = ret
160 161 assert_ok(id_, expected, given=response.body)
161 162 finally:
162 163 fixture.destroy_user(usr.user_id)
163 164
164 165 def test_api_create_user_with_personal_repo_group(self):
165 166 username = 'test_new_api_user_personal_group'
166 167 email = username + "@foo.com"
167 168
168 169 id_, params = build_data(
169 170 self.apikey, 'create_user',
170 171 username=username,
171 172 email=email, extern_name='rhodecode',
172 173 create_personal_repo_group=True)
173 174 response = api_call(self.app, params)
174 175
175 176 usr = UserModel().get_by_username(username)
176 177 ret = {
177 178 'msg': 'created new user `%s`' % (username,),
178 179 'user': jsonify(usr.get_api_data(include_secrets=True)),
179 180 }
180 181
181 182 personal_group = RepoGroup.get_by_group_name(username)
182 183 assert personal_group
183 184 assert personal_group.personal == True
184 185 assert personal_group.user.username == username
185 186
186 187 try:
187 188 expected = ret
188 189 assert_ok(id_, expected, given=response.body)
189 190 finally:
190 191 fixture.destroy_repo_group(username)
191 192 fixture.destroy_user(usr.user_id)
192 193
193 194 @mock.patch.object(UserModel, 'create_or_update', crash)
194 195 def test_api_create_user_when_exception_happened(self):
195 196
196 197 username = 'test_new_api_user'
197 198 email = username + "@foo.com"
198 199
199 200 id_, params = build_data(
200 201 self.apikey, 'create_user',
201 202 username=username,
202 203 email=email,
203 204 password='trololo')
204 205 response = api_call(self.app, params)
205 206 expected = 'failed to create user `%s`' % (username,)
206 207 assert_error(id_, expected, given=response.body)
@@ -1,120 +1,121 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import mock
22 22 import pytest
23 23
24 24 from rhodecode.model.db import User
25 25 from rhodecode.model.user import UserModel
26 26 from rhodecode.tests import TEST_USER_ADMIN_LOGIN
27 27 from rhodecode.api.tests.utils import (
28 28 build_data, api_call, assert_ok, assert_error, crash, jsonify)
29 29
30 30
31 31 @pytest.mark.usefixtures("testuser_api", "app")
32 32 class TestUpdateUser(object):
33 33 @pytest.mark.parametrize("name, expected", [
34 34 ('firstname', 'new_username'),
35 35 ('lastname', 'new_username'),
36 36 ('email', 'new_username'),
37 37 ('admin', True),
38 38 ('admin', False),
39 39 ('extern_type', 'ldap'),
40 40 ('extern_type', None),
41 41 ('extern_name', 'test'),
42 42 ('extern_name', None),
43 43 ('active', False),
44 44 ('active', True),
45 ('password', 'newpass')
45 ('password', 'newpass'),
46 ('description', 'CTO 4 Life')
46 47 ])
47 48 def test_api_update_user(self, name, expected, user_util):
48 49 usr = user_util.create_user()
49 50
50 51 kw = {name: expected, 'userid': usr.user_id}
51 52 id_, params = build_data(self.apikey, 'update_user', **kw)
52 53 response = api_call(self.app, params)
53 54
54 55 ret = {
55 56 'msg': 'updated user ID:%s %s' % (usr.user_id, usr.username),
56 57 'user': jsonify(
57 58 UserModel()
58 59 .get_by_username(usr.username)
59 60 .get_api_data(include_secrets=True)
60 61 )
61 62 }
62 63
63 64 expected = ret
64 65 assert_ok(id_, expected, given=response.body)
65 66
66 67 def test_api_update_user_no_changed_params(self):
67 68 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
68 69 ret = jsonify(usr.get_api_data(include_secrets=True))
69 70 id_, params = build_data(
70 71 self.apikey, 'update_user', userid=TEST_USER_ADMIN_LOGIN)
71 72
72 73 response = api_call(self.app, params)
73 74 ret = {
74 75 'msg': 'updated user ID:%s %s' % (
75 76 usr.user_id, TEST_USER_ADMIN_LOGIN),
76 77 'user': ret
77 78 }
78 79 expected = ret
79 80 expected['user']['last_activity'] = response.json['result']['user'][
80 81 'last_activity']
81 82 assert_ok(id_, expected, given=response.body)
82 83
83 84 def test_api_update_user_by_user_id(self):
84 85 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
85 86 ret = jsonify(usr.get_api_data(include_secrets=True))
86 87 id_, params = build_data(
87 88 self.apikey, 'update_user', userid=usr.user_id)
88 89
89 90 response = api_call(self.app, params)
90 91 ret = {
91 92 'msg': 'updated user ID:%s %s' % (
92 93 usr.user_id, TEST_USER_ADMIN_LOGIN),
93 94 'user': ret
94 95 }
95 96 expected = ret
96 97 expected['user']['last_activity'] = response.json['result']['user'][
97 98 'last_activity']
98 99 assert_ok(id_, expected, given=response.body)
99 100
100 101 def test_api_update_user_default_user(self):
101 102 usr = User.get_default_user()
102 103 id_, params = build_data(
103 104 self.apikey, 'update_user', userid=usr.user_id)
104 105
105 106 response = api_call(self.app, params)
106 107 expected = 'editing default user is forbidden'
107 108 assert_error(id_, expected, given=response.body)
108 109
109 110 @mock.patch.object(UserModel, 'update_user', crash)
110 111 def test_api_update_user_when_exception_happens(self):
111 112 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
112 113 ret = jsonify(usr.get_api_data(include_secrets=True))
113 114 id_, params = build_data(
114 115 self.apikey, 'update_user', userid=usr.user_id)
115 116
116 117 response = api_call(self.app, params)
117 118 ret = 'failed to update user `%s`' % (usr.user_id,)
118 119
119 120 expected = ret
120 121 assert_error(id_, expected, given=response.body)
@@ -1,564 +1,573 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 from pyramid import compat
23 23
24 24 from rhodecode.api import (
25 25 jsonrpc_method, JSONRPCError, JSONRPCForbidden, JSONRPCValidationError)
26 26 from rhodecode.api.utils import (
27 27 Optional, OAttr, has_superadmin_permission, get_user_or_error, store_update)
28 28 from rhodecode.lib import audit_logger
29 29 from rhodecode.lib.auth import AuthUser, PasswordGenerator
30 30 from rhodecode.lib.exceptions import DefaultUserException
31 31 from rhodecode.lib.utils2 import safe_int, str2bool
32 32 from rhodecode.model.db import Session, User, Repository
33 33 from rhodecode.model.user import UserModel
34 34 from rhodecode.model import validation_schema
35 35 from rhodecode.model.validation_schema.schemas import user_schema
36 36
37 37 log = logging.getLogger(__name__)
38 38
39 39
40 40 @jsonrpc_method()
41 41 def get_user(request, apiuser, userid=Optional(OAttr('apiuser'))):
42 42 """
43 43 Returns the information associated with a username or userid.
44 44
45 45 * If the ``userid`` is not set, this command returns the information
46 46 for the ``userid`` calling the method.
47 47
48 48 .. note::
49 49
50 50 Normal users may only run this command against their ``userid``. For
51 51 full privileges you must run this command using an |authtoken| with
52 52 admin rights.
53 53
54 54 :param apiuser: This is filled automatically from the |authtoken|.
55 55 :type apiuser: AuthUser
56 56 :param userid: Sets the userid for which data will be returned.
57 57 :type userid: Optional(str or int)
58 58
59 59 Example output:
60 60
61 61 .. code-block:: bash
62 62
63 63 {
64 64 "error": null,
65 65 "id": <id>,
66 66 "result": {
67 67 "active": true,
68 68 "admin": false,
69 69 "api_keys": [ list of keys ],
70 70 "auth_tokens": [ list of tokens with details ],
71 71 "email": "user@example.com",
72 72 "emails": [
73 73 "user@example.com"
74 74 ],
75 75 "extern_name": "rhodecode",
76 76 "extern_type": "rhodecode",
77 77 "firstname": "username",
78 "description": "user description",
78 79 "ip_addresses": [],
79 80 "language": null,
80 81 "last_login": "Timestamp",
81 82 "last_activity": "Timestamp",
82 83 "lastname": "surnae",
83 84 "permissions": <deprecated>,
84 85 "permissions_summary": {
85 86 "global": [
86 87 "hg.inherit_default_perms.true",
87 88 "usergroup.read",
88 89 "hg.repogroup.create.false",
89 90 "hg.create.none",
90 91 "hg.password_reset.enabled",
91 92 "hg.extern_activate.manual",
92 93 "hg.create.write_on_repogroup.false",
93 94 "hg.usergroup.create.false",
94 95 "group.none",
95 96 "repository.none",
96 97 "hg.register.none",
97 98 "hg.fork.repository"
98 99 ],
99 100 "repositories": { "username/example": "repository.write"},
100 101 "repositories_groups": { "user-group/repo": "group.none" },
101 102 "user_groups": { "user_group_name": "usergroup.read" }
102 103 }
103 104 "user_id": 32,
104 105 "username": "username"
105 106 }
106 107 }
107 108 """
108 109
109 110 if not has_superadmin_permission(apiuser):
110 111 # make sure normal user does not pass someone else userid,
111 112 # he is not allowed to do that
112 113 if not isinstance(userid, Optional) and userid != apiuser.user_id:
113 114 raise JSONRPCError('userid is not the same as your user')
114 115
115 116 userid = Optional.extract(userid, evaluate_locals=locals())
116 117 userid = getattr(userid, 'user_id', userid)
117 118
118 119 user = get_user_or_error(userid)
119 120 data = user.get_api_data(include_secrets=True)
120 121 permissions = AuthUser(user_id=user.user_id).permissions
121 122 data['permissions'] = permissions # TODO(marcink): should be deprecated
122 123 data['permissions_summary'] = permissions
123 124 return data
124 125
125 126
126 127 @jsonrpc_method()
127 128 def get_users(request, apiuser):
128 129 """
129 130 Lists all users in the |RCE| user database.
130 131
131 132 This command can only be run using an |authtoken| with admin rights to
132 133 the specified repository.
133 134
134 135 This command takes the following options:
135 136
136 137 :param apiuser: This is filled automatically from the |authtoken|.
137 138 :type apiuser: AuthUser
138 139
139 140 Example output:
140 141
141 142 .. code-block:: bash
142 143
143 144 id : <id_given_in_input>
144 145 result: [<user_object>, ...]
145 146 error: null
146 147 """
147 148
148 149 if not has_superadmin_permission(apiuser):
149 150 raise JSONRPCForbidden()
150 151
151 152 result = []
152 153 users_list = User.query().order_by(User.username) \
153 154 .filter(User.username != User.DEFAULT_USER) \
154 155 .all()
155 156 for user in users_list:
156 157 result.append(user.get_api_data(include_secrets=True))
157 158 return result
158 159
159 160
160 161 @jsonrpc_method()
161 162 def create_user(request, apiuser, username, email, password=Optional(''),
162 firstname=Optional(''), lastname=Optional(''),
163 firstname=Optional(''), lastname=Optional(''), description=Optional(''),
163 164 active=Optional(True), admin=Optional(False),
164 165 extern_name=Optional('rhodecode'),
165 166 extern_type=Optional('rhodecode'),
166 167 force_password_change=Optional(False),
167 168 create_personal_repo_group=Optional(None)):
168 169 """
169 170 Creates a new user and returns the new user object.
170 171
171 172 This command can only be run using an |authtoken| with admin rights to
172 173 the specified repository.
173 174
174 175 This command takes the following options:
175 176
176 177 :param apiuser: This is filled automatically from the |authtoken|.
177 178 :type apiuser: AuthUser
178 179 :param username: Set the new username.
179 180 :type username: str or int
180 181 :param email: Set the user email address.
181 182 :type email: str
182 183 :param password: Set the new user password.
183 184 :type password: Optional(str)
184 185 :param firstname: Set the new user firstname.
185 186 :type firstname: Optional(str)
186 187 :param lastname: Set the new user surname.
187 188 :type lastname: Optional(str)
189 :param description: Set user description, or short bio. Metatags are allowed.
190 :type description: Optional(str)
188 191 :param active: Set the user as active.
189 192 :type active: Optional(``True`` | ``False``)
190 193 :param admin: Give the new user admin rights.
191 194 :type admin: Optional(``True`` | ``False``)
192 195 :param extern_name: Set the authentication plugin name.
193 196 Using LDAP this is filled with LDAP UID.
194 197 :type extern_name: Optional(str)
195 198 :param extern_type: Set the new user authentication plugin.
196 199 :type extern_type: Optional(str)
197 200 :param force_password_change: Force the new user to change password
198 201 on next login.
199 202 :type force_password_change: Optional(``True`` | ``False``)
200 203 :param create_personal_repo_group: Create personal repo group for this user
201 204 :type create_personal_repo_group: Optional(``True`` | ``False``)
202 205
203 206 Example output:
204 207
205 208 .. code-block:: bash
206 209
207 210 id : <id_given_in_input>
208 211 result: {
209 212 "msg" : "created new user `<username>`",
210 213 "user": <user_obj>
211 214 }
212 215 error: null
213 216
214 217 Example error output:
215 218
216 219 .. code-block:: bash
217 220
218 221 id : <id_given_in_input>
219 222 result : null
220 223 error : {
221 224 "user `<username>` already exist"
222 225 or
223 226 "email `<email>` already exist"
224 227 or
225 228 "failed to create user `<username>`"
226 229 }
227 230
228 231 """
229 232 if not has_superadmin_permission(apiuser):
230 233 raise JSONRPCForbidden()
231 234
232 235 if UserModel().get_by_username(username):
233 236 raise JSONRPCError("user `%s` already exist" % (username,))
234 237
235 238 if UserModel().get_by_email(email, case_insensitive=True):
236 239 raise JSONRPCError("email `%s` already exist" % (email,))
237 240
238 241 # generate random password if we actually given the
239 242 # extern_name and it's not rhodecode
240 243 if (not isinstance(extern_name, Optional) and
241 244 Optional.extract(extern_name) != 'rhodecode'):
242 245 # generate temporary password if user is external
243 246 password = PasswordGenerator().gen_password(length=16)
244 247 create_repo_group = Optional.extract(create_personal_repo_group)
245 248 if isinstance(create_repo_group, compat.string_types):
246 249 create_repo_group = str2bool(create_repo_group)
247 250
248 251 username = Optional.extract(username)
249 252 password = Optional.extract(password)
250 253 email = Optional.extract(email)
251 254 first_name = Optional.extract(firstname)
252 255 last_name = Optional.extract(lastname)
256 description = Optional.extract(description)
253 257 active = Optional.extract(active)
254 258 admin = Optional.extract(admin)
255 259 extern_type = Optional.extract(extern_type)
256 260 extern_name = Optional.extract(extern_name)
257 261
258 262 schema = user_schema.UserSchema().bind(
259 263 # user caller
260 264 user=apiuser)
261 265 try:
262 266 schema_data = schema.deserialize(dict(
263 267 username=username,
264 268 email=email,
265 269 password=password,
266 270 first_name=first_name,
267 271 last_name=last_name,
268 272 active=active,
269 273 admin=admin,
274 description=description,
270 275 extern_type=extern_type,
271 276 extern_name=extern_name,
272 277 ))
273 278 except validation_schema.Invalid as err:
274 279 raise JSONRPCValidationError(colander_exc=err)
275 280
276 281 try:
277 282 user = UserModel().create_or_update(
278 283 username=schema_data['username'],
279 284 password=schema_data['password'],
280 285 email=schema_data['email'],
281 286 firstname=schema_data['first_name'],
282 287 lastname=schema_data['last_name'],
288 description=schema_data['description'],
283 289 active=schema_data['active'],
284 290 admin=schema_data['admin'],
285 291 extern_type=schema_data['extern_type'],
286 292 extern_name=schema_data['extern_name'],
287 293 force_password_change=Optional.extract(force_password_change),
288 294 create_repo_group=create_repo_group
289 295 )
290 296 Session().flush()
291 297 creation_data = user.get_api_data()
292 298 audit_logger.store_api(
293 299 'user.create', action_data={'data': creation_data},
294 300 user=apiuser)
295 301
296 302 Session().commit()
297 303 return {
298 304 'msg': 'created new user `%s`' % username,
299 305 'user': user.get_api_data(include_secrets=True)
300 306 }
301 307 except Exception:
302 308 log.exception('Error occurred during creation of user')
303 309 raise JSONRPCError('failed to create user `%s`' % (username,))
304 310
305 311
306 312 @jsonrpc_method()
307 313 def update_user(request, apiuser, userid, username=Optional(None),
308 314 email=Optional(None), password=Optional(None),
309 315 firstname=Optional(None), lastname=Optional(None),
310 active=Optional(None), admin=Optional(None),
316 description=Optional(None), active=Optional(None), admin=Optional(None),
311 317 extern_type=Optional(None), extern_name=Optional(None), ):
312 318 """
313 319 Updates the details for the specified user, if that user exists.
314 320
315 321 This command can only be run using an |authtoken| with admin rights to
316 322 the specified repository.
317 323
318 324 This command takes the following options:
319 325
320 326 :param apiuser: This is filled automatically from |authtoken|.
321 327 :type apiuser: AuthUser
322 328 :param userid: Set the ``userid`` to update.
323 329 :type userid: str or int
324 330 :param username: Set the new username.
325 331 :type username: str or int
326 332 :param email: Set the new email.
327 333 :type email: str
328 334 :param password: Set the new password.
329 335 :type password: Optional(str)
330 336 :param firstname: Set the new first name.
331 337 :type firstname: Optional(str)
332 338 :param lastname: Set the new surname.
333 339 :type lastname: Optional(str)
340 :param description: Set user description, or short bio. Metatags are allowed.
341 :type description: Optional(str)
334 342 :param active: Set the new user as active.
335 343 :type active: Optional(``True`` | ``False``)
336 344 :param admin: Give the user admin rights.
337 345 :type admin: Optional(``True`` | ``False``)
338 346 :param extern_name: Set the authentication plugin user name.
339 347 Using LDAP this is filled with LDAP UID.
340 348 :type extern_name: Optional(str)
341 349 :param extern_type: Set the authentication plugin type.
342 350 :type extern_type: Optional(str)
343 351
344 352
345 353 Example output:
346 354
347 355 .. code-block:: bash
348 356
349 357 id : <id_given_in_input>
350 358 result: {
351 359 "msg" : "updated user ID:<userid> <username>",
352 360 "user": <user_object>,
353 361 }
354 362 error: null
355 363
356 364 Example error output:
357 365
358 366 .. code-block:: bash
359 367
360 368 id : <id_given_in_input>
361 369 result : null
362 370 error : {
363 371 "failed to update user `<username>`"
364 372 }
365 373
366 374 """
367 375 if not has_superadmin_permission(apiuser):
368 376 raise JSONRPCForbidden()
369 377
370 378 user = get_user_or_error(userid)
371 379 old_data = user.get_api_data()
372 380 # only non optional arguments will be stored in updates
373 381 updates = {}
374 382
375 383 try:
376 384
377 385 store_update(updates, username, 'username')
378 386 store_update(updates, password, 'password')
379 387 store_update(updates, email, 'email')
380 388 store_update(updates, firstname, 'name')
381 389 store_update(updates, lastname, 'lastname')
390 store_update(updates, description, 'description')
382 391 store_update(updates, active, 'active')
383 392 store_update(updates, admin, 'admin')
384 393 store_update(updates, extern_name, 'extern_name')
385 394 store_update(updates, extern_type, 'extern_type')
386 395
387 396 user = UserModel().update_user(user, **updates)
388 397 audit_logger.store_api(
389 398 'user.edit', action_data={'old_data': old_data},
390 399 user=apiuser)
391 400 Session().commit()
392 401 return {
393 402 'msg': 'updated user ID:%s %s' % (user.user_id, user.username),
394 403 'user': user.get_api_data(include_secrets=True)
395 404 }
396 405 except DefaultUserException:
397 406 log.exception("Default user edit exception")
398 407 raise JSONRPCError('editing default user is forbidden')
399 408 except Exception:
400 409 log.exception("Error occurred during update of user")
401 410 raise JSONRPCError('failed to update user `%s`' % (userid,))
402 411
403 412
404 413 @jsonrpc_method()
405 414 def delete_user(request, apiuser, userid):
406 415 """
407 416 Deletes the specified user from the |RCE| user database.
408 417
409 418 This command can only be run using an |authtoken| with admin rights to
410 419 the specified repository.
411 420
412 421 .. important::
413 422
414 423 Ensure all open pull requests and open code review
415 424 requests to this user are close.
416 425
417 426 Also ensure all repositories, or repository groups owned by this
418 427 user are reassigned before deletion.
419 428
420 429 This command takes the following options:
421 430
422 431 :param apiuser: This is filled automatically from the |authtoken|.
423 432 :type apiuser: AuthUser
424 433 :param userid: Set the user to delete.
425 434 :type userid: str or int
426 435
427 436 Example output:
428 437
429 438 .. code-block:: bash
430 439
431 440 id : <id_given_in_input>
432 441 result: {
433 442 "msg" : "deleted user ID:<userid> <username>",
434 443 "user": null
435 444 }
436 445 error: null
437 446
438 447 Example error output:
439 448
440 449 .. code-block:: bash
441 450
442 451 id : <id_given_in_input>
443 452 result : null
444 453 error : {
445 454 "failed to delete user ID:<userid> <username>"
446 455 }
447 456
448 457 """
449 458 if not has_superadmin_permission(apiuser):
450 459 raise JSONRPCForbidden()
451 460
452 461 user = get_user_or_error(userid)
453 462 old_data = user.get_api_data()
454 463 try:
455 464 UserModel().delete(userid)
456 465 audit_logger.store_api(
457 466 'user.delete', action_data={'old_data': old_data},
458 467 user=apiuser)
459 468
460 469 Session().commit()
461 470 return {
462 471 'msg': 'deleted user ID:%s %s' % (user.user_id, user.username),
463 472 'user': None
464 473 }
465 474 except Exception:
466 475 log.exception("Error occurred during deleting of user")
467 476 raise JSONRPCError(
468 477 'failed to delete user ID:%s %s' % (user.user_id, user.username))
469 478
470 479
471 480 @jsonrpc_method()
472 481 def get_user_locks(request, apiuser, userid=Optional(OAttr('apiuser'))):
473 482 """
474 483 Displays all repositories locked by the specified user.
475 484
476 485 * If this command is run by a non-admin user, it returns
477 486 a list of |repos| locked by that user.
478 487
479 488 This command takes the following options:
480 489
481 490 :param apiuser: This is filled automatically from the |authtoken|.
482 491 :type apiuser: AuthUser
483 492 :param userid: Sets the userid whose list of locked |repos| will be
484 493 displayed.
485 494 :type userid: Optional(str or int)
486 495
487 496 Example output:
488 497
489 498 .. code-block:: bash
490 499
491 500 id : <id_given_in_input>
492 501 result : {
493 502 [repo_object, repo_object,...]
494 503 }
495 504 error : null
496 505 """
497 506
498 507 include_secrets = False
499 508 if not has_superadmin_permission(apiuser):
500 509 # make sure normal user does not pass someone else userid,
501 510 # he is not allowed to do that
502 511 if not isinstance(userid, Optional) and userid != apiuser.user_id:
503 512 raise JSONRPCError('userid is not the same as your user')
504 513 else:
505 514 include_secrets = True
506 515
507 516 userid = Optional.extract(userid, evaluate_locals=locals())
508 517 userid = getattr(userid, 'user_id', userid)
509 518 user = get_user_or_error(userid)
510 519
511 520 ret = []
512 521
513 522 # show all locks
514 523 for r in Repository.getAll():
515 524 _user_id, _time, _reason = r.locked
516 525 if _user_id and _time:
517 526 _api_data = r.get_api_data(include_secrets=include_secrets)
518 527 # if we use user filter just show the locks for this user
519 528 if safe_int(_user_id) == user.user_id:
520 529 ret.append(_api_data)
521 530
522 531 return ret
523 532
524 533
525 534 @jsonrpc_method()
526 535 def get_user_audit_logs(request, apiuser, userid=Optional(OAttr('apiuser'))):
527 536 """
528 537 Fetches all action logs made by the specified user.
529 538
530 539 This command takes the following options:
531 540
532 541 :param apiuser: This is filled automatically from the |authtoken|.
533 542 :type apiuser: AuthUser
534 543 :param userid: Sets the userid whose list of locked |repos| will be
535 544 displayed.
536 545 :type userid: Optional(str or int)
537 546
538 547 Example output:
539 548
540 549 .. code-block:: bash
541 550
542 551 id : <id_given_in_input>
543 552 result : {
544 553 [action, action,...]
545 554 }
546 555 error : null
547 556 """
548 557
549 558 if not has_superadmin_permission(apiuser):
550 559 # make sure normal user does not pass someone else userid,
551 560 # he is not allowed to do that
552 561 if not isinstance(userid, Optional) and userid != apiuser.user_id:
553 562 raise JSONRPCError('userid is not the same as your user')
554 563
555 564 userid = Optional.extract(userid, evaluate_locals=locals())
556 565 userid = getattr(userid, 'user_id', userid)
557 566 user = get_user_or_error(userid)
558 567
559 568 ret = []
560 569
561 570 # show all user actions
562 571 for entry in UserModel().get_user_log(user, filter_term=None):
563 572 ret.append(entry)
564 573 return ret
@@ -1,790 +1,793 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import pytest
22 22 from sqlalchemy.orm.exc import NoResultFound
23 23
24 24 from rhodecode.lib import auth
25 25 from rhodecode.lib import helpers as h
26 26 from rhodecode.model.db import User, UserApiKeys, UserEmailMap, Repository
27 27 from rhodecode.model.meta import Session
28 28 from rhodecode.model.user import UserModel
29 29
30 30 from rhodecode.tests import (
31 31 TestController, TEST_USER_REGULAR_LOGIN, assert_session_flash)
32 32 from rhodecode.tests.fixture import Fixture
33 33
34 34 fixture = Fixture()
35 35
36 36
37 37 def route_path(name, params=None, **kwargs):
38 38 import urllib
39 39 from rhodecode.apps._base import ADMIN_PREFIX
40 40
41 41 base_url = {
42 42 'users':
43 43 ADMIN_PREFIX + '/users',
44 44 'users_data':
45 45 ADMIN_PREFIX + '/users_data',
46 46 'users_create':
47 47 ADMIN_PREFIX + '/users/create',
48 48 'users_new':
49 49 ADMIN_PREFIX + '/users/new',
50 50 'user_edit':
51 51 ADMIN_PREFIX + '/users/{user_id}/edit',
52 52 'user_edit_advanced':
53 53 ADMIN_PREFIX + '/users/{user_id}/edit/advanced',
54 54 'user_edit_global_perms':
55 55 ADMIN_PREFIX + '/users/{user_id}/edit/global_permissions',
56 56 'user_edit_global_perms_update':
57 57 ADMIN_PREFIX + '/users/{user_id}/edit/global_permissions/update',
58 58 'user_update':
59 59 ADMIN_PREFIX + '/users/{user_id}/update',
60 60 'user_delete':
61 61 ADMIN_PREFIX + '/users/{user_id}/delete',
62 62 'user_create_personal_repo_group':
63 63 ADMIN_PREFIX + '/users/{user_id}/create_repo_group',
64 64
65 65 'edit_user_auth_tokens':
66 66 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens',
67 67 'edit_user_auth_tokens_add':
68 68 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/new',
69 69 'edit_user_auth_tokens_delete':
70 70 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens/delete',
71 71
72 72 'edit_user_emails':
73 73 ADMIN_PREFIX + '/users/{user_id}/edit/emails',
74 74 'edit_user_emails_add':
75 75 ADMIN_PREFIX + '/users/{user_id}/edit/emails/new',
76 76 'edit_user_emails_delete':
77 77 ADMIN_PREFIX + '/users/{user_id}/edit/emails/delete',
78 78
79 79 'edit_user_ips':
80 80 ADMIN_PREFIX + '/users/{user_id}/edit/ips',
81 81 'edit_user_ips_add':
82 82 ADMIN_PREFIX + '/users/{user_id}/edit/ips/new',
83 83 'edit_user_ips_delete':
84 84 ADMIN_PREFIX + '/users/{user_id}/edit/ips/delete',
85 85
86 86 'edit_user_perms_summary':
87 87 ADMIN_PREFIX + '/users/{user_id}/edit/permissions_summary',
88 88 'edit_user_perms_summary_json':
89 89 ADMIN_PREFIX + '/users/{user_id}/edit/permissions_summary/json',
90 90
91 91 'edit_user_audit_logs':
92 92 ADMIN_PREFIX + '/users/{user_id}/edit/audit',
93 93
94 94 'edit_user_audit_logs_download':
95 95 ADMIN_PREFIX + '/users/{user_id}/edit/audit/download',
96 96
97 97 }[name].format(**kwargs)
98 98
99 99 if params:
100 100 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
101 101 return base_url
102 102
103 103
104 104 class TestAdminUsersView(TestController):
105 105
106 106 def test_show_users(self):
107 107 self.log_user()
108 108 self.app.get(route_path('users'))
109 109
110 110 def test_show_users_data(self, xhr_header):
111 111 self.log_user()
112 112 response = self.app.get(route_path(
113 113 'users_data'), extra_environ=xhr_header)
114 114
115 115 all_users = User.query().filter(
116 116 User.username != User.DEFAULT_USER).count()
117 117 assert response.json['recordsTotal'] == all_users
118 118
119 119 def test_show_users_data_filtered(self, xhr_header):
120 120 self.log_user()
121 121 response = self.app.get(route_path(
122 122 'users_data', params={'search[value]': 'empty_search'}),
123 123 extra_environ=xhr_header)
124 124
125 125 all_users = User.query().filter(
126 126 User.username != User.DEFAULT_USER).count()
127 127 assert response.json['recordsTotal'] == all_users
128 128 assert response.json['recordsFiltered'] == 0
129 129
130 130 def test_auth_tokens_default_user(self):
131 131 self.log_user()
132 132 user = User.get_default_user()
133 133 response = self.app.get(
134 134 route_path('edit_user_auth_tokens', user_id=user.user_id),
135 135 status=302)
136 136
137 137 def test_auth_tokens(self):
138 138 self.log_user()
139 139
140 140 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
141 141 user_id = user.user_id
142 142 auth_tokens = user.auth_tokens
143 143 response = self.app.get(
144 144 route_path('edit_user_auth_tokens', user_id=user_id))
145 145 for token in auth_tokens:
146 146 response.mustcontain(token)
147 147 response.mustcontain('never')
148 148
149 149 @pytest.mark.parametrize("desc, lifetime", [
150 150 ('forever', -1),
151 151 ('5mins', 60*5),
152 152 ('30days', 60*60*24*30),
153 153 ])
154 154 def test_add_auth_token(self, desc, lifetime, user_util):
155 155 self.log_user()
156 156 user = user_util.create_user()
157 157 user_id = user.user_id
158 158
159 159 response = self.app.post(
160 160 route_path('edit_user_auth_tokens_add', user_id=user_id),
161 161 {'description': desc, 'lifetime': lifetime,
162 162 'csrf_token': self.csrf_token})
163 163 assert_session_flash(response, 'Auth token successfully created')
164 164
165 165 response = response.follow()
166 166 user = User.get(user_id)
167 167 for auth_token in user.auth_tokens:
168 168 response.mustcontain(auth_token)
169 169
170 170 def test_delete_auth_token(self, user_util):
171 171 self.log_user()
172 172 user = user_util.create_user()
173 173 user_id = user.user_id
174 174 keys = user.auth_tokens
175 175 assert 2 == len(keys)
176 176
177 177 response = self.app.post(
178 178 route_path('edit_user_auth_tokens_add', user_id=user_id),
179 179 {'description': 'desc', 'lifetime': -1,
180 180 'csrf_token': self.csrf_token})
181 181 assert_session_flash(response, 'Auth token successfully created')
182 182 response.follow()
183 183
184 184 # now delete our key
185 185 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
186 186 assert 3 == len(keys)
187 187
188 188 response = self.app.post(
189 189 route_path('edit_user_auth_tokens_delete', user_id=user_id),
190 190 {'del_auth_token': keys[0].user_api_key_id,
191 191 'csrf_token': self.csrf_token})
192 192
193 193 assert_session_flash(response, 'Auth token successfully deleted')
194 194 keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
195 195 assert 2 == len(keys)
196 196
197 197 def test_ips(self):
198 198 self.log_user()
199 199 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
200 200 response = self.app.get(route_path('edit_user_ips', user_id=user.user_id))
201 201 response.mustcontain('All IP addresses are allowed')
202 202
203 203 @pytest.mark.parametrize("test_name, ip, ip_range, failure", [
204 204 ('127/24', '127.0.0.1/24', '127.0.0.0 - 127.0.0.255', False),
205 205 ('10/32', '10.0.0.10/32', '10.0.0.10 - 10.0.0.10', False),
206 206 ('0/16', '0.0.0.0/16', '0.0.0.0 - 0.0.255.255', False),
207 207 ('0/8', '0.0.0.0/8', '0.0.0.0 - 0.255.255.255', False),
208 208 ('127_bad_mask', '127.0.0.1/99', '127.0.0.1 - 127.0.0.1', True),
209 209 ('127_bad_ip', 'foobar', 'foobar', True),
210 210 ])
211 211 def test_ips_add(self, user_util, test_name, ip, ip_range, failure):
212 212 self.log_user()
213 213 user = user_util.create_user(username=test_name)
214 214 user_id = user.user_id
215 215
216 216 response = self.app.post(
217 217 route_path('edit_user_ips_add', user_id=user_id),
218 218 params={'new_ip': ip, 'csrf_token': self.csrf_token})
219 219
220 220 if failure:
221 221 assert_session_flash(
222 222 response, 'Please enter a valid IPv4 or IpV6 address')
223 223 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
224 224
225 225 response.mustcontain(no=[ip])
226 226 response.mustcontain(no=[ip_range])
227 227
228 228 else:
229 229 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
230 230 response.mustcontain(ip)
231 231 response.mustcontain(ip_range)
232 232
233 233 def test_ips_delete(self, user_util):
234 234 self.log_user()
235 235 user = user_util.create_user()
236 236 user_id = user.user_id
237 237 ip = '127.0.0.1/32'
238 238 ip_range = '127.0.0.1 - 127.0.0.1'
239 239 new_ip = UserModel().add_extra_ip(user_id, ip)
240 240 Session().commit()
241 241 new_ip_id = new_ip.ip_id
242 242
243 243 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
244 244 response.mustcontain(ip)
245 245 response.mustcontain(ip_range)
246 246
247 247 self.app.post(
248 248 route_path('edit_user_ips_delete', user_id=user_id),
249 249 params={'del_ip_id': new_ip_id, 'csrf_token': self.csrf_token})
250 250
251 251 response = self.app.get(route_path('edit_user_ips', user_id=user_id))
252 252 response.mustcontain('All IP addresses are allowed')
253 253 response.mustcontain(no=[ip])
254 254 response.mustcontain(no=[ip_range])
255 255
256 256 def test_emails(self):
257 257 self.log_user()
258 258 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
259 259 response = self.app.get(
260 260 route_path('edit_user_emails', user_id=user.user_id))
261 261 response.mustcontain('No additional emails specified')
262 262
263 263 def test_emails_add(self, user_util):
264 264 self.log_user()
265 265 user = user_util.create_user()
266 266 user_id = user.user_id
267 267
268 268 self.app.post(
269 269 route_path('edit_user_emails_add', user_id=user_id),
270 270 params={'new_email': 'example@rhodecode.com',
271 271 'csrf_token': self.csrf_token})
272 272
273 273 response = self.app.get(
274 274 route_path('edit_user_emails', user_id=user_id))
275 275 response.mustcontain('example@rhodecode.com')
276 276
277 277 def test_emails_add_existing_email(self, user_util, user_regular):
278 278 existing_email = user_regular.email
279 279
280 280 self.log_user()
281 281 user = user_util.create_user()
282 282 user_id = user.user_id
283 283
284 284 response = self.app.post(
285 285 route_path('edit_user_emails_add', user_id=user_id),
286 286 params={'new_email': existing_email,
287 287 'csrf_token': self.csrf_token})
288 288 assert_session_flash(
289 289 response, 'This e-mail address is already taken')
290 290
291 291 response = self.app.get(
292 292 route_path('edit_user_emails', user_id=user_id))
293 293 response.mustcontain(no=[existing_email])
294 294
295 295 def test_emails_delete(self, user_util):
296 296 self.log_user()
297 297 user = user_util.create_user()
298 298 user_id = user.user_id
299 299
300 300 self.app.post(
301 301 route_path('edit_user_emails_add', user_id=user_id),
302 302 params={'new_email': 'example@rhodecode.com',
303 303 'csrf_token': self.csrf_token})
304 304
305 305 response = self.app.get(
306 306 route_path('edit_user_emails', user_id=user_id))
307 307 response.mustcontain('example@rhodecode.com')
308 308
309 309 user_email = UserEmailMap.query()\
310 310 .filter(UserEmailMap.email == 'example@rhodecode.com') \
311 311 .filter(UserEmailMap.user_id == user_id)\
312 312 .one()
313 313
314 314 del_email_id = user_email.email_id
315 315 self.app.post(
316 316 route_path('edit_user_emails_delete', user_id=user_id),
317 317 params={'del_email_id': del_email_id,
318 318 'csrf_token': self.csrf_token})
319 319
320 320 response = self.app.get(
321 321 route_path('edit_user_emails', user_id=user_id))
322 322 response.mustcontain(no=['example@rhodecode.com'])
323 323
324 324 def test_create(self, request, xhr_header):
325 325 self.log_user()
326 326 username = 'newtestuser'
327 327 password = 'test12'
328 328 password_confirmation = password
329 329 name = 'name'
330 330 lastname = 'lastname'
331 331 email = 'mail@mail.com'
332 332
333 333 self.app.get(route_path('users_new'))
334 334
335 335 response = self.app.post(route_path('users_create'), params={
336 336 'username': username,
337 337 'password': password,
338 'description': 'mr CTO',
338 339 'password_confirmation': password_confirmation,
339 340 'firstname': name,
340 341 'active': True,
341 342 'lastname': lastname,
342 343 'extern_name': 'rhodecode',
343 344 'extern_type': 'rhodecode',
344 345 'email': email,
345 346 'csrf_token': self.csrf_token,
346 347 })
347 348 user_link = h.link_to(
348 349 username,
349 350 route_path(
350 351 'user_edit', user_id=User.get_by_username(username).user_id))
351 352 assert_session_flash(response, 'Created user %s' % (user_link,))
352 353
353 354 @request.addfinalizer
354 355 def cleanup():
355 356 fixture.destroy_user(username)
356 357 Session().commit()
357 358
358 359 new_user = User.query().filter(User.username == username).one()
359 360
360 361 assert new_user.username == username
361 362 assert auth.check_password(password, new_user.password)
362 363 assert new_user.name == name
363 364 assert new_user.lastname == lastname
364 365 assert new_user.email == email
365 366
366 367 response = self.app.get(route_path('users_data'),
367 368 extra_environ=xhr_header)
368 369 response.mustcontain(username)
369 370
370 371 def test_create_err(self):
371 372 self.log_user()
372 373 username = 'new_user'
373 374 password = ''
374 375 name = 'name'
375 376 lastname = 'lastname'
376 377 email = 'errmail.com'
377 378
378 379 self.app.get(route_path('users_new'))
379 380
380 381 response = self.app.post(route_path('users_create'), params={
381 382 'username': username,
382 383 'password': password,
383 384 'name': name,
384 385 'active': False,
385 386 'lastname': lastname,
387 'description': 'mr CTO',
386 388 'email': email,
387 389 'csrf_token': self.csrf_token,
388 390 })
389 391
390 392 msg = u'Username "%(username)s" is forbidden'
391 393 msg = h.html_escape(msg % {'username': 'new_user'})
392 394 response.mustcontain('<span class="error-message">%s</span>' % msg)
393 395 response.mustcontain(
394 396 '<span class="error-message">Please enter a value</span>')
395 397 response.mustcontain(
396 398 '<span class="error-message">An email address must contain a'
397 399 ' single @</span>')
398 400
399 401 def get_user():
400 402 Session().query(User).filter(User.username == username).one()
401 403
402 404 with pytest.raises(NoResultFound):
403 405 get_user()
404 406
405 407 def test_new(self):
406 408 self.log_user()
407 409 self.app.get(route_path('users_new'))
408 410
409 411 @pytest.mark.parametrize("name, attrs", [
410 412 ('firstname', {'firstname': 'new_username'}),
411 413 ('lastname', {'lastname': 'new_username'}),
412 414 ('admin', {'admin': True}),
413 415 ('admin', {'admin': False}),
414 416 ('extern_type', {'extern_type': 'ldap'}),
415 417 ('extern_type', {'extern_type': None}),
416 418 ('extern_name', {'extern_name': 'test'}),
417 419 ('extern_name', {'extern_name': None}),
418 420 ('active', {'active': False}),
419 421 ('active', {'active': True}),
420 422 ('email', {'email': 'some@email.com'}),
421 423 ('language', {'language': 'de'}),
422 424 ('language', {'language': 'en'}),
425 ('description', {'description': 'hello CTO'}),
423 426 # ('new_password', {'new_password': 'foobar123',
424 427 # 'password_confirmation': 'foobar123'})
425 428 ])
426 429 def test_update(self, name, attrs, user_util):
427 430 self.log_user()
428 431 usr = user_util.create_user(
429 432 password='qweqwe',
430 433 email='testme@rhodecode.org',
431 434 extern_type='rhodecode',
432 435 extern_name='xxx',
433 436 )
434 437 user_id = usr.user_id
435 438 Session().commit()
436 439
437 440 params = usr.get_api_data()
438 441 cur_lang = params['language'] or 'en'
439 442 params.update({
440 443 'password_confirmation': '',
441 444 'new_password': '',
442 445 'language': cur_lang,
443 446 'csrf_token': self.csrf_token,
444 447 })
445 448 params.update({'new_password': ''})
446 449 params.update(attrs)
447 450 if name == 'email':
448 451 params['emails'] = [attrs['email']]
449 452 elif name == 'extern_type':
450 453 # cannot update this via form, expected value is original one
451 454 params['extern_type'] = "rhodecode"
452 455 elif name == 'extern_name':
453 456 # cannot update this via form, expected value is original one
454 457 params['extern_name'] = 'xxx'
455 458 # special case since this user is not
456 459 # logged in yet his data is not filled
457 460 # so we use creation data
458 461
459 462 response = self.app.post(
460 463 route_path('user_update', user_id=usr.user_id), params)
461 464 assert response.status_int == 302
462 465 assert_session_flash(response, 'User updated successfully')
463 466
464 467 updated_user = User.get(user_id)
465 468 updated_params = updated_user.get_api_data()
466 469 updated_params.update({'password_confirmation': ''})
467 470 updated_params.update({'new_password': ''})
468 471
469 472 del params['csrf_token']
470 473 assert params == updated_params
471 474
472 475 def test_update_and_migrate_password(
473 476 self, autologin_user, real_crypto_backend, user_util):
474 477
475 478 user = user_util.create_user()
476 479 temp_user = user.username
477 480 user.password = auth._RhodeCodeCryptoSha256().hash_create(
478 481 b'test123')
479 482 Session().add(user)
480 483 Session().commit()
481 484
482 485 params = user.get_api_data()
483 486
484 487 params.update({
485 488 'password_confirmation': 'qweqwe123',
486 489 'new_password': 'qweqwe123',
487 490 'language': 'en',
488 491 'csrf_token': autologin_user.csrf_token,
489 492 })
490 493
491 494 response = self.app.post(
492 495 route_path('user_update', user_id=user.user_id), params)
493 496 assert response.status_int == 302
494 497 assert_session_flash(response, 'User updated successfully')
495 498
496 499 # new password should be bcrypted, after log-in and transfer
497 500 user = User.get_by_username(temp_user)
498 501 assert user.password.startswith('$')
499 502
500 503 updated_user = User.get_by_username(temp_user)
501 504 updated_params = updated_user.get_api_data()
502 505 updated_params.update({'password_confirmation': 'qweqwe123'})
503 506 updated_params.update({'new_password': 'qweqwe123'})
504 507
505 508 del params['csrf_token']
506 509 assert params == updated_params
507 510
508 511 def test_delete(self):
509 512 self.log_user()
510 513 username = 'newtestuserdeleteme'
511 514
512 515 fixture.create_user(name=username)
513 516
514 517 new_user = Session().query(User)\
515 518 .filter(User.username == username).one()
516 519 response = self.app.post(
517 520 route_path('user_delete', user_id=new_user.user_id),
518 521 params={'csrf_token': self.csrf_token})
519 522
520 523 assert_session_flash(response, 'Successfully deleted user `{}`'.format(username))
521 524
522 525 def test_delete_owner_of_repository(self, request, user_util):
523 526 self.log_user()
524 527 obj_name = 'test_repo'
525 528 usr = user_util.create_user()
526 529 username = usr.username
527 530 fixture.create_repo(obj_name, cur_user=usr.username)
528 531
529 532 new_user = Session().query(User)\
530 533 .filter(User.username == username).one()
531 534 response = self.app.post(
532 535 route_path('user_delete', user_id=new_user.user_id),
533 536 params={'csrf_token': self.csrf_token})
534 537
535 538 msg = 'user "%s" still owns 1 repositories and cannot be removed. ' \
536 539 'Switch owners or remove those repositories:%s' % (username, obj_name)
537 540 assert_session_flash(response, msg)
538 541 fixture.destroy_repo(obj_name)
539 542
540 543 def test_delete_owner_of_repository_detaching(self, request, user_util):
541 544 self.log_user()
542 545 obj_name = 'test_repo'
543 546 usr = user_util.create_user(auto_cleanup=False)
544 547 username = usr.username
545 548 fixture.create_repo(obj_name, cur_user=usr.username)
546 549
547 550 new_user = Session().query(User)\
548 551 .filter(User.username == username).one()
549 552 response = self.app.post(
550 553 route_path('user_delete', user_id=new_user.user_id),
551 554 params={'user_repos': 'detach', 'csrf_token': self.csrf_token})
552 555
553 556 msg = 'Detached 1 repositories'
554 557 assert_session_flash(response, msg)
555 558 fixture.destroy_repo(obj_name)
556 559
557 560 def test_delete_owner_of_repository_deleting(self, request, user_util):
558 561 self.log_user()
559 562 obj_name = 'test_repo'
560 563 usr = user_util.create_user(auto_cleanup=False)
561 564 username = usr.username
562 565 fixture.create_repo(obj_name, cur_user=usr.username)
563 566
564 567 new_user = Session().query(User)\
565 568 .filter(User.username == username).one()
566 569 response = self.app.post(
567 570 route_path('user_delete', user_id=new_user.user_id),
568 571 params={'user_repos': 'delete', 'csrf_token': self.csrf_token})
569 572
570 573 msg = 'Deleted 1 repositories'
571 574 assert_session_flash(response, msg)
572 575
573 576 def test_delete_owner_of_repository_group(self, request, user_util):
574 577 self.log_user()
575 578 obj_name = 'test_group'
576 579 usr = user_util.create_user()
577 580 username = usr.username
578 581 fixture.create_repo_group(obj_name, cur_user=usr.username)
579 582
580 583 new_user = Session().query(User)\
581 584 .filter(User.username == username).one()
582 585 response = self.app.post(
583 586 route_path('user_delete', user_id=new_user.user_id),
584 587 params={'csrf_token': self.csrf_token})
585 588
586 589 msg = 'user "%s" still owns 1 repository groups and cannot be removed. ' \
587 590 'Switch owners or remove those repository groups:%s' % (username, obj_name)
588 591 assert_session_flash(response, msg)
589 592 fixture.destroy_repo_group(obj_name)
590 593
591 594 def test_delete_owner_of_repository_group_detaching(self, request, user_util):
592 595 self.log_user()
593 596 obj_name = 'test_group'
594 597 usr = user_util.create_user(auto_cleanup=False)
595 598 username = usr.username
596 599 fixture.create_repo_group(obj_name, cur_user=usr.username)
597 600
598 601 new_user = Session().query(User)\
599 602 .filter(User.username == username).one()
600 603 response = self.app.post(
601 604 route_path('user_delete', user_id=new_user.user_id),
602 605 params={'user_repo_groups': 'delete', 'csrf_token': self.csrf_token})
603 606
604 607 msg = 'Deleted 1 repository groups'
605 608 assert_session_flash(response, msg)
606 609
607 610 def test_delete_owner_of_repository_group_deleting(self, request, user_util):
608 611 self.log_user()
609 612 obj_name = 'test_group'
610 613 usr = user_util.create_user(auto_cleanup=False)
611 614 username = usr.username
612 615 fixture.create_repo_group(obj_name, cur_user=usr.username)
613 616
614 617 new_user = Session().query(User)\
615 618 .filter(User.username == username).one()
616 619 response = self.app.post(
617 620 route_path('user_delete', user_id=new_user.user_id),
618 621 params={'user_repo_groups': 'detach', 'csrf_token': self.csrf_token})
619 622
620 623 msg = 'Detached 1 repository groups'
621 624 assert_session_flash(response, msg)
622 625 fixture.destroy_repo_group(obj_name)
623 626
624 627 def test_delete_owner_of_user_group(self, request, user_util):
625 628 self.log_user()
626 629 obj_name = 'test_user_group'
627 630 usr = user_util.create_user()
628 631 username = usr.username
629 632 fixture.create_user_group(obj_name, cur_user=usr.username)
630 633
631 634 new_user = Session().query(User)\
632 635 .filter(User.username == username).one()
633 636 response = self.app.post(
634 637 route_path('user_delete', user_id=new_user.user_id),
635 638 params={'csrf_token': self.csrf_token})
636 639
637 640 msg = 'user "%s" still owns 1 user groups and cannot be removed. ' \
638 641 'Switch owners or remove those user groups:%s' % (username, obj_name)
639 642 assert_session_flash(response, msg)
640 643 fixture.destroy_user_group(obj_name)
641 644
642 645 def test_delete_owner_of_user_group_detaching(self, request, user_util):
643 646 self.log_user()
644 647 obj_name = 'test_user_group'
645 648 usr = user_util.create_user(auto_cleanup=False)
646 649 username = usr.username
647 650 fixture.create_user_group(obj_name, cur_user=usr.username)
648 651
649 652 new_user = Session().query(User)\
650 653 .filter(User.username == username).one()
651 654 try:
652 655 response = self.app.post(
653 656 route_path('user_delete', user_id=new_user.user_id),
654 657 params={'user_user_groups': 'detach',
655 658 'csrf_token': self.csrf_token})
656 659
657 660 msg = 'Detached 1 user groups'
658 661 assert_session_flash(response, msg)
659 662 finally:
660 663 fixture.destroy_user_group(obj_name)
661 664
662 665 def test_delete_owner_of_user_group_deleting(self, request, user_util):
663 666 self.log_user()
664 667 obj_name = 'test_user_group'
665 668 usr = user_util.create_user(auto_cleanup=False)
666 669 username = usr.username
667 670 fixture.create_user_group(obj_name, cur_user=usr.username)
668 671
669 672 new_user = Session().query(User)\
670 673 .filter(User.username == username).one()
671 674 response = self.app.post(
672 675 route_path('user_delete', user_id=new_user.user_id),
673 676 params={'user_user_groups': 'delete', 'csrf_token': self.csrf_token})
674 677
675 678 msg = 'Deleted 1 user groups'
676 679 assert_session_flash(response, msg)
677 680
678 681 def test_edit(self, user_util):
679 682 self.log_user()
680 683 user = user_util.create_user()
681 684 self.app.get(route_path('user_edit', user_id=user.user_id))
682 685
683 686 def test_edit_default_user_redirect(self):
684 687 self.log_user()
685 688 user = User.get_default_user()
686 689 self.app.get(route_path('user_edit', user_id=user.user_id), status=302)
687 690
688 691 @pytest.mark.parametrize(
689 692 'repo_create, repo_create_write, user_group_create, repo_group_create,'
690 693 'fork_create, inherit_default_permissions, expect_error,'
691 694 'expect_form_error', [
692 695 ('hg.create.none', 'hg.create.write_on_repogroup.false',
693 696 'hg.usergroup.create.false', 'hg.repogroup.create.false',
694 697 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
695 698 ('hg.create.repository', 'hg.create.write_on_repogroup.false',
696 699 'hg.usergroup.create.false', 'hg.repogroup.create.false',
697 700 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
698 701 ('hg.create.repository', 'hg.create.write_on_repogroup.true',
699 702 'hg.usergroup.create.true', 'hg.repogroup.create.true',
700 703 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
701 704 False),
702 705 ('hg.create.XXX', 'hg.create.write_on_repogroup.true',
703 706 'hg.usergroup.create.true', 'hg.repogroup.create.true',
704 707 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
705 708 True),
706 709 ('', '', '', '', '', '', True, False),
707 710 ])
708 711 def test_global_perms_on_user(
709 712 self, repo_create, repo_create_write, user_group_create,
710 713 repo_group_create, fork_create, expect_error, expect_form_error,
711 714 inherit_default_permissions, user_util):
712 715 self.log_user()
713 716 user = user_util.create_user()
714 717 uid = user.user_id
715 718
716 719 # ENABLE REPO CREATE ON A GROUP
717 720 perm_params = {
718 721 'inherit_default_permissions': False,
719 722 'default_repo_create': repo_create,
720 723 'default_repo_create_on_write': repo_create_write,
721 724 'default_user_group_create': user_group_create,
722 725 'default_repo_group_create': repo_group_create,
723 726 'default_fork_create': fork_create,
724 727 'default_inherit_default_permissions': inherit_default_permissions,
725 728 'csrf_token': self.csrf_token,
726 729 }
727 730 response = self.app.post(
728 731 route_path('user_edit_global_perms_update', user_id=uid),
729 732 params=perm_params)
730 733
731 734 if expect_form_error:
732 735 assert response.status_int == 200
733 736 response.mustcontain('Value must be one of')
734 737 else:
735 738 if expect_error:
736 739 msg = 'An error occurred during permissions saving'
737 740 else:
738 741 msg = 'User global permissions updated successfully'
739 742 ug = User.get(uid)
740 743 del perm_params['inherit_default_permissions']
741 744 del perm_params['csrf_token']
742 745 assert perm_params == ug.get_default_perms()
743 746 assert_session_flash(response, msg)
744 747
745 748 def test_global_permissions_initial_values(self, user_util):
746 749 self.log_user()
747 750 user = user_util.create_user()
748 751 uid = user.user_id
749 752 response = self.app.get(
750 753 route_path('user_edit_global_perms', user_id=uid))
751 754 default_user = User.get_default_user()
752 755 default_permissions = default_user.get_default_perms()
753 756 assert_response = response.assert_response()
754 757 expected_permissions = (
755 758 'default_repo_create', 'default_repo_create_on_write',
756 759 'default_fork_create', 'default_repo_group_create',
757 760 'default_user_group_create', 'default_inherit_default_permissions')
758 761 for permission in expected_permissions:
759 762 css_selector = '[name={}][checked=checked]'.format(permission)
760 763 element = assert_response.get_element(css_selector)
761 764 assert element.value == default_permissions[permission]
762 765
763 766 def test_perms_summary_page(self):
764 767 user = self.log_user()
765 768 response = self.app.get(
766 769 route_path('edit_user_perms_summary', user_id=user['user_id']))
767 770 for repo in Repository.query().all():
768 771 response.mustcontain(repo.repo_name)
769 772
770 773 def test_perms_summary_page_json(self):
771 774 user = self.log_user()
772 775 response = self.app.get(
773 776 route_path('edit_user_perms_summary_json', user_id=user['user_id']))
774 777 for repo in Repository.query().all():
775 778 response.mustcontain(repo.repo_name)
776 779
777 780 def test_audit_log_page(self):
778 781 user = self.log_user()
779 782 self.app.get(
780 783 route_path('edit_user_audit_logs', user_id=user['user_id']))
781 784
782 785 def test_audit_log_page_download(self):
783 786 user = self.log_user()
784 787 user_id = user['user_id']
785 788 response = self.app.get(
786 789 route_path('edit_user_audit_logs_download', user_id=user_id))
787 790
788 791 assert response.content_disposition == \
789 792 'attachment; filename=user_{}_audit_logs.json'.format(user_id)
790 793 assert response.content_type == "application/json"
@@ -1,5445 +1,5446 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Database Models for RhodeCode Enterprise
23 23 """
24 24
25 25 import re
26 26 import os
27 27 import time
28 28 import string
29 29 import hashlib
30 30 import logging
31 31 import datetime
32 32 import uuid
33 33 import warnings
34 34 import ipaddress
35 35 import functools
36 36 import traceback
37 37 import collections
38 38
39 39 from sqlalchemy import (
40 40 or_, and_, not_, func, TypeDecorator, event,
41 41 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
42 42 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
43 43 Text, Float, PickleType, BigInteger)
44 44 from sqlalchemy.sql.expression import true, false, case
45 45 from sqlalchemy.sql.functions import coalesce, count # pragma: no cover
46 46 from sqlalchemy.orm import (
47 47 relationship, joinedload, class_mapper, validates, aliased)
48 48 from sqlalchemy.ext.declarative import declared_attr
49 49 from sqlalchemy.ext.hybrid import hybrid_property
50 50 from sqlalchemy.exc import IntegrityError # pragma: no cover
51 51 from sqlalchemy.dialects.mysql import LONGTEXT
52 52 from zope.cachedescriptors.property import Lazy as LazyProperty
53 53 from pyramid import compat
54 54 from pyramid.threadlocal import get_current_request
55 55 from webhelpers.text import collapse, remove_formatting
56 56
57 57 from rhodecode.translation import _
58 58 from rhodecode.lib.vcs import get_vcs_instance
59 59 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
60 60 from rhodecode.lib.utils2 import (
61 61 str2bool, safe_str, get_commit_safe, safe_unicode, sha1_safe,
62 62 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
63 63 glob2re, StrictAttributeDict, cleaned_uri, datetime_to_time, OrderedDefaultDict)
64 64 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
65 65 JsonRaw
66 66 from rhodecode.lib.ext_json import json
67 67 from rhodecode.lib.caching_query import FromCache
68 68 from rhodecode.lib.encrypt import AESCipher, validate_and_get_enc_data
69 69 from rhodecode.lib.encrypt2 import Encryptor
70 70 from rhodecode.lib.exceptions import (
71 71 ArtifactMetadataDuplicate, ArtifactMetadataBadValueType)
72 72 from rhodecode.model.meta import Base, Session
73 73
74 74 URL_SEP = '/'
75 75 log = logging.getLogger(__name__)
76 76
77 77 # =============================================================================
78 78 # BASE CLASSES
79 79 # =============================================================================
80 80
81 81 # this is propagated from .ini file rhodecode.encrypted_values.secret or
82 82 # beaker.session.secret if first is not set.
83 83 # and initialized at environment.py
84 84 ENCRYPTION_KEY = None
85 85
86 86 # used to sort permissions by types, '#' used here is not allowed to be in
87 87 # usernames, and it's very early in sorted string.printable table.
88 88 PERMISSION_TYPE_SORT = {
89 89 'admin': '####',
90 90 'write': '###',
91 91 'read': '##',
92 92 'none': '#',
93 93 }
94 94
95 95
96 96 def display_user_sort(obj):
97 97 """
98 98 Sort function used to sort permissions in .permissions() function of
99 99 Repository, RepoGroup, UserGroup. Also it put the default user in front
100 100 of all other resources
101 101 """
102 102
103 103 if obj.username == User.DEFAULT_USER:
104 104 return '#####'
105 105 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
106 106 return prefix + obj.username
107 107
108 108
109 109 def display_user_group_sort(obj):
110 110 """
111 111 Sort function used to sort permissions in .permissions() function of
112 112 Repository, RepoGroup, UserGroup. Also it put the default user in front
113 113 of all other resources
114 114 """
115 115
116 116 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
117 117 return prefix + obj.users_group_name
118 118
119 119
120 120 def _hash_key(k):
121 121 return sha1_safe(k)
122 122
123 123
124 124 def in_filter_generator(qry, items, limit=500):
125 125 """
126 126 Splits IN() into multiple with OR
127 127 e.g.::
128 128 cnt = Repository.query().filter(
129 129 or_(
130 130 *in_filter_generator(Repository.repo_id, range(100000))
131 131 )).count()
132 132 """
133 133 if not items:
134 134 # empty list will cause empty query which might cause security issues
135 135 # this can lead to hidden unpleasant results
136 136 items = [-1]
137 137
138 138 parts = []
139 139 for chunk in xrange(0, len(items), limit):
140 140 parts.append(
141 141 qry.in_(items[chunk: chunk + limit])
142 142 )
143 143
144 144 return parts
145 145
146 146
147 147 base_table_args = {
148 148 'extend_existing': True,
149 149 'mysql_engine': 'InnoDB',
150 150 'mysql_charset': 'utf8',
151 151 'sqlite_autoincrement': True
152 152 }
153 153
154 154
155 155 class EncryptedTextValue(TypeDecorator):
156 156 """
157 157 Special column for encrypted long text data, use like::
158 158
159 159 value = Column("encrypted_value", EncryptedValue(), nullable=False)
160 160
161 161 This column is intelligent so if value is in unencrypted form it return
162 162 unencrypted form, but on save it always encrypts
163 163 """
164 164 impl = Text
165 165
166 166 def process_bind_param(self, value, dialect):
167 167 """
168 168 Setter for storing value
169 169 """
170 170 import rhodecode
171 171 if not value:
172 172 return value
173 173
174 174 # protect against double encrypting if values is already encrypted
175 175 if value.startswith('enc$aes$') \
176 176 or value.startswith('enc$aes_hmac$') \
177 177 or value.startswith('enc2$'):
178 178 raise ValueError('value needs to be in unencrypted format, '
179 179 'ie. not starting with enc$ or enc2$')
180 180
181 181 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
182 182 if algo == 'aes':
183 183 return 'enc$aes_hmac$%s' % AESCipher(ENCRYPTION_KEY, hmac=True).encrypt(value)
184 184 elif algo == 'fernet':
185 185 return Encryptor(ENCRYPTION_KEY).encrypt(value)
186 186 else:
187 187 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
188 188
189 189 def process_result_value(self, value, dialect):
190 190 """
191 191 Getter for retrieving value
192 192 """
193 193
194 194 import rhodecode
195 195 if not value:
196 196 return value
197 197
198 198 algo = rhodecode.CONFIG.get('rhodecode.encrypted_values.algorithm') or 'aes'
199 199 enc_strict_mode = str2bool(rhodecode.CONFIG.get('rhodecode.encrypted_values.strict') or True)
200 200 if algo == 'aes':
201 201 decrypted_data = validate_and_get_enc_data(value, ENCRYPTION_KEY, enc_strict_mode)
202 202 elif algo == 'fernet':
203 203 return Encryptor(ENCRYPTION_KEY).decrypt(value)
204 204 else:
205 205 ValueError('Bad encryption algorithm, should be fernet or aes, got: {}'.format(algo))
206 206 return decrypted_data
207 207
208 208
209 209 class BaseModel(object):
210 210 """
211 211 Base Model for all classes
212 212 """
213 213
214 214 @classmethod
215 215 def _get_keys(cls):
216 216 """return column names for this model """
217 217 return class_mapper(cls).c.keys()
218 218
219 219 def get_dict(self):
220 220 """
221 221 return dict with keys and values corresponding
222 222 to this model data """
223 223
224 224 d = {}
225 225 for k in self._get_keys():
226 226 d[k] = getattr(self, k)
227 227
228 228 # also use __json__() if present to get additional fields
229 229 _json_attr = getattr(self, '__json__', None)
230 230 if _json_attr:
231 231 # update with attributes from __json__
232 232 if callable(_json_attr):
233 233 _json_attr = _json_attr()
234 234 for k, val in _json_attr.iteritems():
235 235 d[k] = val
236 236 return d
237 237
238 238 def get_appstruct(self):
239 239 """return list with keys and values tuples corresponding
240 240 to this model data """
241 241
242 242 lst = []
243 243 for k in self._get_keys():
244 244 lst.append((k, getattr(self, k),))
245 245 return lst
246 246
247 247 def populate_obj(self, populate_dict):
248 248 """populate model with data from given populate_dict"""
249 249
250 250 for k in self._get_keys():
251 251 if k in populate_dict:
252 252 setattr(self, k, populate_dict[k])
253 253
254 254 @classmethod
255 255 def query(cls):
256 256 return Session().query(cls)
257 257
258 258 @classmethod
259 259 def get(cls, id_):
260 260 if id_:
261 261 return cls.query().get(id_)
262 262
263 263 @classmethod
264 264 def get_or_404(cls, id_):
265 265 from pyramid.httpexceptions import HTTPNotFound
266 266
267 267 try:
268 268 id_ = int(id_)
269 269 except (TypeError, ValueError):
270 270 raise HTTPNotFound()
271 271
272 272 res = cls.query().get(id_)
273 273 if not res:
274 274 raise HTTPNotFound()
275 275 return res
276 276
277 277 @classmethod
278 278 def getAll(cls):
279 279 # deprecated and left for backward compatibility
280 280 return cls.get_all()
281 281
282 282 @classmethod
283 283 def get_all(cls):
284 284 return cls.query().all()
285 285
286 286 @classmethod
287 287 def delete(cls, id_):
288 288 obj = cls.query().get(id_)
289 289 Session().delete(obj)
290 290
291 291 @classmethod
292 292 def identity_cache(cls, session, attr_name, value):
293 293 exist_in_session = []
294 294 for (item_cls, pkey), instance in session.identity_map.items():
295 295 if cls == item_cls and getattr(instance, attr_name) == value:
296 296 exist_in_session.append(instance)
297 297 if exist_in_session:
298 298 if len(exist_in_session) == 1:
299 299 return exist_in_session[0]
300 300 log.exception(
301 301 'multiple objects with attr %s and '
302 302 'value %s found with same name: %r',
303 303 attr_name, value, exist_in_session)
304 304
305 305 def __repr__(self):
306 306 if hasattr(self, '__unicode__'):
307 307 # python repr needs to return str
308 308 try:
309 309 return safe_str(self.__unicode__())
310 310 except UnicodeDecodeError:
311 311 pass
312 312 return '<DB:%s>' % (self.__class__.__name__)
313 313
314 314
315 315 class RhodeCodeSetting(Base, BaseModel):
316 316 __tablename__ = 'rhodecode_settings'
317 317 __table_args__ = (
318 318 UniqueConstraint('app_settings_name'),
319 319 base_table_args
320 320 )
321 321
322 322 SETTINGS_TYPES = {
323 323 'str': safe_str,
324 324 'int': safe_int,
325 325 'unicode': safe_unicode,
326 326 'bool': str2bool,
327 327 'list': functools.partial(aslist, sep=',')
328 328 }
329 329 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
330 330 GLOBAL_CONF_KEY = 'app_settings'
331 331
332 332 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
333 333 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
334 334 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
335 335 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
336 336
337 337 def __init__(self, key='', val='', type='unicode'):
338 338 self.app_settings_name = key
339 339 self.app_settings_type = type
340 340 self.app_settings_value = val
341 341
342 342 @validates('_app_settings_value')
343 343 def validate_settings_value(self, key, val):
344 344 assert type(val) == unicode
345 345 return val
346 346
347 347 @hybrid_property
348 348 def app_settings_value(self):
349 349 v = self._app_settings_value
350 350 _type = self.app_settings_type
351 351 if _type:
352 352 _type = self.app_settings_type.split('.')[0]
353 353 # decode the encrypted value
354 354 if 'encrypted' in self.app_settings_type:
355 355 cipher = EncryptedTextValue()
356 356 v = safe_unicode(cipher.process_result_value(v, None))
357 357
358 358 converter = self.SETTINGS_TYPES.get(_type) or \
359 359 self.SETTINGS_TYPES['unicode']
360 360 return converter(v)
361 361
362 362 @app_settings_value.setter
363 363 def app_settings_value(self, val):
364 364 """
365 365 Setter that will always make sure we use unicode in app_settings_value
366 366
367 367 :param val:
368 368 """
369 369 val = safe_unicode(val)
370 370 # encode the encrypted value
371 371 if 'encrypted' in self.app_settings_type:
372 372 cipher = EncryptedTextValue()
373 373 val = safe_unicode(cipher.process_bind_param(val, None))
374 374 self._app_settings_value = val
375 375
376 376 @hybrid_property
377 377 def app_settings_type(self):
378 378 return self._app_settings_type
379 379
380 380 @app_settings_type.setter
381 381 def app_settings_type(self, val):
382 382 if val.split('.')[0] not in self.SETTINGS_TYPES:
383 383 raise Exception('type must be one of %s got %s'
384 384 % (self.SETTINGS_TYPES.keys(), val))
385 385 self._app_settings_type = val
386 386
387 387 @classmethod
388 388 def get_by_prefix(cls, prefix):
389 389 return RhodeCodeSetting.query()\
390 390 .filter(RhodeCodeSetting.app_settings_name.startswith(prefix))\
391 391 .all()
392 392
393 393 def __unicode__(self):
394 394 return u"<%s('%s:%s[%s]')>" % (
395 395 self.__class__.__name__,
396 396 self.app_settings_name, self.app_settings_value,
397 397 self.app_settings_type
398 398 )
399 399
400 400
401 401 class RhodeCodeUi(Base, BaseModel):
402 402 __tablename__ = 'rhodecode_ui'
403 403 __table_args__ = (
404 404 UniqueConstraint('ui_key'),
405 405 base_table_args
406 406 )
407 407
408 408 HOOK_REPO_SIZE = 'changegroup.repo_size'
409 409 # HG
410 410 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
411 411 HOOK_PULL = 'outgoing.pull_logger'
412 412 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
413 413 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
414 414 HOOK_PUSH = 'changegroup.push_logger'
415 415 HOOK_PUSH_KEY = 'pushkey.key_push'
416 416
417 417 HOOKS_BUILTIN = [
418 418 HOOK_PRE_PULL,
419 419 HOOK_PULL,
420 420 HOOK_PRE_PUSH,
421 421 HOOK_PRETX_PUSH,
422 422 HOOK_PUSH,
423 423 HOOK_PUSH_KEY,
424 424 ]
425 425
426 426 # TODO: johbo: Unify way how hooks are configured for git and hg,
427 427 # git part is currently hardcoded.
428 428
429 429 # SVN PATTERNS
430 430 SVN_BRANCH_ID = 'vcs_svn_branch'
431 431 SVN_TAG_ID = 'vcs_svn_tag'
432 432
433 433 ui_id = Column(
434 434 "ui_id", Integer(), nullable=False, unique=True, default=None,
435 435 primary_key=True)
436 436 ui_section = Column(
437 437 "ui_section", String(255), nullable=True, unique=None, default=None)
438 438 ui_key = Column(
439 439 "ui_key", String(255), nullable=True, unique=None, default=None)
440 440 ui_value = Column(
441 441 "ui_value", String(255), nullable=True, unique=None, default=None)
442 442 ui_active = Column(
443 443 "ui_active", Boolean(), nullable=True, unique=None, default=True)
444 444
445 445 def __repr__(self):
446 446 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
447 447 self.ui_key, self.ui_value)
448 448
449 449
450 450 class RepoRhodeCodeSetting(Base, BaseModel):
451 451 __tablename__ = 'repo_rhodecode_settings'
452 452 __table_args__ = (
453 453 UniqueConstraint(
454 454 'app_settings_name', 'repository_id',
455 455 name='uq_repo_rhodecode_setting_name_repo_id'),
456 456 base_table_args
457 457 )
458 458
459 459 repository_id = Column(
460 460 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
461 461 nullable=False)
462 462 app_settings_id = Column(
463 463 "app_settings_id", Integer(), nullable=False, unique=True,
464 464 default=None, primary_key=True)
465 465 app_settings_name = Column(
466 466 "app_settings_name", String(255), nullable=True, unique=None,
467 467 default=None)
468 468 _app_settings_value = Column(
469 469 "app_settings_value", String(4096), nullable=True, unique=None,
470 470 default=None)
471 471 _app_settings_type = Column(
472 472 "app_settings_type", String(255), nullable=True, unique=None,
473 473 default=None)
474 474
475 475 repository = relationship('Repository')
476 476
477 477 def __init__(self, repository_id, key='', val='', type='unicode'):
478 478 self.repository_id = repository_id
479 479 self.app_settings_name = key
480 480 self.app_settings_type = type
481 481 self.app_settings_value = val
482 482
483 483 @validates('_app_settings_value')
484 484 def validate_settings_value(self, key, val):
485 485 assert type(val) == unicode
486 486 return val
487 487
488 488 @hybrid_property
489 489 def app_settings_value(self):
490 490 v = self._app_settings_value
491 491 type_ = self.app_settings_type
492 492 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
493 493 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
494 494 return converter(v)
495 495
496 496 @app_settings_value.setter
497 497 def app_settings_value(self, val):
498 498 """
499 499 Setter that will always make sure we use unicode in app_settings_value
500 500
501 501 :param val:
502 502 """
503 503 self._app_settings_value = safe_unicode(val)
504 504
505 505 @hybrid_property
506 506 def app_settings_type(self):
507 507 return self._app_settings_type
508 508
509 509 @app_settings_type.setter
510 510 def app_settings_type(self, val):
511 511 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
512 512 if val not in SETTINGS_TYPES:
513 513 raise Exception('type must be one of %s got %s'
514 514 % (SETTINGS_TYPES.keys(), val))
515 515 self._app_settings_type = val
516 516
517 517 def __unicode__(self):
518 518 return u"<%s('%s:%s:%s[%s]')>" % (
519 519 self.__class__.__name__, self.repository.repo_name,
520 520 self.app_settings_name, self.app_settings_value,
521 521 self.app_settings_type
522 522 )
523 523
524 524
525 525 class RepoRhodeCodeUi(Base, BaseModel):
526 526 __tablename__ = 'repo_rhodecode_ui'
527 527 __table_args__ = (
528 528 UniqueConstraint(
529 529 'repository_id', 'ui_section', 'ui_key',
530 530 name='uq_repo_rhodecode_ui_repository_id_section_key'),
531 531 base_table_args
532 532 )
533 533
534 534 repository_id = Column(
535 535 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
536 536 nullable=False)
537 537 ui_id = Column(
538 538 "ui_id", Integer(), nullable=False, unique=True, default=None,
539 539 primary_key=True)
540 540 ui_section = Column(
541 541 "ui_section", String(255), nullable=True, unique=None, default=None)
542 542 ui_key = Column(
543 543 "ui_key", String(255), nullable=True, unique=None, default=None)
544 544 ui_value = Column(
545 545 "ui_value", String(255), nullable=True, unique=None, default=None)
546 546 ui_active = Column(
547 547 "ui_active", Boolean(), nullable=True, unique=None, default=True)
548 548
549 549 repository = relationship('Repository')
550 550
551 551 def __repr__(self):
552 552 return '<%s[%s:%s]%s=>%s]>' % (
553 553 self.__class__.__name__, self.repository.repo_name,
554 554 self.ui_section, self.ui_key, self.ui_value)
555 555
556 556
557 557 class User(Base, BaseModel):
558 558 __tablename__ = 'users'
559 559 __table_args__ = (
560 560 UniqueConstraint('username'), UniqueConstraint('email'),
561 561 Index('u_username_idx', 'username'),
562 562 Index('u_email_idx', 'email'),
563 563 base_table_args
564 564 )
565 565
566 566 DEFAULT_USER = 'default'
567 567 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
568 568 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
569 569
570 570 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
571 571 username = Column("username", String(255), nullable=True, unique=None, default=None)
572 572 password = Column("password", String(255), nullable=True, unique=None, default=None)
573 573 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
574 574 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
575 575 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
576 576 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
577 577 _email = Column("email", String(255), nullable=True, unique=None, default=None)
578 578 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
579 579 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
580 580 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
581 581
582 582 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
583 583 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
584 584 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
585 585 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
586 586 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
587 587 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
588 588
589 589 user_log = relationship('UserLog')
590 590 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all, delete-orphan')
591 591
592 592 repositories = relationship('Repository')
593 593 repository_groups = relationship('RepoGroup')
594 594 user_groups = relationship('UserGroup')
595 595
596 596 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
597 597 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
598 598
599 599 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all, delete-orphan')
600 600 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
601 601 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all, delete-orphan')
602 602
603 603 group_member = relationship('UserGroupMember', cascade='all')
604 604
605 605 notifications = relationship('UserNotification', cascade='all')
606 606 # notifications assigned to this user
607 607 user_created_notifications = relationship('Notification', cascade='all')
608 608 # comments created by this user
609 609 user_comments = relationship('ChangesetComment', cascade='all')
610 610 # user profile extra info
611 611 user_emails = relationship('UserEmailMap', cascade='all')
612 612 user_ip_map = relationship('UserIpMap', cascade='all')
613 613 user_auth_tokens = relationship('UserApiKeys', cascade='all')
614 614 user_ssh_keys = relationship('UserSshKeys', cascade='all')
615 615
616 616 # gists
617 617 user_gists = relationship('Gist', cascade='all')
618 618 # user pull requests
619 619 user_pull_requests = relationship('PullRequest', cascade='all')
620 620 # external identities
621 621 external_identities = relationship(
622 622 'ExternalIdentity',
623 623 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
624 624 cascade='all')
625 625 # review rules
626 626 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
627 627
628 628 # artifacts owned
629 629 artifacts = relationship('FileStore', primaryjoin='FileStore.user_id==User.user_id')
630 630
631 631 # no cascade, set NULL
632 632 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_user_id==User.user_id')
633 633
634 634 def __unicode__(self):
635 635 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
636 636 self.user_id, self.username)
637 637
638 638 @hybrid_property
639 639 def email(self):
640 640 return self._email
641 641
642 642 @email.setter
643 643 def email(self, val):
644 644 self._email = val.lower() if val else None
645 645
646 646 @hybrid_property
647 647 def first_name(self):
648 648 from rhodecode.lib import helpers as h
649 649 if self.name:
650 650 return h.escape(self.name)
651 651 return self.name
652 652
653 653 @hybrid_property
654 654 def last_name(self):
655 655 from rhodecode.lib import helpers as h
656 656 if self.lastname:
657 657 return h.escape(self.lastname)
658 658 return self.lastname
659 659
660 660 @hybrid_property
661 661 def api_key(self):
662 662 """
663 663 Fetch if exist an auth-token with role ALL connected to this user
664 664 """
665 665 user_auth_token = UserApiKeys.query()\
666 666 .filter(UserApiKeys.user_id == self.user_id)\
667 667 .filter(or_(UserApiKeys.expires == -1,
668 668 UserApiKeys.expires >= time.time()))\
669 669 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
670 670 if user_auth_token:
671 671 user_auth_token = user_auth_token.api_key
672 672
673 673 return user_auth_token
674 674
675 675 @api_key.setter
676 676 def api_key(self, val):
677 677 # don't allow to set API key this is deprecated for now
678 678 self._api_key = None
679 679
680 680 @property
681 681 def reviewer_pull_requests(self):
682 682 return PullRequestReviewers.query() \
683 683 .options(joinedload(PullRequestReviewers.pull_request)) \
684 684 .filter(PullRequestReviewers.user_id == self.user_id) \
685 685 .all()
686 686
687 687 @property
688 688 def firstname(self):
689 689 # alias for future
690 690 return self.name
691 691
692 692 @property
693 693 def emails(self):
694 694 other = UserEmailMap.query()\
695 695 .filter(UserEmailMap.user == self) \
696 696 .order_by(UserEmailMap.email_id.asc()) \
697 697 .all()
698 698 return [self.email] + [x.email for x in other]
699 699
700 700 def emails_cached(self):
701 701 emails = UserEmailMap.query()\
702 702 .filter(UserEmailMap.user == self) \
703 703 .order_by(UserEmailMap.email_id.asc())
704 704
705 705 emails = emails.options(
706 706 FromCache("sql_cache_short", "get_user_{}_emails".format(self.user_id))
707 707 )
708 708
709 709 return [self.email] + [x.email for x in emails]
710 710
711 711 @property
712 712 def auth_tokens(self):
713 713 auth_tokens = self.get_auth_tokens()
714 714 return [x.api_key for x in auth_tokens]
715 715
716 716 def get_auth_tokens(self):
717 717 return UserApiKeys.query()\
718 718 .filter(UserApiKeys.user == self)\
719 719 .order_by(UserApiKeys.user_api_key_id.asc())\
720 720 .all()
721 721
722 722 @LazyProperty
723 723 def feed_token(self):
724 724 return self.get_feed_token()
725 725
726 726 def get_feed_token(self, cache=True):
727 727 feed_tokens = UserApiKeys.query()\
728 728 .filter(UserApiKeys.user == self)\
729 729 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
730 730 if cache:
731 731 feed_tokens = feed_tokens.options(
732 732 FromCache("sql_cache_short", "get_user_feed_token_%s" % self.user_id))
733 733
734 734 feed_tokens = feed_tokens.all()
735 735 if feed_tokens:
736 736 return feed_tokens[0].api_key
737 737 return 'NO_FEED_TOKEN_AVAILABLE'
738 738
739 739 @LazyProperty
740 740 def artifact_token(self):
741 741 return self.get_artifact_token()
742 742
743 743 def get_artifact_token(self, cache=True):
744 744 artifacts_tokens = UserApiKeys.query()\
745 745 .filter(UserApiKeys.user == self)\
746 746 .filter(UserApiKeys.role == UserApiKeys.ROLE_ARTIFACT_DOWNLOAD)
747 747 if cache:
748 748 artifacts_tokens = artifacts_tokens.options(
749 749 FromCache("sql_cache_short", "get_user_artifact_token_%s" % self.user_id))
750 750
751 751 artifacts_tokens = artifacts_tokens.all()
752 752 if artifacts_tokens:
753 753 return artifacts_tokens[0].api_key
754 754 return 'NO_ARTIFACT_TOKEN_AVAILABLE'
755 755
756 756 @classmethod
757 757 def get(cls, user_id, cache=False):
758 758 if not user_id:
759 759 return
760 760
761 761 user = cls.query()
762 762 if cache:
763 763 user = user.options(
764 764 FromCache("sql_cache_short", "get_users_%s" % user_id))
765 765 return user.get(user_id)
766 766
767 767 @classmethod
768 768 def extra_valid_auth_tokens(cls, user, role=None):
769 769 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
770 770 .filter(or_(UserApiKeys.expires == -1,
771 771 UserApiKeys.expires >= time.time()))
772 772 if role:
773 773 tokens = tokens.filter(or_(UserApiKeys.role == role,
774 774 UserApiKeys.role == UserApiKeys.ROLE_ALL))
775 775 return tokens.all()
776 776
777 777 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
778 778 from rhodecode.lib import auth
779 779
780 780 log.debug('Trying to authenticate user: %s via auth-token, '
781 781 'and roles: %s', self, roles)
782 782
783 783 if not auth_token:
784 784 return False
785 785
786 786 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
787 787 tokens_q = UserApiKeys.query()\
788 788 .filter(UserApiKeys.user_id == self.user_id)\
789 789 .filter(or_(UserApiKeys.expires == -1,
790 790 UserApiKeys.expires >= time.time()))
791 791
792 792 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
793 793
794 794 crypto_backend = auth.crypto_backend()
795 795 enc_token_map = {}
796 796 plain_token_map = {}
797 797 for token in tokens_q:
798 798 if token.api_key.startswith(crypto_backend.ENC_PREF):
799 799 enc_token_map[token.api_key] = token
800 800 else:
801 801 plain_token_map[token.api_key] = token
802 802 log.debug(
803 803 'Found %s plain and %s encrypted tokens to check for authentication for this user',
804 804 len(plain_token_map), len(enc_token_map))
805 805
806 806 # plain token match comes first
807 807 match = plain_token_map.get(auth_token)
808 808
809 809 # check encrypted tokens now
810 810 if not match:
811 811 for token_hash, token in enc_token_map.items():
812 812 # NOTE(marcink): this is expensive to calculate, but most secure
813 813 if crypto_backend.hash_check(auth_token, token_hash):
814 814 match = token
815 815 break
816 816
817 817 if match:
818 818 log.debug('Found matching token %s', match)
819 819 if match.repo_id:
820 820 log.debug('Found scope, checking for scope match of token %s', match)
821 821 if match.repo_id == scope_repo_id:
822 822 return True
823 823 else:
824 824 log.debug(
825 825 'AUTH_TOKEN: scope mismatch, token has a set repo scope: %s, '
826 826 'and calling scope is:%s, skipping further checks',
827 827 match.repo, scope_repo_id)
828 828 return False
829 829 else:
830 830 return True
831 831
832 832 return False
833 833
834 834 @property
835 835 def ip_addresses(self):
836 836 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
837 837 return [x.ip_addr for x in ret]
838 838
839 839 @property
840 840 def username_and_name(self):
841 841 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
842 842
843 843 @property
844 844 def username_or_name_or_email(self):
845 845 full_name = self.full_name if self.full_name is not ' ' else None
846 846 return self.username or full_name or self.email
847 847
848 848 @property
849 849 def full_name(self):
850 850 return '%s %s' % (self.first_name, self.last_name)
851 851
852 852 @property
853 853 def full_name_or_username(self):
854 854 return ('%s %s' % (self.first_name, self.last_name)
855 855 if (self.first_name and self.last_name) else self.username)
856 856
857 857 @property
858 858 def full_contact(self):
859 859 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
860 860
861 861 @property
862 862 def short_contact(self):
863 863 return '%s %s' % (self.first_name, self.last_name)
864 864
865 865 @property
866 866 def is_admin(self):
867 867 return self.admin
868 868
869 869 @property
870 870 def language(self):
871 871 return self.user_data.get('language')
872 872
873 873 def AuthUser(self, **kwargs):
874 874 """
875 875 Returns instance of AuthUser for this user
876 876 """
877 877 from rhodecode.lib.auth import AuthUser
878 878 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
879 879
880 880 @hybrid_property
881 881 def user_data(self):
882 882 if not self._user_data:
883 883 return {}
884 884
885 885 try:
886 886 return json.loads(self._user_data)
887 887 except TypeError:
888 888 return {}
889 889
890 890 @user_data.setter
891 891 def user_data(self, val):
892 892 if not isinstance(val, dict):
893 893 raise Exception('user_data must be dict, got %s' % type(val))
894 894 try:
895 895 self._user_data = json.dumps(val)
896 896 except Exception:
897 897 log.error(traceback.format_exc())
898 898
899 899 @classmethod
900 900 def get_by_username(cls, username, case_insensitive=False,
901 901 cache=False, identity_cache=False):
902 902 session = Session()
903 903
904 904 if case_insensitive:
905 905 q = cls.query().filter(
906 906 func.lower(cls.username) == func.lower(username))
907 907 else:
908 908 q = cls.query().filter(cls.username == username)
909 909
910 910 if cache:
911 911 if identity_cache:
912 912 val = cls.identity_cache(session, 'username', username)
913 913 if val:
914 914 return val
915 915 else:
916 916 cache_key = "get_user_by_name_%s" % _hash_key(username)
917 917 q = q.options(
918 918 FromCache("sql_cache_short", cache_key))
919 919
920 920 return q.scalar()
921 921
922 922 @classmethod
923 923 def get_by_auth_token(cls, auth_token, cache=False):
924 924 q = UserApiKeys.query()\
925 925 .filter(UserApiKeys.api_key == auth_token)\
926 926 .filter(or_(UserApiKeys.expires == -1,
927 927 UserApiKeys.expires >= time.time()))
928 928 if cache:
929 929 q = q.options(
930 930 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
931 931
932 932 match = q.first()
933 933 if match:
934 934 return match.user
935 935
936 936 @classmethod
937 937 def get_by_email(cls, email, case_insensitive=False, cache=False):
938 938
939 939 if case_insensitive:
940 940 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
941 941
942 942 else:
943 943 q = cls.query().filter(cls.email == email)
944 944
945 945 email_key = _hash_key(email)
946 946 if cache:
947 947 q = q.options(
948 948 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
949 949
950 950 ret = q.scalar()
951 951 if ret is None:
952 952 q = UserEmailMap.query()
953 953 # try fetching in alternate email map
954 954 if case_insensitive:
955 955 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
956 956 else:
957 957 q = q.filter(UserEmailMap.email == email)
958 958 q = q.options(joinedload(UserEmailMap.user))
959 959 if cache:
960 960 q = q.options(
961 961 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
962 962 ret = getattr(q.scalar(), 'user', None)
963 963
964 964 return ret
965 965
966 966 @classmethod
967 967 def get_from_cs_author(cls, author):
968 968 """
969 969 Tries to get User objects out of commit author string
970 970
971 971 :param author:
972 972 """
973 973 from rhodecode.lib.helpers import email, author_name
974 974 # Valid email in the attribute passed, see if they're in the system
975 975 _email = email(author)
976 976 if _email:
977 977 user = cls.get_by_email(_email, case_insensitive=True)
978 978 if user:
979 979 return user
980 980 # Maybe we can match by username?
981 981 _author = author_name(author)
982 982 user = cls.get_by_username(_author, case_insensitive=True)
983 983 if user:
984 984 return user
985 985
986 986 def update_userdata(self, **kwargs):
987 987 usr = self
988 988 old = usr.user_data
989 989 old.update(**kwargs)
990 990 usr.user_data = old
991 991 Session().add(usr)
992 992 log.debug('updated userdata with %s', kwargs)
993 993
994 994 def update_lastlogin(self):
995 995 """Update user lastlogin"""
996 996 self.last_login = datetime.datetime.now()
997 997 Session().add(self)
998 998 log.debug('updated user %s lastlogin', self.username)
999 999
1000 1000 def update_password(self, new_password):
1001 1001 from rhodecode.lib.auth import get_crypt_password
1002 1002
1003 1003 self.password = get_crypt_password(new_password)
1004 1004 Session().add(self)
1005 1005
1006 1006 @classmethod
1007 1007 def get_first_super_admin(cls):
1008 1008 user = User.query()\
1009 1009 .filter(User.admin == true()) \
1010 1010 .order_by(User.user_id.asc()) \
1011 1011 .first()
1012 1012
1013 1013 if user is None:
1014 1014 raise Exception('FATAL: Missing administrative account!')
1015 1015 return user
1016 1016
1017 1017 @classmethod
1018 1018 def get_all_super_admins(cls, only_active=False):
1019 1019 """
1020 1020 Returns all admin accounts sorted by username
1021 1021 """
1022 1022 qry = User.query().filter(User.admin == true()).order_by(User.username.asc())
1023 1023 if only_active:
1024 1024 qry = qry.filter(User.active == true())
1025 1025 return qry.all()
1026 1026
1027 1027 @classmethod
1028 1028 def get_default_user(cls, cache=False, refresh=False):
1029 1029 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
1030 1030 if user is None:
1031 1031 raise Exception('FATAL: Missing default account!')
1032 1032 if refresh:
1033 1033 # The default user might be based on outdated state which
1034 1034 # has been loaded from the cache.
1035 1035 # A call to refresh() ensures that the
1036 1036 # latest state from the database is used.
1037 1037 Session().refresh(user)
1038 1038 return user
1039 1039
1040 1040 def _get_default_perms(self, user, suffix=''):
1041 1041 from rhodecode.model.permission import PermissionModel
1042 1042 return PermissionModel().get_default_perms(user.user_perms, suffix)
1043 1043
1044 1044 def get_default_perms(self, suffix=''):
1045 1045 return self._get_default_perms(self, suffix)
1046 1046
1047 1047 def get_api_data(self, include_secrets=False, details='full'):
1048 1048 """
1049 1049 Common function for generating user related data for API
1050 1050
1051 1051 :param include_secrets: By default secrets in the API data will be replaced
1052 1052 by a placeholder value to prevent exposing this data by accident. In case
1053 1053 this data shall be exposed, set this flag to ``True``.
1054 1054
1055 1055 :param details: details can be 'basic|full' basic gives only a subset of
1056 1056 the available user information that includes user_id, name and emails.
1057 1057 """
1058 1058 user = self
1059 1059 user_data = self.user_data
1060 1060 data = {
1061 1061 'user_id': user.user_id,
1062 1062 'username': user.username,
1063 1063 'firstname': user.name,
1064 1064 'lastname': user.lastname,
1065 'description': user.description,
1065 1066 'email': user.email,
1066 1067 'emails': user.emails,
1067 1068 }
1068 1069 if details == 'basic':
1069 1070 return data
1070 1071
1071 1072 auth_token_length = 40
1072 1073 auth_token_replacement = '*' * auth_token_length
1073 1074
1074 1075 extras = {
1075 1076 'auth_tokens': [auth_token_replacement],
1076 1077 'active': user.active,
1077 1078 'admin': user.admin,
1078 1079 'extern_type': user.extern_type,
1079 1080 'extern_name': user.extern_name,
1080 1081 'last_login': user.last_login,
1081 1082 'last_activity': user.last_activity,
1082 1083 'ip_addresses': user.ip_addresses,
1083 1084 'language': user_data.get('language')
1084 1085 }
1085 1086 data.update(extras)
1086 1087
1087 1088 if include_secrets:
1088 1089 data['auth_tokens'] = user.auth_tokens
1089 1090 return data
1090 1091
1091 1092 def __json__(self):
1092 1093 data = {
1093 1094 'full_name': self.full_name,
1094 1095 'full_name_or_username': self.full_name_or_username,
1095 1096 'short_contact': self.short_contact,
1096 1097 'full_contact': self.full_contact,
1097 1098 }
1098 1099 data.update(self.get_api_data())
1099 1100 return data
1100 1101
1101 1102
1102 1103 class UserApiKeys(Base, BaseModel):
1103 1104 __tablename__ = 'user_api_keys'
1104 1105 __table_args__ = (
1105 1106 Index('uak_api_key_idx', 'api_key'),
1106 1107 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1107 1108 base_table_args
1108 1109 )
1109 1110 __mapper_args__ = {}
1110 1111
1111 1112 # ApiKey role
1112 1113 ROLE_ALL = 'token_role_all'
1113 1114 ROLE_HTTP = 'token_role_http'
1114 1115 ROLE_VCS = 'token_role_vcs'
1115 1116 ROLE_API = 'token_role_api'
1116 1117 ROLE_FEED = 'token_role_feed'
1117 1118 ROLE_ARTIFACT_DOWNLOAD = 'role_artifact_download'
1118 1119 ROLE_PASSWORD_RESET = 'token_password_reset'
1119 1120
1120 1121 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED, ROLE_ARTIFACT_DOWNLOAD]
1121 1122
1122 1123 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1123 1124 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1124 1125 api_key = Column("api_key", String(255), nullable=False, unique=True)
1125 1126 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1126 1127 expires = Column('expires', Float(53), nullable=False)
1127 1128 role = Column('role', String(255), nullable=True)
1128 1129 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1129 1130
1130 1131 # scope columns
1131 1132 repo_id = Column(
1132 1133 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1133 1134 nullable=True, unique=None, default=None)
1134 1135 repo = relationship('Repository', lazy='joined')
1135 1136
1136 1137 repo_group_id = Column(
1137 1138 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1138 1139 nullable=True, unique=None, default=None)
1139 1140 repo_group = relationship('RepoGroup', lazy='joined')
1140 1141
1141 1142 user = relationship('User', lazy='joined')
1142 1143
1143 1144 def __unicode__(self):
1144 1145 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1145 1146
1146 1147 def __json__(self):
1147 1148 data = {
1148 1149 'auth_token': self.api_key,
1149 1150 'role': self.role,
1150 1151 'scope': self.scope_humanized,
1151 1152 'expired': self.expired
1152 1153 }
1153 1154 return data
1154 1155
1155 1156 def get_api_data(self, include_secrets=False):
1156 1157 data = self.__json__()
1157 1158 if include_secrets:
1158 1159 return data
1159 1160 else:
1160 1161 data['auth_token'] = self.token_obfuscated
1161 1162 return data
1162 1163
1163 1164 @hybrid_property
1164 1165 def description_safe(self):
1165 1166 from rhodecode.lib import helpers as h
1166 1167 return h.escape(self.description)
1167 1168
1168 1169 @property
1169 1170 def expired(self):
1170 1171 if self.expires == -1:
1171 1172 return False
1172 1173 return time.time() > self.expires
1173 1174
1174 1175 @classmethod
1175 1176 def _get_role_name(cls, role):
1176 1177 return {
1177 1178 cls.ROLE_ALL: _('all'),
1178 1179 cls.ROLE_HTTP: _('http/web interface'),
1179 1180 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1180 1181 cls.ROLE_API: _('api calls'),
1181 1182 cls.ROLE_FEED: _('feed access'),
1182 1183 cls.ROLE_ARTIFACT_DOWNLOAD: _('artifacts downloads'),
1183 1184 }.get(role, role)
1184 1185
1185 1186 @property
1186 1187 def role_humanized(self):
1187 1188 return self._get_role_name(self.role)
1188 1189
1189 1190 def _get_scope(self):
1190 1191 if self.repo:
1191 1192 return 'Repository: {}'.format(self.repo.repo_name)
1192 1193 if self.repo_group:
1193 1194 return 'RepositoryGroup: {} (recursive)'.format(self.repo_group.group_name)
1194 1195 return 'Global'
1195 1196
1196 1197 @property
1197 1198 def scope_humanized(self):
1198 1199 return self._get_scope()
1199 1200
1200 1201 @property
1201 1202 def token_obfuscated(self):
1202 1203 if self.api_key:
1203 1204 return self.api_key[:4] + "****"
1204 1205
1205 1206
1206 1207 class UserEmailMap(Base, BaseModel):
1207 1208 __tablename__ = 'user_email_map'
1208 1209 __table_args__ = (
1209 1210 Index('uem_email_idx', 'email'),
1210 1211 UniqueConstraint('email'),
1211 1212 base_table_args
1212 1213 )
1213 1214 __mapper_args__ = {}
1214 1215
1215 1216 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1216 1217 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1217 1218 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1218 1219 user = relationship('User', lazy='joined')
1219 1220
1220 1221 @validates('_email')
1221 1222 def validate_email(self, key, email):
1222 1223 # check if this email is not main one
1223 1224 main_email = Session().query(User).filter(User.email == email).scalar()
1224 1225 if main_email is not None:
1225 1226 raise AttributeError('email %s is present is user table' % email)
1226 1227 return email
1227 1228
1228 1229 @hybrid_property
1229 1230 def email(self):
1230 1231 return self._email
1231 1232
1232 1233 @email.setter
1233 1234 def email(self, val):
1234 1235 self._email = val.lower() if val else None
1235 1236
1236 1237
1237 1238 class UserIpMap(Base, BaseModel):
1238 1239 __tablename__ = 'user_ip_map'
1239 1240 __table_args__ = (
1240 1241 UniqueConstraint('user_id', 'ip_addr'),
1241 1242 base_table_args
1242 1243 )
1243 1244 __mapper_args__ = {}
1244 1245
1245 1246 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1246 1247 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1247 1248 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1248 1249 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1249 1250 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1250 1251 user = relationship('User', lazy='joined')
1251 1252
1252 1253 @hybrid_property
1253 1254 def description_safe(self):
1254 1255 from rhodecode.lib import helpers as h
1255 1256 return h.escape(self.description)
1256 1257
1257 1258 @classmethod
1258 1259 def _get_ip_range(cls, ip_addr):
1259 1260 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1260 1261 return [str(net.network_address), str(net.broadcast_address)]
1261 1262
1262 1263 def __json__(self):
1263 1264 return {
1264 1265 'ip_addr': self.ip_addr,
1265 1266 'ip_range': self._get_ip_range(self.ip_addr),
1266 1267 }
1267 1268
1268 1269 def __unicode__(self):
1269 1270 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1270 1271 self.user_id, self.ip_addr)
1271 1272
1272 1273
1273 1274 class UserSshKeys(Base, BaseModel):
1274 1275 __tablename__ = 'user_ssh_keys'
1275 1276 __table_args__ = (
1276 1277 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1277 1278
1278 1279 UniqueConstraint('ssh_key_fingerprint'),
1279 1280
1280 1281 base_table_args
1281 1282 )
1282 1283 __mapper_args__ = {}
1283 1284
1284 1285 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1285 1286 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1286 1287 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1287 1288
1288 1289 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1289 1290
1290 1291 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1291 1292 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1292 1293 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1293 1294
1294 1295 user = relationship('User', lazy='joined')
1295 1296
1296 1297 def __json__(self):
1297 1298 data = {
1298 1299 'ssh_fingerprint': self.ssh_key_fingerprint,
1299 1300 'description': self.description,
1300 1301 'created_on': self.created_on
1301 1302 }
1302 1303 return data
1303 1304
1304 1305 def get_api_data(self):
1305 1306 data = self.__json__()
1306 1307 return data
1307 1308
1308 1309
1309 1310 class UserLog(Base, BaseModel):
1310 1311 __tablename__ = 'user_logs'
1311 1312 __table_args__ = (
1312 1313 base_table_args,
1313 1314 )
1314 1315
1315 1316 VERSION_1 = 'v1'
1316 1317 VERSION_2 = 'v2'
1317 1318 VERSIONS = [VERSION_1, VERSION_2]
1318 1319
1319 1320 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1320 1321 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1321 1322 username = Column("username", String(255), nullable=True, unique=None, default=None)
1322 1323 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1323 1324 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1324 1325 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1325 1326 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1326 1327 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1327 1328
1328 1329 version = Column("version", String(255), nullable=True, default=VERSION_1)
1329 1330 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1330 1331 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1331 1332
1332 1333 def __unicode__(self):
1333 1334 return u"<%s('id:%s:%s')>" % (
1334 1335 self.__class__.__name__, self.repository_name, self.action)
1335 1336
1336 1337 def __json__(self):
1337 1338 return {
1338 1339 'user_id': self.user_id,
1339 1340 'username': self.username,
1340 1341 'repository_id': self.repository_id,
1341 1342 'repository_name': self.repository_name,
1342 1343 'user_ip': self.user_ip,
1343 1344 'action_date': self.action_date,
1344 1345 'action': self.action,
1345 1346 }
1346 1347
1347 1348 @hybrid_property
1348 1349 def entry_id(self):
1349 1350 return self.user_log_id
1350 1351
1351 1352 @property
1352 1353 def action_as_day(self):
1353 1354 return datetime.date(*self.action_date.timetuple()[:3])
1354 1355
1355 1356 user = relationship('User')
1356 1357 repository = relationship('Repository', cascade='')
1357 1358
1358 1359
1359 1360 class UserGroup(Base, BaseModel):
1360 1361 __tablename__ = 'users_groups'
1361 1362 __table_args__ = (
1362 1363 base_table_args,
1363 1364 )
1364 1365
1365 1366 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1366 1367 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1367 1368 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1368 1369 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1369 1370 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1370 1371 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1371 1372 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1372 1373 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1373 1374
1374 1375 members = relationship('UserGroupMember', cascade="all, delete-orphan", lazy="joined")
1375 1376 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1376 1377 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1377 1378 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1378 1379 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1379 1380 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1380 1381
1381 1382 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1382 1383 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1383 1384
1384 1385 @classmethod
1385 1386 def _load_group_data(cls, column):
1386 1387 if not column:
1387 1388 return {}
1388 1389
1389 1390 try:
1390 1391 return json.loads(column) or {}
1391 1392 except TypeError:
1392 1393 return {}
1393 1394
1394 1395 @hybrid_property
1395 1396 def description_safe(self):
1396 1397 from rhodecode.lib import helpers as h
1397 1398 return h.escape(self.user_group_description)
1398 1399
1399 1400 @hybrid_property
1400 1401 def group_data(self):
1401 1402 return self._load_group_data(self._group_data)
1402 1403
1403 1404 @group_data.expression
1404 1405 def group_data(self, **kwargs):
1405 1406 return self._group_data
1406 1407
1407 1408 @group_data.setter
1408 1409 def group_data(self, val):
1409 1410 try:
1410 1411 self._group_data = json.dumps(val)
1411 1412 except Exception:
1412 1413 log.error(traceback.format_exc())
1413 1414
1414 1415 @classmethod
1415 1416 def _load_sync(cls, group_data):
1416 1417 if group_data:
1417 1418 return group_data.get('extern_type')
1418 1419
1419 1420 @property
1420 1421 def sync(self):
1421 1422 return self._load_sync(self.group_data)
1422 1423
1423 1424 def __unicode__(self):
1424 1425 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1425 1426 self.users_group_id,
1426 1427 self.users_group_name)
1427 1428
1428 1429 @classmethod
1429 1430 def get_by_group_name(cls, group_name, cache=False,
1430 1431 case_insensitive=False):
1431 1432 if case_insensitive:
1432 1433 q = cls.query().filter(func.lower(cls.users_group_name) ==
1433 1434 func.lower(group_name))
1434 1435
1435 1436 else:
1436 1437 q = cls.query().filter(cls.users_group_name == group_name)
1437 1438 if cache:
1438 1439 q = q.options(
1439 1440 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1440 1441 return q.scalar()
1441 1442
1442 1443 @classmethod
1443 1444 def get(cls, user_group_id, cache=False):
1444 1445 if not user_group_id:
1445 1446 return
1446 1447
1447 1448 user_group = cls.query()
1448 1449 if cache:
1449 1450 user_group = user_group.options(
1450 1451 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1451 1452 return user_group.get(user_group_id)
1452 1453
1453 1454 def permissions(self, with_admins=True, with_owner=True,
1454 1455 expand_from_user_groups=False):
1455 1456 """
1456 1457 Permissions for user groups
1457 1458 """
1458 1459 _admin_perm = 'usergroup.admin'
1459 1460
1460 1461 owner_row = []
1461 1462 if with_owner:
1462 1463 usr = AttributeDict(self.user.get_dict())
1463 1464 usr.owner_row = True
1464 1465 usr.permission = _admin_perm
1465 1466 owner_row.append(usr)
1466 1467
1467 1468 super_admin_ids = []
1468 1469 super_admin_rows = []
1469 1470 if with_admins:
1470 1471 for usr in User.get_all_super_admins():
1471 1472 super_admin_ids.append(usr.user_id)
1472 1473 # if this admin is also owner, don't double the record
1473 1474 if usr.user_id == owner_row[0].user_id:
1474 1475 owner_row[0].admin_row = True
1475 1476 else:
1476 1477 usr = AttributeDict(usr.get_dict())
1477 1478 usr.admin_row = True
1478 1479 usr.permission = _admin_perm
1479 1480 super_admin_rows.append(usr)
1480 1481
1481 1482 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1482 1483 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1483 1484 joinedload(UserUserGroupToPerm.user),
1484 1485 joinedload(UserUserGroupToPerm.permission),)
1485 1486
1486 1487 # get owners and admins and permissions. We do a trick of re-writing
1487 1488 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1488 1489 # has a global reference and changing one object propagates to all
1489 1490 # others. This means if admin is also an owner admin_row that change
1490 1491 # would propagate to both objects
1491 1492 perm_rows = []
1492 1493 for _usr in q.all():
1493 1494 usr = AttributeDict(_usr.user.get_dict())
1494 1495 # if this user is also owner/admin, mark as duplicate record
1495 1496 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
1496 1497 usr.duplicate_perm = True
1497 1498 usr.permission = _usr.permission.permission_name
1498 1499 perm_rows.append(usr)
1499 1500
1500 1501 # filter the perm rows by 'default' first and then sort them by
1501 1502 # admin,write,read,none permissions sorted again alphabetically in
1502 1503 # each group
1503 1504 perm_rows = sorted(perm_rows, key=display_user_sort)
1504 1505
1505 1506 user_groups_rows = []
1506 1507 if expand_from_user_groups:
1507 1508 for ug in self.permission_user_groups(with_members=True):
1508 1509 for user_data in ug.members:
1509 1510 user_groups_rows.append(user_data)
1510 1511
1511 1512 return super_admin_rows + owner_row + perm_rows + user_groups_rows
1512 1513
1513 1514 def permission_user_groups(self, with_members=False):
1514 1515 q = UserGroupUserGroupToPerm.query()\
1515 1516 .filter(UserGroupUserGroupToPerm.target_user_group == self)
1516 1517 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1517 1518 joinedload(UserGroupUserGroupToPerm.target_user_group),
1518 1519 joinedload(UserGroupUserGroupToPerm.permission),)
1519 1520
1520 1521 perm_rows = []
1521 1522 for _user_group in q.all():
1522 1523 entry = AttributeDict(_user_group.user_group.get_dict())
1523 1524 entry.permission = _user_group.permission.permission_name
1524 1525 if with_members:
1525 1526 entry.members = [x.user.get_dict()
1526 1527 for x in _user_group.user_group.members]
1527 1528 perm_rows.append(entry)
1528 1529
1529 1530 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1530 1531 return perm_rows
1531 1532
1532 1533 def _get_default_perms(self, user_group, suffix=''):
1533 1534 from rhodecode.model.permission import PermissionModel
1534 1535 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1535 1536
1536 1537 def get_default_perms(self, suffix=''):
1537 1538 return self._get_default_perms(self, suffix)
1538 1539
1539 1540 def get_api_data(self, with_group_members=True, include_secrets=False):
1540 1541 """
1541 1542 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1542 1543 basically forwarded.
1543 1544
1544 1545 """
1545 1546 user_group = self
1546 1547 data = {
1547 1548 'users_group_id': user_group.users_group_id,
1548 1549 'group_name': user_group.users_group_name,
1549 1550 'group_description': user_group.user_group_description,
1550 1551 'active': user_group.users_group_active,
1551 1552 'owner': user_group.user.username,
1552 1553 'sync': user_group.sync,
1553 1554 'owner_email': user_group.user.email,
1554 1555 }
1555 1556
1556 1557 if with_group_members:
1557 1558 users = []
1558 1559 for user in user_group.members:
1559 1560 user = user.user
1560 1561 users.append(user.get_api_data(include_secrets=include_secrets))
1561 1562 data['users'] = users
1562 1563
1563 1564 return data
1564 1565
1565 1566
1566 1567 class UserGroupMember(Base, BaseModel):
1567 1568 __tablename__ = 'users_groups_members'
1568 1569 __table_args__ = (
1569 1570 base_table_args,
1570 1571 )
1571 1572
1572 1573 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1573 1574 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1574 1575 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1575 1576
1576 1577 user = relationship('User', lazy='joined')
1577 1578 users_group = relationship('UserGroup')
1578 1579
1579 1580 def __init__(self, gr_id='', u_id=''):
1580 1581 self.users_group_id = gr_id
1581 1582 self.user_id = u_id
1582 1583
1583 1584
1584 1585 class RepositoryField(Base, BaseModel):
1585 1586 __tablename__ = 'repositories_fields'
1586 1587 __table_args__ = (
1587 1588 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1588 1589 base_table_args,
1589 1590 )
1590 1591
1591 1592 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1592 1593
1593 1594 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1594 1595 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1595 1596 field_key = Column("field_key", String(250))
1596 1597 field_label = Column("field_label", String(1024), nullable=False)
1597 1598 field_value = Column("field_value", String(10000), nullable=False)
1598 1599 field_desc = Column("field_desc", String(1024), nullable=False)
1599 1600 field_type = Column("field_type", String(255), nullable=False, unique=None)
1600 1601 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1601 1602
1602 1603 repository = relationship('Repository')
1603 1604
1604 1605 @property
1605 1606 def field_key_prefixed(self):
1606 1607 return 'ex_%s' % self.field_key
1607 1608
1608 1609 @classmethod
1609 1610 def un_prefix_key(cls, key):
1610 1611 if key.startswith(cls.PREFIX):
1611 1612 return key[len(cls.PREFIX):]
1612 1613 return key
1613 1614
1614 1615 @classmethod
1615 1616 def get_by_key_name(cls, key, repo):
1616 1617 row = cls.query()\
1617 1618 .filter(cls.repository == repo)\
1618 1619 .filter(cls.field_key == key).scalar()
1619 1620 return row
1620 1621
1621 1622
1622 1623 class Repository(Base, BaseModel):
1623 1624 __tablename__ = 'repositories'
1624 1625 __table_args__ = (
1625 1626 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1626 1627 base_table_args,
1627 1628 )
1628 1629 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1629 1630 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1630 1631 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1631 1632
1632 1633 STATE_CREATED = 'repo_state_created'
1633 1634 STATE_PENDING = 'repo_state_pending'
1634 1635 STATE_ERROR = 'repo_state_error'
1635 1636
1636 1637 LOCK_AUTOMATIC = 'lock_auto'
1637 1638 LOCK_API = 'lock_api'
1638 1639 LOCK_WEB = 'lock_web'
1639 1640 LOCK_PULL = 'lock_pull'
1640 1641
1641 1642 NAME_SEP = URL_SEP
1642 1643
1643 1644 repo_id = Column(
1644 1645 "repo_id", Integer(), nullable=False, unique=True, default=None,
1645 1646 primary_key=True)
1646 1647 _repo_name = Column(
1647 1648 "repo_name", Text(), nullable=False, default=None)
1648 1649 _repo_name_hash = Column(
1649 1650 "repo_name_hash", String(255), nullable=False, unique=True)
1650 1651 repo_state = Column("repo_state", String(255), nullable=True)
1651 1652
1652 1653 clone_uri = Column(
1653 1654 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1654 1655 default=None)
1655 1656 push_uri = Column(
1656 1657 "push_uri", EncryptedTextValue(), nullable=True, unique=False,
1657 1658 default=None)
1658 1659 repo_type = Column(
1659 1660 "repo_type", String(255), nullable=False, unique=False, default=None)
1660 1661 user_id = Column(
1661 1662 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1662 1663 unique=False, default=None)
1663 1664 private = Column(
1664 1665 "private", Boolean(), nullable=True, unique=None, default=None)
1665 1666 archived = Column(
1666 1667 "archived", Boolean(), nullable=True, unique=None, default=None)
1667 1668 enable_statistics = Column(
1668 1669 "statistics", Boolean(), nullable=True, unique=None, default=True)
1669 1670 enable_downloads = Column(
1670 1671 "downloads", Boolean(), nullable=True, unique=None, default=True)
1671 1672 description = Column(
1672 1673 "description", String(10000), nullable=True, unique=None, default=None)
1673 1674 created_on = Column(
1674 1675 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1675 1676 default=datetime.datetime.now)
1676 1677 updated_on = Column(
1677 1678 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1678 1679 default=datetime.datetime.now)
1679 1680 _landing_revision = Column(
1680 1681 "landing_revision", String(255), nullable=False, unique=False,
1681 1682 default=None)
1682 1683 enable_locking = Column(
1683 1684 "enable_locking", Boolean(), nullable=False, unique=None,
1684 1685 default=False)
1685 1686 _locked = Column(
1686 1687 "locked", String(255), nullable=True, unique=False, default=None)
1687 1688 _changeset_cache = Column(
1688 1689 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1689 1690
1690 1691 fork_id = Column(
1691 1692 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1692 1693 nullable=True, unique=False, default=None)
1693 1694 group_id = Column(
1694 1695 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1695 1696 unique=False, default=None)
1696 1697
1697 1698 user = relationship('User', lazy='joined')
1698 1699 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1699 1700 group = relationship('RepoGroup', lazy='joined')
1700 1701 repo_to_perm = relationship(
1701 1702 'UserRepoToPerm', cascade='all',
1702 1703 order_by='UserRepoToPerm.repo_to_perm_id')
1703 1704 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1704 1705 stats = relationship('Statistics', cascade='all', uselist=False)
1705 1706
1706 1707 followers = relationship(
1707 1708 'UserFollowing',
1708 1709 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1709 1710 cascade='all')
1710 1711 extra_fields = relationship(
1711 1712 'RepositoryField', cascade="all, delete-orphan")
1712 1713 logs = relationship('UserLog')
1713 1714 comments = relationship(
1714 1715 'ChangesetComment', cascade="all, delete-orphan")
1715 1716 pull_requests_source = relationship(
1716 1717 'PullRequest',
1717 1718 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1718 1719 cascade="all, delete-orphan")
1719 1720 pull_requests_target = relationship(
1720 1721 'PullRequest',
1721 1722 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1722 1723 cascade="all, delete-orphan")
1723 1724 ui = relationship('RepoRhodeCodeUi', cascade="all")
1724 1725 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1725 1726 integrations = relationship('Integration', cascade="all, delete-orphan")
1726 1727
1727 1728 scoped_tokens = relationship('UserApiKeys', cascade="all")
1728 1729
1729 1730 # no cascade, set NULL
1730 1731 artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_id==Repository.repo_id')
1731 1732
1732 1733 def __unicode__(self):
1733 1734 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1734 1735 safe_unicode(self.repo_name))
1735 1736
1736 1737 @hybrid_property
1737 1738 def description_safe(self):
1738 1739 from rhodecode.lib import helpers as h
1739 1740 return h.escape(self.description)
1740 1741
1741 1742 @hybrid_property
1742 1743 def landing_rev(self):
1743 1744 # always should return [rev_type, rev]
1744 1745 if self._landing_revision:
1745 1746 _rev_info = self._landing_revision.split(':')
1746 1747 if len(_rev_info) < 2:
1747 1748 _rev_info.insert(0, 'rev')
1748 1749 return [_rev_info[0], _rev_info[1]]
1749 1750 return [None, None]
1750 1751
1751 1752 @landing_rev.setter
1752 1753 def landing_rev(self, val):
1753 1754 if ':' not in val:
1754 1755 raise ValueError('value must be delimited with `:` and consist '
1755 1756 'of <rev_type>:<rev>, got %s instead' % val)
1756 1757 self._landing_revision = val
1757 1758
1758 1759 @hybrid_property
1759 1760 def locked(self):
1760 1761 if self._locked:
1761 1762 user_id, timelocked, reason = self._locked.split(':')
1762 1763 lock_values = int(user_id), timelocked, reason
1763 1764 else:
1764 1765 lock_values = [None, None, None]
1765 1766 return lock_values
1766 1767
1767 1768 @locked.setter
1768 1769 def locked(self, val):
1769 1770 if val and isinstance(val, (list, tuple)):
1770 1771 self._locked = ':'.join(map(str, val))
1771 1772 else:
1772 1773 self._locked = None
1773 1774
1774 1775 @hybrid_property
1775 1776 def changeset_cache(self):
1776 1777 from rhodecode.lib.vcs.backends.base import EmptyCommit
1777 1778 dummy = EmptyCommit().__json__()
1778 1779 if not self._changeset_cache:
1779 1780 dummy['source_repo_id'] = self.repo_id
1780 1781 return json.loads(json.dumps(dummy))
1781 1782
1782 1783 try:
1783 1784 return json.loads(self._changeset_cache)
1784 1785 except TypeError:
1785 1786 return dummy
1786 1787 except Exception:
1787 1788 log.error(traceback.format_exc())
1788 1789 return dummy
1789 1790
1790 1791 @changeset_cache.setter
1791 1792 def changeset_cache(self, val):
1792 1793 try:
1793 1794 self._changeset_cache = json.dumps(val)
1794 1795 except Exception:
1795 1796 log.error(traceback.format_exc())
1796 1797
1797 1798 @hybrid_property
1798 1799 def repo_name(self):
1799 1800 return self._repo_name
1800 1801
1801 1802 @repo_name.setter
1802 1803 def repo_name(self, value):
1803 1804 self._repo_name = value
1804 1805 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1805 1806
1806 1807 @classmethod
1807 1808 def normalize_repo_name(cls, repo_name):
1808 1809 """
1809 1810 Normalizes os specific repo_name to the format internally stored inside
1810 1811 database using URL_SEP
1811 1812
1812 1813 :param cls:
1813 1814 :param repo_name:
1814 1815 """
1815 1816 return cls.NAME_SEP.join(repo_name.split(os.sep))
1816 1817
1817 1818 @classmethod
1818 1819 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1819 1820 session = Session()
1820 1821 q = session.query(cls).filter(cls.repo_name == repo_name)
1821 1822
1822 1823 if cache:
1823 1824 if identity_cache:
1824 1825 val = cls.identity_cache(session, 'repo_name', repo_name)
1825 1826 if val:
1826 1827 return val
1827 1828 else:
1828 1829 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1829 1830 q = q.options(
1830 1831 FromCache("sql_cache_short", cache_key))
1831 1832
1832 1833 return q.scalar()
1833 1834
1834 1835 @classmethod
1835 1836 def get_by_id_or_repo_name(cls, repoid):
1836 1837 if isinstance(repoid, (int, long)):
1837 1838 try:
1838 1839 repo = cls.get(repoid)
1839 1840 except ValueError:
1840 1841 repo = None
1841 1842 else:
1842 1843 repo = cls.get_by_repo_name(repoid)
1843 1844 return repo
1844 1845
1845 1846 @classmethod
1846 1847 def get_by_full_path(cls, repo_full_path):
1847 1848 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1848 1849 repo_name = cls.normalize_repo_name(repo_name)
1849 1850 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1850 1851
1851 1852 @classmethod
1852 1853 def get_repo_forks(cls, repo_id):
1853 1854 return cls.query().filter(Repository.fork_id == repo_id)
1854 1855
1855 1856 @classmethod
1856 1857 def base_path(cls):
1857 1858 """
1858 1859 Returns base path when all repos are stored
1859 1860
1860 1861 :param cls:
1861 1862 """
1862 1863 q = Session().query(RhodeCodeUi)\
1863 1864 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1864 1865 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1865 1866 return q.one().ui_value
1866 1867
1867 1868 @classmethod
1868 1869 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1869 1870 case_insensitive=True, archived=False):
1870 1871 q = Repository.query()
1871 1872
1872 1873 if not archived:
1873 1874 q = q.filter(Repository.archived.isnot(true()))
1874 1875
1875 1876 if not isinstance(user_id, Optional):
1876 1877 q = q.filter(Repository.user_id == user_id)
1877 1878
1878 1879 if not isinstance(group_id, Optional):
1879 1880 q = q.filter(Repository.group_id == group_id)
1880 1881
1881 1882 if case_insensitive:
1882 1883 q = q.order_by(func.lower(Repository.repo_name))
1883 1884 else:
1884 1885 q = q.order_by(Repository.repo_name)
1885 1886
1886 1887 return q.all()
1887 1888
1888 1889 @property
1889 1890 def repo_uid(self):
1890 1891 return '_{}'.format(self.repo_id)
1891 1892
1892 1893 @property
1893 1894 def forks(self):
1894 1895 """
1895 1896 Return forks of this repo
1896 1897 """
1897 1898 return Repository.get_repo_forks(self.repo_id)
1898 1899
1899 1900 @property
1900 1901 def parent(self):
1901 1902 """
1902 1903 Returns fork parent
1903 1904 """
1904 1905 return self.fork
1905 1906
1906 1907 @property
1907 1908 def just_name(self):
1908 1909 return self.repo_name.split(self.NAME_SEP)[-1]
1909 1910
1910 1911 @property
1911 1912 def groups_with_parents(self):
1912 1913 groups = []
1913 1914 if self.group is None:
1914 1915 return groups
1915 1916
1916 1917 cur_gr = self.group
1917 1918 groups.insert(0, cur_gr)
1918 1919 while 1:
1919 1920 gr = getattr(cur_gr, 'parent_group', None)
1920 1921 cur_gr = cur_gr.parent_group
1921 1922 if gr is None:
1922 1923 break
1923 1924 groups.insert(0, gr)
1924 1925
1925 1926 return groups
1926 1927
1927 1928 @property
1928 1929 def groups_and_repo(self):
1929 1930 return self.groups_with_parents, self
1930 1931
1931 1932 @LazyProperty
1932 1933 def repo_path(self):
1933 1934 """
1934 1935 Returns base full path for that repository means where it actually
1935 1936 exists on a filesystem
1936 1937 """
1937 1938 q = Session().query(RhodeCodeUi).filter(
1938 1939 RhodeCodeUi.ui_key == self.NAME_SEP)
1939 1940 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1940 1941 return q.one().ui_value
1941 1942
1942 1943 @property
1943 1944 def repo_full_path(self):
1944 1945 p = [self.repo_path]
1945 1946 # we need to split the name by / since this is how we store the
1946 1947 # names in the database, but that eventually needs to be converted
1947 1948 # into a valid system path
1948 1949 p += self.repo_name.split(self.NAME_SEP)
1949 1950 return os.path.join(*map(safe_unicode, p))
1950 1951
1951 1952 @property
1952 1953 def cache_keys(self):
1953 1954 """
1954 1955 Returns associated cache keys for that repo
1955 1956 """
1956 1957 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
1957 1958 repo_id=self.repo_id)
1958 1959 return CacheKey.query()\
1959 1960 .filter(CacheKey.cache_args == invalidation_namespace)\
1960 1961 .order_by(CacheKey.cache_key)\
1961 1962 .all()
1962 1963
1963 1964 @property
1964 1965 def cached_diffs_relative_dir(self):
1965 1966 """
1966 1967 Return a relative to the repository store path of cached diffs
1967 1968 used for safe display for users, who shouldn't know the absolute store
1968 1969 path
1969 1970 """
1970 1971 return os.path.join(
1971 1972 os.path.dirname(self.repo_name),
1972 1973 self.cached_diffs_dir.split(os.path.sep)[-1])
1973 1974
1974 1975 @property
1975 1976 def cached_diffs_dir(self):
1976 1977 path = self.repo_full_path
1977 1978 return os.path.join(
1978 1979 os.path.dirname(path),
1979 1980 '.__shadow_diff_cache_repo_{}'.format(self.repo_id))
1980 1981
1981 1982 def cached_diffs(self):
1982 1983 diff_cache_dir = self.cached_diffs_dir
1983 1984 if os.path.isdir(diff_cache_dir):
1984 1985 return os.listdir(diff_cache_dir)
1985 1986 return []
1986 1987
1987 1988 def shadow_repos(self):
1988 1989 shadow_repos_pattern = '.__shadow_repo_{}'.format(self.repo_id)
1989 1990 return [
1990 1991 x for x in os.listdir(os.path.dirname(self.repo_full_path))
1991 1992 if x.startswith(shadow_repos_pattern)]
1992 1993
1993 1994 def get_new_name(self, repo_name):
1994 1995 """
1995 1996 returns new full repository name based on assigned group and new new
1996 1997
1997 1998 :param group_name:
1998 1999 """
1999 2000 path_prefix = self.group.full_path_splitted if self.group else []
2000 2001 return self.NAME_SEP.join(path_prefix + [repo_name])
2001 2002
2002 2003 @property
2003 2004 def _config(self):
2004 2005 """
2005 2006 Returns db based config object.
2006 2007 """
2007 2008 from rhodecode.lib.utils import make_db_config
2008 2009 return make_db_config(clear_session=False, repo=self)
2009 2010
2010 2011 def permissions(self, with_admins=True, with_owner=True,
2011 2012 expand_from_user_groups=False):
2012 2013 """
2013 2014 Permissions for repositories
2014 2015 """
2015 2016 _admin_perm = 'repository.admin'
2016 2017
2017 2018 owner_row = []
2018 2019 if with_owner:
2019 2020 usr = AttributeDict(self.user.get_dict())
2020 2021 usr.owner_row = True
2021 2022 usr.permission = _admin_perm
2022 2023 usr.permission_id = None
2023 2024 owner_row.append(usr)
2024 2025
2025 2026 super_admin_ids = []
2026 2027 super_admin_rows = []
2027 2028 if with_admins:
2028 2029 for usr in User.get_all_super_admins():
2029 2030 super_admin_ids.append(usr.user_id)
2030 2031 # if this admin is also owner, don't double the record
2031 2032 if usr.user_id == owner_row[0].user_id:
2032 2033 owner_row[0].admin_row = True
2033 2034 else:
2034 2035 usr = AttributeDict(usr.get_dict())
2035 2036 usr.admin_row = True
2036 2037 usr.permission = _admin_perm
2037 2038 usr.permission_id = None
2038 2039 super_admin_rows.append(usr)
2039 2040
2040 2041 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
2041 2042 q = q.options(joinedload(UserRepoToPerm.repository),
2042 2043 joinedload(UserRepoToPerm.user),
2043 2044 joinedload(UserRepoToPerm.permission),)
2044 2045
2045 2046 # get owners and admins and permissions. We do a trick of re-writing
2046 2047 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2047 2048 # has a global reference and changing one object propagates to all
2048 2049 # others. This means if admin is also an owner admin_row that change
2049 2050 # would propagate to both objects
2050 2051 perm_rows = []
2051 2052 for _usr in q.all():
2052 2053 usr = AttributeDict(_usr.user.get_dict())
2053 2054 # if this user is also owner/admin, mark as duplicate record
2054 2055 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2055 2056 usr.duplicate_perm = True
2056 2057 # also check if this permission is maybe used by branch_permissions
2057 2058 if _usr.branch_perm_entry:
2058 2059 usr.branch_rules = [x.branch_rule_id for x in _usr.branch_perm_entry]
2059 2060
2060 2061 usr.permission = _usr.permission.permission_name
2061 2062 usr.permission_id = _usr.repo_to_perm_id
2062 2063 perm_rows.append(usr)
2063 2064
2064 2065 # filter the perm rows by 'default' first and then sort them by
2065 2066 # admin,write,read,none permissions sorted again alphabetically in
2066 2067 # each group
2067 2068 perm_rows = sorted(perm_rows, key=display_user_sort)
2068 2069
2069 2070 user_groups_rows = []
2070 2071 if expand_from_user_groups:
2071 2072 for ug in self.permission_user_groups(with_members=True):
2072 2073 for user_data in ug.members:
2073 2074 user_groups_rows.append(user_data)
2074 2075
2075 2076 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2076 2077
2077 2078 def permission_user_groups(self, with_members=True):
2078 2079 q = UserGroupRepoToPerm.query()\
2079 2080 .filter(UserGroupRepoToPerm.repository == self)
2080 2081 q = q.options(joinedload(UserGroupRepoToPerm.repository),
2081 2082 joinedload(UserGroupRepoToPerm.users_group),
2082 2083 joinedload(UserGroupRepoToPerm.permission),)
2083 2084
2084 2085 perm_rows = []
2085 2086 for _user_group in q.all():
2086 2087 entry = AttributeDict(_user_group.users_group.get_dict())
2087 2088 entry.permission = _user_group.permission.permission_name
2088 2089 if with_members:
2089 2090 entry.members = [x.user.get_dict()
2090 2091 for x in _user_group.users_group.members]
2091 2092 perm_rows.append(entry)
2092 2093
2093 2094 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2094 2095 return perm_rows
2095 2096
2096 2097 def get_api_data(self, include_secrets=False):
2097 2098 """
2098 2099 Common function for generating repo api data
2099 2100
2100 2101 :param include_secrets: See :meth:`User.get_api_data`.
2101 2102
2102 2103 """
2103 2104 # TODO: mikhail: Here there is an anti-pattern, we probably need to
2104 2105 # move this methods on models level.
2105 2106 from rhodecode.model.settings import SettingsModel
2106 2107 from rhodecode.model.repo import RepoModel
2107 2108
2108 2109 repo = self
2109 2110 _user_id, _time, _reason = self.locked
2110 2111
2111 2112 data = {
2112 2113 'repo_id': repo.repo_id,
2113 2114 'repo_name': repo.repo_name,
2114 2115 'repo_type': repo.repo_type,
2115 2116 'clone_uri': repo.clone_uri or '',
2116 2117 'push_uri': repo.push_uri or '',
2117 2118 'url': RepoModel().get_url(self),
2118 2119 'private': repo.private,
2119 2120 'created_on': repo.created_on,
2120 2121 'description': repo.description_safe,
2121 2122 'landing_rev': repo.landing_rev,
2122 2123 'owner': repo.user.username,
2123 2124 'fork_of': repo.fork.repo_name if repo.fork else None,
2124 2125 'fork_of_id': repo.fork.repo_id if repo.fork else None,
2125 2126 'enable_statistics': repo.enable_statistics,
2126 2127 'enable_locking': repo.enable_locking,
2127 2128 'enable_downloads': repo.enable_downloads,
2128 2129 'last_changeset': repo.changeset_cache,
2129 2130 'locked_by': User.get(_user_id).get_api_data(
2130 2131 include_secrets=include_secrets) if _user_id else None,
2131 2132 'locked_date': time_to_datetime(_time) if _time else None,
2132 2133 'lock_reason': _reason if _reason else None,
2133 2134 }
2134 2135
2135 2136 # TODO: mikhail: should be per-repo settings here
2136 2137 rc_config = SettingsModel().get_all_settings()
2137 2138 repository_fields = str2bool(
2138 2139 rc_config.get('rhodecode_repository_fields'))
2139 2140 if repository_fields:
2140 2141 for f in self.extra_fields:
2141 2142 data[f.field_key_prefixed] = f.field_value
2142 2143
2143 2144 return data
2144 2145
2145 2146 @classmethod
2146 2147 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
2147 2148 if not lock_time:
2148 2149 lock_time = time.time()
2149 2150 if not lock_reason:
2150 2151 lock_reason = cls.LOCK_AUTOMATIC
2151 2152 repo.locked = [user_id, lock_time, lock_reason]
2152 2153 Session().add(repo)
2153 2154 Session().commit()
2154 2155
2155 2156 @classmethod
2156 2157 def unlock(cls, repo):
2157 2158 repo.locked = None
2158 2159 Session().add(repo)
2159 2160 Session().commit()
2160 2161
2161 2162 @classmethod
2162 2163 def getlock(cls, repo):
2163 2164 return repo.locked
2164 2165
2165 2166 def is_user_lock(self, user_id):
2166 2167 if self.lock[0]:
2167 2168 lock_user_id = safe_int(self.lock[0])
2168 2169 user_id = safe_int(user_id)
2169 2170 # both are ints, and they are equal
2170 2171 return all([lock_user_id, user_id]) and lock_user_id == user_id
2171 2172
2172 2173 return False
2173 2174
2174 2175 def get_locking_state(self, action, user_id, only_when_enabled=True):
2175 2176 """
2176 2177 Checks locking on this repository, if locking is enabled and lock is
2177 2178 present returns a tuple of make_lock, locked, locked_by.
2178 2179 make_lock can have 3 states None (do nothing) True, make lock
2179 2180 False release lock, This value is later propagated to hooks, which
2180 2181 do the locking. Think about this as signals passed to hooks what to do.
2181 2182
2182 2183 """
2183 2184 # TODO: johbo: This is part of the business logic and should be moved
2184 2185 # into the RepositoryModel.
2185 2186
2186 2187 if action not in ('push', 'pull'):
2187 2188 raise ValueError("Invalid action value: %s" % repr(action))
2188 2189
2189 2190 # defines if locked error should be thrown to user
2190 2191 currently_locked = False
2191 2192 # defines if new lock should be made, tri-state
2192 2193 make_lock = None
2193 2194 repo = self
2194 2195 user = User.get(user_id)
2195 2196
2196 2197 lock_info = repo.locked
2197 2198
2198 2199 if repo and (repo.enable_locking or not only_when_enabled):
2199 2200 if action == 'push':
2200 2201 # check if it's already locked !, if it is compare users
2201 2202 locked_by_user_id = lock_info[0]
2202 2203 if user.user_id == locked_by_user_id:
2203 2204 log.debug(
2204 2205 'Got `push` action from user %s, now unlocking', user)
2205 2206 # unlock if we have push from user who locked
2206 2207 make_lock = False
2207 2208 else:
2208 2209 # we're not the same user who locked, ban with
2209 2210 # code defined in settings (default is 423 HTTP Locked) !
2210 2211 log.debug('Repo %s is currently locked by %s', repo, user)
2211 2212 currently_locked = True
2212 2213 elif action == 'pull':
2213 2214 # [0] user [1] date
2214 2215 if lock_info[0] and lock_info[1]:
2215 2216 log.debug('Repo %s is currently locked by %s', repo, user)
2216 2217 currently_locked = True
2217 2218 else:
2218 2219 log.debug('Setting lock on repo %s by %s', repo, user)
2219 2220 make_lock = True
2220 2221
2221 2222 else:
2222 2223 log.debug('Repository %s do not have locking enabled', repo)
2223 2224
2224 2225 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2225 2226 make_lock, currently_locked, lock_info)
2226 2227
2227 2228 from rhodecode.lib.auth import HasRepoPermissionAny
2228 2229 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2229 2230 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2230 2231 # if we don't have at least write permission we cannot make a lock
2231 2232 log.debug('lock state reset back to FALSE due to lack '
2232 2233 'of at least read permission')
2233 2234 make_lock = False
2234 2235
2235 2236 return make_lock, currently_locked, lock_info
2236 2237
2237 2238 @property
2238 2239 def last_commit_cache_update_diff(self):
2239 2240 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2240 2241
2241 2242 @property
2242 2243 def last_commit_change(self):
2243 2244 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2244 2245 empty_date = datetime.datetime.fromtimestamp(0)
2245 2246 date_latest = self.changeset_cache.get('date', empty_date)
2246 2247 try:
2247 2248 return parse_datetime(date_latest)
2248 2249 except Exception:
2249 2250 return empty_date
2250 2251
2251 2252 @property
2252 2253 def last_db_change(self):
2253 2254 return self.updated_on
2254 2255
2255 2256 @property
2256 2257 def clone_uri_hidden(self):
2257 2258 clone_uri = self.clone_uri
2258 2259 if clone_uri:
2259 2260 import urlobject
2260 2261 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2261 2262 if url_obj.password:
2262 2263 clone_uri = url_obj.with_password('*****')
2263 2264 return clone_uri
2264 2265
2265 2266 @property
2266 2267 def push_uri_hidden(self):
2267 2268 push_uri = self.push_uri
2268 2269 if push_uri:
2269 2270 import urlobject
2270 2271 url_obj = urlobject.URLObject(cleaned_uri(push_uri))
2271 2272 if url_obj.password:
2272 2273 push_uri = url_obj.with_password('*****')
2273 2274 return push_uri
2274 2275
2275 2276 def clone_url(self, **override):
2276 2277 from rhodecode.model.settings import SettingsModel
2277 2278
2278 2279 uri_tmpl = None
2279 2280 if 'with_id' in override:
2280 2281 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2281 2282 del override['with_id']
2282 2283
2283 2284 if 'uri_tmpl' in override:
2284 2285 uri_tmpl = override['uri_tmpl']
2285 2286 del override['uri_tmpl']
2286 2287
2287 2288 ssh = False
2288 2289 if 'ssh' in override:
2289 2290 ssh = True
2290 2291 del override['ssh']
2291 2292
2292 2293 # we didn't override our tmpl from **overrides
2293 2294 request = get_current_request()
2294 2295 if not uri_tmpl:
2295 2296 if hasattr(request, 'call_context') and hasattr(request.call_context, 'rc_config'):
2296 2297 rc_config = request.call_context.rc_config
2297 2298 else:
2298 2299 rc_config = SettingsModel().get_all_settings(cache=True)
2299 2300 if ssh:
2300 2301 uri_tmpl = rc_config.get(
2301 2302 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2302 2303 else:
2303 2304 uri_tmpl = rc_config.get(
2304 2305 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2305 2306
2306 2307 return get_clone_url(request=request,
2307 2308 uri_tmpl=uri_tmpl,
2308 2309 repo_name=self.repo_name,
2309 2310 repo_id=self.repo_id, **override)
2310 2311
2311 2312 def set_state(self, state):
2312 2313 self.repo_state = state
2313 2314 Session().add(self)
2314 2315 #==========================================================================
2315 2316 # SCM PROPERTIES
2316 2317 #==========================================================================
2317 2318
2318 2319 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2319 2320 return get_commit_safe(
2320 2321 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2321 2322
2322 2323 def get_changeset(self, rev=None, pre_load=None):
2323 2324 warnings.warn("Use get_commit", DeprecationWarning)
2324 2325 commit_id = None
2325 2326 commit_idx = None
2326 2327 if isinstance(rev, compat.string_types):
2327 2328 commit_id = rev
2328 2329 else:
2329 2330 commit_idx = rev
2330 2331 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2331 2332 pre_load=pre_load)
2332 2333
2333 2334 def get_landing_commit(self):
2334 2335 """
2335 2336 Returns landing commit, or if that doesn't exist returns the tip
2336 2337 """
2337 2338 _rev_type, _rev = self.landing_rev
2338 2339 commit = self.get_commit(_rev)
2339 2340 if isinstance(commit, EmptyCommit):
2340 2341 return self.get_commit()
2341 2342 return commit
2342 2343
2343 2344 def flush_commit_cache(self):
2344 2345 self.update_commit_cache(cs_cache={'raw_id':'0'})
2345 2346 self.update_commit_cache()
2346 2347
2347 2348 def update_commit_cache(self, cs_cache=None, config=None):
2348 2349 """
2349 2350 Update cache of last commit for repository, keys should be::
2350 2351
2351 2352 source_repo_id
2352 2353 short_id
2353 2354 raw_id
2354 2355 revision
2355 2356 parents
2356 2357 message
2357 2358 date
2358 2359 author
2359 2360 updated_on
2360 2361
2361 2362 """
2362 2363 from rhodecode.lib.vcs.backends.base import BaseChangeset
2363 2364 if cs_cache is None:
2364 2365 # use no-cache version here
2365 2366 scm_repo = self.scm_instance(cache=False, config=config)
2366 2367
2367 2368 empty = scm_repo is None or scm_repo.is_empty()
2368 2369 if not empty:
2369 2370 cs_cache = scm_repo.get_commit(
2370 2371 pre_load=["author", "date", "message", "parents", "branch"])
2371 2372 else:
2372 2373 cs_cache = EmptyCommit()
2373 2374
2374 2375 if isinstance(cs_cache, BaseChangeset):
2375 2376 cs_cache = cs_cache.__json__()
2376 2377
2377 2378 def is_outdated(new_cs_cache):
2378 2379 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2379 2380 new_cs_cache['revision'] != self.changeset_cache['revision']):
2380 2381 return True
2381 2382 return False
2382 2383
2383 2384 # check if we have maybe already latest cached revision
2384 2385 if is_outdated(cs_cache) or not self.changeset_cache:
2385 2386 _default = datetime.datetime.utcnow()
2386 2387 last_change = cs_cache.get('date') or _default
2387 2388 # we check if last update is newer than the new value
2388 2389 # if yes, we use the current timestamp instead. Imagine you get
2389 2390 # old commit pushed 1y ago, we'd set last update 1y to ago.
2390 2391 last_change_timestamp = datetime_to_time(last_change)
2391 2392 current_timestamp = datetime_to_time(last_change)
2392 2393 if last_change_timestamp > current_timestamp:
2393 2394 cs_cache['date'] = _default
2394 2395
2395 2396 cs_cache['updated_on'] = time.time()
2396 2397 self.changeset_cache = cs_cache
2397 2398 self.updated_on = last_change
2398 2399 Session().add(self)
2399 2400 Session().commit()
2400 2401
2401 2402 log.debug('updated repo `%s` with new commit cache %s',
2402 2403 self.repo_name, cs_cache)
2403 2404 else:
2404 2405 cs_cache = self.changeset_cache
2405 2406 cs_cache['updated_on'] = time.time()
2406 2407 self.changeset_cache = cs_cache
2407 2408 Session().add(self)
2408 2409 Session().commit()
2409 2410
2410 2411 log.debug('Skipping update_commit_cache for repo:`%s` '
2411 2412 'commit already with latest changes', self.repo_name)
2412 2413
2413 2414 @property
2414 2415 def tip(self):
2415 2416 return self.get_commit('tip')
2416 2417
2417 2418 @property
2418 2419 def author(self):
2419 2420 return self.tip.author
2420 2421
2421 2422 @property
2422 2423 def last_change(self):
2423 2424 return self.scm_instance().last_change
2424 2425
2425 2426 def get_comments(self, revisions=None):
2426 2427 """
2427 2428 Returns comments for this repository grouped by revisions
2428 2429
2429 2430 :param revisions: filter query by revisions only
2430 2431 """
2431 2432 cmts = ChangesetComment.query()\
2432 2433 .filter(ChangesetComment.repo == self)
2433 2434 if revisions:
2434 2435 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2435 2436 grouped = collections.defaultdict(list)
2436 2437 for cmt in cmts.all():
2437 2438 grouped[cmt.revision].append(cmt)
2438 2439 return grouped
2439 2440
2440 2441 def statuses(self, revisions=None):
2441 2442 """
2442 2443 Returns statuses for this repository
2443 2444
2444 2445 :param revisions: list of revisions to get statuses for
2445 2446 """
2446 2447 statuses = ChangesetStatus.query()\
2447 2448 .filter(ChangesetStatus.repo == self)\
2448 2449 .filter(ChangesetStatus.version == 0)
2449 2450
2450 2451 if revisions:
2451 2452 # Try doing the filtering in chunks to avoid hitting limits
2452 2453 size = 500
2453 2454 status_results = []
2454 2455 for chunk in xrange(0, len(revisions), size):
2455 2456 status_results += statuses.filter(
2456 2457 ChangesetStatus.revision.in_(
2457 2458 revisions[chunk: chunk+size])
2458 2459 ).all()
2459 2460 else:
2460 2461 status_results = statuses.all()
2461 2462
2462 2463 grouped = {}
2463 2464
2464 2465 # maybe we have open new pullrequest without a status?
2465 2466 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2466 2467 status_lbl = ChangesetStatus.get_status_lbl(stat)
2467 2468 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2468 2469 for rev in pr.revisions:
2469 2470 pr_id = pr.pull_request_id
2470 2471 pr_repo = pr.target_repo.repo_name
2471 2472 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2472 2473
2473 2474 for stat in status_results:
2474 2475 pr_id = pr_repo = None
2475 2476 if stat.pull_request:
2476 2477 pr_id = stat.pull_request.pull_request_id
2477 2478 pr_repo = stat.pull_request.target_repo.repo_name
2478 2479 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2479 2480 pr_id, pr_repo]
2480 2481 return grouped
2481 2482
2482 2483 # ==========================================================================
2483 2484 # SCM CACHE INSTANCE
2484 2485 # ==========================================================================
2485 2486
2486 2487 def scm_instance(self, **kwargs):
2487 2488 import rhodecode
2488 2489
2489 2490 # Passing a config will not hit the cache currently only used
2490 2491 # for repo2dbmapper
2491 2492 config = kwargs.pop('config', None)
2492 2493 cache = kwargs.pop('cache', None)
2493 2494 vcs_full_cache = kwargs.pop('vcs_full_cache', None)
2494 2495 if vcs_full_cache is not None:
2495 2496 # allows override global config
2496 2497 full_cache = vcs_full_cache
2497 2498 else:
2498 2499 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2499 2500 # if cache is NOT defined use default global, else we have a full
2500 2501 # control over cache behaviour
2501 2502 if cache is None and full_cache and not config:
2502 2503 log.debug('Initializing pure cached instance for %s', self.repo_path)
2503 2504 return self._get_instance_cached()
2504 2505
2505 2506 # cache here is sent to the "vcs server"
2506 2507 return self._get_instance(cache=bool(cache), config=config)
2507 2508
2508 2509 def _get_instance_cached(self):
2509 2510 from rhodecode.lib import rc_cache
2510 2511
2511 2512 cache_namespace_uid = 'cache_repo_instance.{}'.format(self.repo_id)
2512 2513 invalidation_namespace = CacheKey.REPO_INVALIDATION_NAMESPACE.format(
2513 2514 repo_id=self.repo_id)
2514 2515 region = rc_cache.get_or_create_region('cache_repo_longterm', cache_namespace_uid)
2515 2516
2516 2517 @region.conditional_cache_on_arguments(namespace=cache_namespace_uid)
2517 2518 def get_instance_cached(repo_id, context_id, _cache_state_uid):
2518 2519 return self._get_instance(repo_state_uid=_cache_state_uid)
2519 2520
2520 2521 # we must use thread scoped cache here,
2521 2522 # because each thread of gevent needs it's own not shared connection and cache
2522 2523 # we also alter `args` so the cache key is individual for every green thread.
2523 2524 inv_context_manager = rc_cache.InvalidationContext(
2524 2525 uid=cache_namespace_uid, invalidation_namespace=invalidation_namespace,
2525 2526 thread_scoped=True)
2526 2527 with inv_context_manager as invalidation_context:
2527 2528 cache_state_uid = invalidation_context.cache_data['cache_state_uid']
2528 2529 args = (self.repo_id, inv_context_manager.cache_key, cache_state_uid)
2529 2530
2530 2531 # re-compute and store cache if we get invalidate signal
2531 2532 if invalidation_context.should_invalidate():
2532 2533 instance = get_instance_cached.refresh(*args)
2533 2534 else:
2534 2535 instance = get_instance_cached(*args)
2535 2536
2536 2537 log.debug('Repo instance fetched in %.4fs', inv_context_manager.compute_time)
2537 2538 return instance
2538 2539
2539 2540 def _get_instance(self, cache=True, config=None, repo_state_uid=None):
2540 2541 log.debug('Initializing %s instance `%s` with cache flag set to: %s',
2541 2542 self.repo_type, self.repo_path, cache)
2542 2543 config = config or self._config
2543 2544 custom_wire = {
2544 2545 'cache': cache, # controls the vcs.remote cache
2545 2546 'repo_state_uid': repo_state_uid
2546 2547 }
2547 2548 repo = get_vcs_instance(
2548 2549 repo_path=safe_str(self.repo_full_path),
2549 2550 config=config,
2550 2551 with_wire=custom_wire,
2551 2552 create=False,
2552 2553 _vcs_alias=self.repo_type)
2553 2554 if repo is not None:
2554 2555 repo.count() # cache rebuild
2555 2556 return repo
2556 2557
2557 2558 def get_shadow_repository_path(self, workspace_id):
2558 2559 from rhodecode.lib.vcs.backends.base import BaseRepository
2559 2560 shadow_repo_path = BaseRepository._get_shadow_repository_path(
2560 2561 self.repo_full_path, self.repo_id, workspace_id)
2561 2562 return shadow_repo_path
2562 2563
2563 2564 def __json__(self):
2564 2565 return {'landing_rev': self.landing_rev}
2565 2566
2566 2567 def get_dict(self):
2567 2568
2568 2569 # Since we transformed `repo_name` to a hybrid property, we need to
2569 2570 # keep compatibility with the code which uses `repo_name` field.
2570 2571
2571 2572 result = super(Repository, self).get_dict()
2572 2573 result['repo_name'] = result.pop('_repo_name', None)
2573 2574 return result
2574 2575
2575 2576
2576 2577 class RepoGroup(Base, BaseModel):
2577 2578 __tablename__ = 'groups'
2578 2579 __table_args__ = (
2579 2580 UniqueConstraint('group_name', 'group_parent_id'),
2580 2581 base_table_args,
2581 2582 )
2582 2583 __mapper_args__ = {'order_by': 'group_name'}
2583 2584
2584 2585 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2585 2586
2586 2587 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2587 2588 _group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2588 2589 group_name_hash = Column("repo_group_name_hash", String(1024), nullable=False, unique=False)
2589 2590 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2590 2591 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2591 2592 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2592 2593 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2593 2594 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2594 2595 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2595 2596 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2596 2597 _changeset_cache = Column(
2597 2598 "changeset_cache", LargeBinary(), nullable=True) # JSON data
2598 2599
2599 2600 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2600 2601 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2601 2602 parent_group = relationship('RepoGroup', remote_side=group_id)
2602 2603 user = relationship('User')
2603 2604 integrations = relationship('Integration', cascade="all, delete-orphan")
2604 2605
2605 2606 # no cascade, set NULL
2606 2607 scope_artifacts = relationship('FileStore', primaryjoin='FileStore.scope_repo_group_id==RepoGroup.group_id')
2607 2608
2608 2609 def __init__(self, group_name='', parent_group=None):
2609 2610 self.group_name = group_name
2610 2611 self.parent_group = parent_group
2611 2612
2612 2613 def __unicode__(self):
2613 2614 return u"<%s('id:%s:%s')>" % (
2614 2615 self.__class__.__name__, self.group_id, self.group_name)
2615 2616
2616 2617 @hybrid_property
2617 2618 def group_name(self):
2618 2619 return self._group_name
2619 2620
2620 2621 @group_name.setter
2621 2622 def group_name(self, value):
2622 2623 self._group_name = value
2623 2624 self.group_name_hash = self.hash_repo_group_name(value)
2624 2625
2625 2626 @hybrid_property
2626 2627 def changeset_cache(self):
2627 2628 from rhodecode.lib.vcs.backends.base import EmptyCommit
2628 2629 dummy = EmptyCommit().__json__()
2629 2630 if not self._changeset_cache:
2630 2631 dummy['source_repo_id'] = ''
2631 2632 return json.loads(json.dumps(dummy))
2632 2633
2633 2634 try:
2634 2635 return json.loads(self._changeset_cache)
2635 2636 except TypeError:
2636 2637 return dummy
2637 2638 except Exception:
2638 2639 log.error(traceback.format_exc())
2639 2640 return dummy
2640 2641
2641 2642 @changeset_cache.setter
2642 2643 def changeset_cache(self, val):
2643 2644 try:
2644 2645 self._changeset_cache = json.dumps(val)
2645 2646 except Exception:
2646 2647 log.error(traceback.format_exc())
2647 2648
2648 2649 @validates('group_parent_id')
2649 2650 def validate_group_parent_id(self, key, val):
2650 2651 """
2651 2652 Check cycle references for a parent group to self
2652 2653 """
2653 2654 if self.group_id and val:
2654 2655 assert val != self.group_id
2655 2656
2656 2657 return val
2657 2658
2658 2659 @hybrid_property
2659 2660 def description_safe(self):
2660 2661 from rhodecode.lib import helpers as h
2661 2662 return h.escape(self.group_description)
2662 2663
2663 2664 @classmethod
2664 2665 def hash_repo_group_name(cls, repo_group_name):
2665 2666 val = remove_formatting(repo_group_name)
2666 2667 val = safe_str(val).lower()
2667 2668 chars = []
2668 2669 for c in val:
2669 2670 if c not in string.ascii_letters:
2670 2671 c = str(ord(c))
2671 2672 chars.append(c)
2672 2673
2673 2674 return ''.join(chars)
2674 2675
2675 2676 @classmethod
2676 2677 def _generate_choice(cls, repo_group):
2677 2678 from webhelpers.html import literal as _literal
2678 2679 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2679 2680 return repo_group.group_id, _name(repo_group.full_path_splitted)
2680 2681
2681 2682 @classmethod
2682 2683 def groups_choices(cls, groups=None, show_empty_group=True):
2683 2684 if not groups:
2684 2685 groups = cls.query().all()
2685 2686
2686 2687 repo_groups = []
2687 2688 if show_empty_group:
2688 2689 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2689 2690
2690 2691 repo_groups.extend([cls._generate_choice(x) for x in groups])
2691 2692
2692 2693 repo_groups = sorted(
2693 2694 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2694 2695 return repo_groups
2695 2696
2696 2697 @classmethod
2697 2698 def url_sep(cls):
2698 2699 return URL_SEP
2699 2700
2700 2701 @classmethod
2701 2702 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2702 2703 if case_insensitive:
2703 2704 gr = cls.query().filter(func.lower(cls.group_name)
2704 2705 == func.lower(group_name))
2705 2706 else:
2706 2707 gr = cls.query().filter(cls.group_name == group_name)
2707 2708 if cache:
2708 2709 name_key = _hash_key(group_name)
2709 2710 gr = gr.options(
2710 2711 FromCache("sql_cache_short", "get_group_%s" % name_key))
2711 2712 return gr.scalar()
2712 2713
2713 2714 @classmethod
2714 2715 def get_user_personal_repo_group(cls, user_id):
2715 2716 user = User.get(user_id)
2716 2717 if user.username == User.DEFAULT_USER:
2717 2718 return None
2718 2719
2719 2720 return cls.query()\
2720 2721 .filter(cls.personal == true()) \
2721 2722 .filter(cls.user == user) \
2722 2723 .order_by(cls.group_id.asc()) \
2723 2724 .first()
2724 2725
2725 2726 @classmethod
2726 2727 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2727 2728 case_insensitive=True):
2728 2729 q = RepoGroup.query()
2729 2730
2730 2731 if not isinstance(user_id, Optional):
2731 2732 q = q.filter(RepoGroup.user_id == user_id)
2732 2733
2733 2734 if not isinstance(group_id, Optional):
2734 2735 q = q.filter(RepoGroup.group_parent_id == group_id)
2735 2736
2736 2737 if case_insensitive:
2737 2738 q = q.order_by(func.lower(RepoGroup.group_name))
2738 2739 else:
2739 2740 q = q.order_by(RepoGroup.group_name)
2740 2741 return q.all()
2741 2742
2742 2743 @property
2743 2744 def parents(self, parents_recursion_limit = 10):
2744 2745 groups = []
2745 2746 if self.parent_group is None:
2746 2747 return groups
2747 2748 cur_gr = self.parent_group
2748 2749 groups.insert(0, cur_gr)
2749 2750 cnt = 0
2750 2751 while 1:
2751 2752 cnt += 1
2752 2753 gr = getattr(cur_gr, 'parent_group', None)
2753 2754 cur_gr = cur_gr.parent_group
2754 2755 if gr is None:
2755 2756 break
2756 2757 if cnt == parents_recursion_limit:
2757 2758 # this will prevent accidental infinit loops
2758 2759 log.error('more than %s parents found for group %s, stopping '
2759 2760 'recursive parent fetching', parents_recursion_limit, self)
2760 2761 break
2761 2762
2762 2763 groups.insert(0, gr)
2763 2764 return groups
2764 2765
2765 2766 @property
2766 2767 def last_commit_cache_update_diff(self):
2767 2768 return time.time() - (safe_int(self.changeset_cache.get('updated_on')) or 0)
2768 2769
2769 2770 @property
2770 2771 def last_commit_change(self):
2771 2772 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2772 2773 empty_date = datetime.datetime.fromtimestamp(0)
2773 2774 date_latest = self.changeset_cache.get('date', empty_date)
2774 2775 try:
2775 2776 return parse_datetime(date_latest)
2776 2777 except Exception:
2777 2778 return empty_date
2778 2779
2779 2780 @property
2780 2781 def last_db_change(self):
2781 2782 return self.updated_on
2782 2783
2783 2784 @property
2784 2785 def children(self):
2785 2786 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2786 2787
2787 2788 @property
2788 2789 def name(self):
2789 2790 return self.group_name.split(RepoGroup.url_sep())[-1]
2790 2791
2791 2792 @property
2792 2793 def full_path(self):
2793 2794 return self.group_name
2794 2795
2795 2796 @property
2796 2797 def full_path_splitted(self):
2797 2798 return self.group_name.split(RepoGroup.url_sep())
2798 2799
2799 2800 @property
2800 2801 def repositories(self):
2801 2802 return Repository.query()\
2802 2803 .filter(Repository.group == self)\
2803 2804 .order_by(Repository.repo_name)
2804 2805
2805 2806 @property
2806 2807 def repositories_recursive_count(self):
2807 2808 cnt = self.repositories.count()
2808 2809
2809 2810 def children_count(group):
2810 2811 cnt = 0
2811 2812 for child in group.children:
2812 2813 cnt += child.repositories.count()
2813 2814 cnt += children_count(child)
2814 2815 return cnt
2815 2816
2816 2817 return cnt + children_count(self)
2817 2818
2818 2819 def _recursive_objects(self, include_repos=True, include_groups=True):
2819 2820 all_ = []
2820 2821
2821 2822 def _get_members(root_gr):
2822 2823 if include_repos:
2823 2824 for r in root_gr.repositories:
2824 2825 all_.append(r)
2825 2826 childs = root_gr.children.all()
2826 2827 if childs:
2827 2828 for gr in childs:
2828 2829 if include_groups:
2829 2830 all_.append(gr)
2830 2831 _get_members(gr)
2831 2832
2832 2833 root_group = []
2833 2834 if include_groups:
2834 2835 root_group = [self]
2835 2836
2836 2837 _get_members(self)
2837 2838 return root_group + all_
2838 2839
2839 2840 def recursive_groups_and_repos(self):
2840 2841 """
2841 2842 Recursive return all groups, with repositories in those groups
2842 2843 """
2843 2844 return self._recursive_objects()
2844 2845
2845 2846 def recursive_groups(self):
2846 2847 """
2847 2848 Returns all children groups for this group including children of children
2848 2849 """
2849 2850 return self._recursive_objects(include_repos=False)
2850 2851
2851 2852 def recursive_repos(self):
2852 2853 """
2853 2854 Returns all children repositories for this group
2854 2855 """
2855 2856 return self._recursive_objects(include_groups=False)
2856 2857
2857 2858 def get_new_name(self, group_name):
2858 2859 """
2859 2860 returns new full group name based on parent and new name
2860 2861
2861 2862 :param group_name:
2862 2863 """
2863 2864 path_prefix = (self.parent_group.full_path_splitted if
2864 2865 self.parent_group else [])
2865 2866 return RepoGroup.url_sep().join(path_prefix + [group_name])
2866 2867
2867 2868 def update_commit_cache(self, config=None):
2868 2869 """
2869 2870 Update cache of last changeset for newest repository inside this group, keys should be::
2870 2871
2871 2872 source_repo_id
2872 2873 short_id
2873 2874 raw_id
2874 2875 revision
2875 2876 parents
2876 2877 message
2877 2878 date
2878 2879 author
2879 2880
2880 2881 """
2881 2882 from rhodecode.lib.vcs.utils.helpers import parse_datetime
2882 2883
2883 2884 def repo_groups_and_repos():
2884 2885 all_entries = OrderedDefaultDict(list)
2885 2886
2886 2887 def _get_members(root_gr, pos=0):
2887 2888
2888 2889 for repo in root_gr.repositories:
2889 2890 all_entries[root_gr].append(repo)
2890 2891
2891 2892 # fill in all parent positions
2892 2893 for parent_group in root_gr.parents:
2893 2894 all_entries[parent_group].extend(all_entries[root_gr])
2894 2895
2895 2896 children_groups = root_gr.children.all()
2896 2897 if children_groups:
2897 2898 for cnt, gr in enumerate(children_groups, 1):
2898 2899 _get_members(gr, pos=pos+cnt)
2899 2900
2900 2901 _get_members(root_gr=self)
2901 2902 return all_entries
2902 2903
2903 2904 empty_date = datetime.datetime.fromtimestamp(0)
2904 2905 for repo_group, repos in repo_groups_and_repos().items():
2905 2906
2906 2907 latest_repo_cs_cache = {}
2907 2908 _date_latest = empty_date
2908 2909 for repo in repos:
2909 2910 repo_cs_cache = repo.changeset_cache
2910 2911 date_latest = latest_repo_cs_cache.get('date', empty_date)
2911 2912 date_current = repo_cs_cache.get('date', empty_date)
2912 2913 current_timestamp = datetime_to_time(parse_datetime(date_latest))
2913 2914 if current_timestamp < datetime_to_time(parse_datetime(date_current)):
2914 2915 latest_repo_cs_cache = repo_cs_cache
2915 2916 latest_repo_cs_cache['source_repo_id'] = repo.repo_id
2916 2917 _date_latest = parse_datetime(latest_repo_cs_cache['date'])
2917 2918
2918 2919 latest_repo_cs_cache['updated_on'] = time.time()
2919 2920 repo_group.changeset_cache = latest_repo_cs_cache
2920 2921 repo_group.updated_on = _date_latest
2921 2922 Session().add(repo_group)
2922 2923 Session().commit()
2923 2924
2924 2925 log.debug('updated repo group `%s` with new commit cache %s',
2925 2926 repo_group.group_name, latest_repo_cs_cache)
2926 2927
2927 2928 def permissions(self, with_admins=True, with_owner=True,
2928 2929 expand_from_user_groups=False):
2929 2930 """
2930 2931 Permissions for repository groups
2931 2932 """
2932 2933 _admin_perm = 'group.admin'
2933 2934
2934 2935 owner_row = []
2935 2936 if with_owner:
2936 2937 usr = AttributeDict(self.user.get_dict())
2937 2938 usr.owner_row = True
2938 2939 usr.permission = _admin_perm
2939 2940 owner_row.append(usr)
2940 2941
2941 2942 super_admin_ids = []
2942 2943 super_admin_rows = []
2943 2944 if with_admins:
2944 2945 for usr in User.get_all_super_admins():
2945 2946 super_admin_ids.append(usr.user_id)
2946 2947 # if this admin is also owner, don't double the record
2947 2948 if usr.user_id == owner_row[0].user_id:
2948 2949 owner_row[0].admin_row = True
2949 2950 else:
2950 2951 usr = AttributeDict(usr.get_dict())
2951 2952 usr.admin_row = True
2952 2953 usr.permission = _admin_perm
2953 2954 super_admin_rows.append(usr)
2954 2955
2955 2956 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2956 2957 q = q.options(joinedload(UserRepoGroupToPerm.group),
2957 2958 joinedload(UserRepoGroupToPerm.user),
2958 2959 joinedload(UserRepoGroupToPerm.permission),)
2959 2960
2960 2961 # get owners and admins and permissions. We do a trick of re-writing
2961 2962 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2962 2963 # has a global reference and changing one object propagates to all
2963 2964 # others. This means if admin is also an owner admin_row that change
2964 2965 # would propagate to both objects
2965 2966 perm_rows = []
2966 2967 for _usr in q.all():
2967 2968 usr = AttributeDict(_usr.user.get_dict())
2968 2969 # if this user is also owner/admin, mark as duplicate record
2969 2970 if usr.user_id == owner_row[0].user_id or usr.user_id in super_admin_ids:
2970 2971 usr.duplicate_perm = True
2971 2972 usr.permission = _usr.permission.permission_name
2972 2973 perm_rows.append(usr)
2973 2974
2974 2975 # filter the perm rows by 'default' first and then sort them by
2975 2976 # admin,write,read,none permissions sorted again alphabetically in
2976 2977 # each group
2977 2978 perm_rows = sorted(perm_rows, key=display_user_sort)
2978 2979
2979 2980 user_groups_rows = []
2980 2981 if expand_from_user_groups:
2981 2982 for ug in self.permission_user_groups(with_members=True):
2982 2983 for user_data in ug.members:
2983 2984 user_groups_rows.append(user_data)
2984 2985
2985 2986 return super_admin_rows + owner_row + perm_rows + user_groups_rows
2986 2987
2987 2988 def permission_user_groups(self, with_members=False):
2988 2989 q = UserGroupRepoGroupToPerm.query()\
2989 2990 .filter(UserGroupRepoGroupToPerm.group == self)
2990 2991 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2991 2992 joinedload(UserGroupRepoGroupToPerm.users_group),
2992 2993 joinedload(UserGroupRepoGroupToPerm.permission),)
2993 2994
2994 2995 perm_rows = []
2995 2996 for _user_group in q.all():
2996 2997 entry = AttributeDict(_user_group.users_group.get_dict())
2997 2998 entry.permission = _user_group.permission.permission_name
2998 2999 if with_members:
2999 3000 entry.members = [x.user.get_dict()
3000 3001 for x in _user_group.users_group.members]
3001 3002 perm_rows.append(entry)
3002 3003
3003 3004 perm_rows = sorted(perm_rows, key=display_user_group_sort)
3004 3005 return perm_rows
3005 3006
3006 3007 def get_api_data(self):
3007 3008 """
3008 3009 Common function for generating api data
3009 3010
3010 3011 """
3011 3012 group = self
3012 3013 data = {
3013 3014 'group_id': group.group_id,
3014 3015 'group_name': group.group_name,
3015 3016 'group_description': group.description_safe,
3016 3017 'parent_group': group.parent_group.group_name if group.parent_group else None,
3017 3018 'repositories': [x.repo_name for x in group.repositories],
3018 3019 'owner': group.user.username,
3019 3020 }
3020 3021 return data
3021 3022
3022 3023 def get_dict(self):
3023 3024 # Since we transformed `group_name` to a hybrid property, we need to
3024 3025 # keep compatibility with the code which uses `group_name` field.
3025 3026 result = super(RepoGroup, self).get_dict()
3026 3027 result['group_name'] = result.pop('_group_name', None)
3027 3028 return result
3028 3029
3029 3030
3030 3031 class Permission(Base, BaseModel):
3031 3032 __tablename__ = 'permissions'
3032 3033 __table_args__ = (
3033 3034 Index('p_perm_name_idx', 'permission_name'),
3034 3035 base_table_args,
3035 3036 )
3036 3037
3037 3038 PERMS = [
3038 3039 ('hg.admin', _('RhodeCode Super Administrator')),
3039 3040
3040 3041 ('repository.none', _('Repository no access')),
3041 3042 ('repository.read', _('Repository read access')),
3042 3043 ('repository.write', _('Repository write access')),
3043 3044 ('repository.admin', _('Repository admin access')),
3044 3045
3045 3046 ('group.none', _('Repository group no access')),
3046 3047 ('group.read', _('Repository group read access')),
3047 3048 ('group.write', _('Repository group write access')),
3048 3049 ('group.admin', _('Repository group admin access')),
3049 3050
3050 3051 ('usergroup.none', _('User group no access')),
3051 3052 ('usergroup.read', _('User group read access')),
3052 3053 ('usergroup.write', _('User group write access')),
3053 3054 ('usergroup.admin', _('User group admin access')),
3054 3055
3055 3056 ('branch.none', _('Branch no permissions')),
3056 3057 ('branch.merge', _('Branch access by web merge')),
3057 3058 ('branch.push', _('Branch access by push')),
3058 3059 ('branch.push_force', _('Branch access by push with force')),
3059 3060
3060 3061 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
3061 3062 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
3062 3063
3063 3064 ('hg.usergroup.create.false', _('User Group creation disabled')),
3064 3065 ('hg.usergroup.create.true', _('User Group creation enabled')),
3065 3066
3066 3067 ('hg.create.none', _('Repository creation disabled')),
3067 3068 ('hg.create.repository', _('Repository creation enabled')),
3068 3069 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
3069 3070 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
3070 3071
3071 3072 ('hg.fork.none', _('Repository forking disabled')),
3072 3073 ('hg.fork.repository', _('Repository forking enabled')),
3073 3074
3074 3075 ('hg.register.none', _('Registration disabled')),
3075 3076 ('hg.register.manual_activate', _('User Registration with manual account activation')),
3076 3077 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
3077 3078
3078 3079 ('hg.password_reset.enabled', _('Password reset enabled')),
3079 3080 ('hg.password_reset.hidden', _('Password reset hidden')),
3080 3081 ('hg.password_reset.disabled', _('Password reset disabled')),
3081 3082
3082 3083 ('hg.extern_activate.manual', _('Manual activation of external account')),
3083 3084 ('hg.extern_activate.auto', _('Automatic activation of external account')),
3084 3085
3085 3086 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
3086 3087 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
3087 3088 ]
3088 3089
3089 3090 # definition of system default permissions for DEFAULT user, created on
3090 3091 # system setup
3091 3092 DEFAULT_USER_PERMISSIONS = [
3092 3093 # object perms
3093 3094 'repository.read',
3094 3095 'group.read',
3095 3096 'usergroup.read',
3096 3097 # branch, for backward compat we need same value as before so forced pushed
3097 3098 'branch.push_force',
3098 3099 # global
3099 3100 'hg.create.repository',
3100 3101 'hg.repogroup.create.false',
3101 3102 'hg.usergroup.create.false',
3102 3103 'hg.create.write_on_repogroup.true',
3103 3104 'hg.fork.repository',
3104 3105 'hg.register.manual_activate',
3105 3106 'hg.password_reset.enabled',
3106 3107 'hg.extern_activate.auto',
3107 3108 'hg.inherit_default_perms.true',
3108 3109 ]
3109 3110
3110 3111 # defines which permissions are more important higher the more important
3111 3112 # Weight defines which permissions are more important.
3112 3113 # The higher number the more important.
3113 3114 PERM_WEIGHTS = {
3114 3115 'repository.none': 0,
3115 3116 'repository.read': 1,
3116 3117 'repository.write': 3,
3117 3118 'repository.admin': 4,
3118 3119
3119 3120 'group.none': 0,
3120 3121 'group.read': 1,
3121 3122 'group.write': 3,
3122 3123 'group.admin': 4,
3123 3124
3124 3125 'usergroup.none': 0,
3125 3126 'usergroup.read': 1,
3126 3127 'usergroup.write': 3,
3127 3128 'usergroup.admin': 4,
3128 3129
3129 3130 'branch.none': 0,
3130 3131 'branch.merge': 1,
3131 3132 'branch.push': 3,
3132 3133 'branch.push_force': 4,
3133 3134
3134 3135 'hg.repogroup.create.false': 0,
3135 3136 'hg.repogroup.create.true': 1,
3136 3137
3137 3138 'hg.usergroup.create.false': 0,
3138 3139 'hg.usergroup.create.true': 1,
3139 3140
3140 3141 'hg.fork.none': 0,
3141 3142 'hg.fork.repository': 1,
3142 3143 'hg.create.none': 0,
3143 3144 'hg.create.repository': 1
3144 3145 }
3145 3146
3146 3147 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3147 3148 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
3148 3149 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
3149 3150
3150 3151 def __unicode__(self):
3151 3152 return u"<%s('%s:%s')>" % (
3152 3153 self.__class__.__name__, self.permission_id, self.permission_name
3153 3154 )
3154 3155
3155 3156 @classmethod
3156 3157 def get_by_key(cls, key):
3157 3158 return cls.query().filter(cls.permission_name == key).scalar()
3158 3159
3159 3160 @classmethod
3160 3161 def get_default_repo_perms(cls, user_id, repo_id=None):
3161 3162 q = Session().query(UserRepoToPerm, Repository, Permission)\
3162 3163 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
3163 3164 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
3164 3165 .filter(UserRepoToPerm.user_id == user_id)
3165 3166 if repo_id:
3166 3167 q = q.filter(UserRepoToPerm.repository_id == repo_id)
3167 3168 return q.all()
3168 3169
3169 3170 @classmethod
3170 3171 def get_default_repo_branch_perms(cls, user_id, repo_id=None):
3171 3172 q = Session().query(UserToRepoBranchPermission, UserRepoToPerm, Permission) \
3172 3173 .join(
3173 3174 Permission,
3174 3175 UserToRepoBranchPermission.permission_id == Permission.permission_id) \
3175 3176 .join(
3176 3177 UserRepoToPerm,
3177 3178 UserToRepoBranchPermission.rule_to_perm_id == UserRepoToPerm.repo_to_perm_id) \
3178 3179 .filter(UserRepoToPerm.user_id == user_id)
3179 3180
3180 3181 if repo_id:
3181 3182 q = q.filter(UserToRepoBranchPermission.repository_id == repo_id)
3182 3183 return q.order_by(UserToRepoBranchPermission.rule_order).all()
3183 3184
3184 3185 @classmethod
3185 3186 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
3186 3187 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
3187 3188 .join(
3188 3189 Permission,
3189 3190 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
3190 3191 .join(
3191 3192 Repository,
3192 3193 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
3193 3194 .join(
3194 3195 UserGroup,
3195 3196 UserGroupRepoToPerm.users_group_id ==
3196 3197 UserGroup.users_group_id)\
3197 3198 .join(
3198 3199 UserGroupMember,
3199 3200 UserGroupRepoToPerm.users_group_id ==
3200 3201 UserGroupMember.users_group_id)\
3201 3202 .filter(
3202 3203 UserGroupMember.user_id == user_id,
3203 3204 UserGroup.users_group_active == true())
3204 3205 if repo_id:
3205 3206 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
3206 3207 return q.all()
3207 3208
3208 3209 @classmethod
3209 3210 def get_default_repo_branch_perms_from_user_group(cls, user_id, repo_id=None):
3210 3211 q = Session().query(UserGroupToRepoBranchPermission, UserGroupRepoToPerm, Permission) \
3211 3212 .join(
3212 3213 Permission,
3213 3214 UserGroupToRepoBranchPermission.permission_id == Permission.permission_id) \
3214 3215 .join(
3215 3216 UserGroupRepoToPerm,
3216 3217 UserGroupToRepoBranchPermission.rule_to_perm_id == UserGroupRepoToPerm.users_group_to_perm_id) \
3217 3218 .join(
3218 3219 UserGroup,
3219 3220 UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id) \
3220 3221 .join(
3221 3222 UserGroupMember,
3222 3223 UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id) \
3223 3224 .filter(
3224 3225 UserGroupMember.user_id == user_id,
3225 3226 UserGroup.users_group_active == true())
3226 3227
3227 3228 if repo_id:
3228 3229 q = q.filter(UserGroupToRepoBranchPermission.repository_id == repo_id)
3229 3230 return q.order_by(UserGroupToRepoBranchPermission.rule_order).all()
3230 3231
3231 3232 @classmethod
3232 3233 def get_default_group_perms(cls, user_id, repo_group_id=None):
3233 3234 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
3234 3235 .join(
3235 3236 Permission,
3236 3237 UserRepoGroupToPerm.permission_id == Permission.permission_id)\
3237 3238 .join(
3238 3239 RepoGroup,
3239 3240 UserRepoGroupToPerm.group_id == RepoGroup.group_id)\
3240 3241 .filter(UserRepoGroupToPerm.user_id == user_id)
3241 3242 if repo_group_id:
3242 3243 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
3243 3244 return q.all()
3244 3245
3245 3246 @classmethod
3246 3247 def get_default_group_perms_from_user_group(
3247 3248 cls, user_id, repo_group_id=None):
3248 3249 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
3249 3250 .join(
3250 3251 Permission,
3251 3252 UserGroupRepoGroupToPerm.permission_id ==
3252 3253 Permission.permission_id)\
3253 3254 .join(
3254 3255 RepoGroup,
3255 3256 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
3256 3257 .join(
3257 3258 UserGroup,
3258 3259 UserGroupRepoGroupToPerm.users_group_id ==
3259 3260 UserGroup.users_group_id)\
3260 3261 .join(
3261 3262 UserGroupMember,
3262 3263 UserGroupRepoGroupToPerm.users_group_id ==
3263 3264 UserGroupMember.users_group_id)\
3264 3265 .filter(
3265 3266 UserGroupMember.user_id == user_id,
3266 3267 UserGroup.users_group_active == true())
3267 3268 if repo_group_id:
3268 3269 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
3269 3270 return q.all()
3270 3271
3271 3272 @classmethod
3272 3273 def get_default_user_group_perms(cls, user_id, user_group_id=None):
3273 3274 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
3274 3275 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
3275 3276 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
3276 3277 .filter(UserUserGroupToPerm.user_id == user_id)
3277 3278 if user_group_id:
3278 3279 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
3279 3280 return q.all()
3280 3281
3281 3282 @classmethod
3282 3283 def get_default_user_group_perms_from_user_group(
3283 3284 cls, user_id, user_group_id=None):
3284 3285 TargetUserGroup = aliased(UserGroup, name='target_user_group')
3285 3286 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
3286 3287 .join(
3287 3288 Permission,
3288 3289 UserGroupUserGroupToPerm.permission_id ==
3289 3290 Permission.permission_id)\
3290 3291 .join(
3291 3292 TargetUserGroup,
3292 3293 UserGroupUserGroupToPerm.target_user_group_id ==
3293 3294 TargetUserGroup.users_group_id)\
3294 3295 .join(
3295 3296 UserGroup,
3296 3297 UserGroupUserGroupToPerm.user_group_id ==
3297 3298 UserGroup.users_group_id)\
3298 3299 .join(
3299 3300 UserGroupMember,
3300 3301 UserGroupUserGroupToPerm.user_group_id ==
3301 3302 UserGroupMember.users_group_id)\
3302 3303 .filter(
3303 3304 UserGroupMember.user_id == user_id,
3304 3305 UserGroup.users_group_active == true())
3305 3306 if user_group_id:
3306 3307 q = q.filter(
3307 3308 UserGroupUserGroupToPerm.user_group_id == user_group_id)
3308 3309
3309 3310 return q.all()
3310 3311
3311 3312
3312 3313 class UserRepoToPerm(Base, BaseModel):
3313 3314 __tablename__ = 'repo_to_perm'
3314 3315 __table_args__ = (
3315 3316 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
3316 3317 base_table_args
3317 3318 )
3318 3319
3319 3320 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3320 3321 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3321 3322 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3322 3323 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3323 3324
3324 3325 user = relationship('User')
3325 3326 repository = relationship('Repository')
3326 3327 permission = relationship('Permission')
3327 3328
3328 3329 branch_perm_entry = relationship('UserToRepoBranchPermission', cascade="all, delete-orphan", lazy='joined')
3329 3330
3330 3331 @classmethod
3331 3332 def create(cls, user, repository, permission):
3332 3333 n = cls()
3333 3334 n.user = user
3334 3335 n.repository = repository
3335 3336 n.permission = permission
3336 3337 Session().add(n)
3337 3338 return n
3338 3339
3339 3340 def __unicode__(self):
3340 3341 return u'<%s => %s >' % (self.user, self.repository)
3341 3342
3342 3343
3343 3344 class UserUserGroupToPerm(Base, BaseModel):
3344 3345 __tablename__ = 'user_user_group_to_perm'
3345 3346 __table_args__ = (
3346 3347 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
3347 3348 base_table_args
3348 3349 )
3349 3350
3350 3351 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3351 3352 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3352 3353 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3353 3354 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3354 3355
3355 3356 user = relationship('User')
3356 3357 user_group = relationship('UserGroup')
3357 3358 permission = relationship('Permission')
3358 3359
3359 3360 @classmethod
3360 3361 def create(cls, user, user_group, permission):
3361 3362 n = cls()
3362 3363 n.user = user
3363 3364 n.user_group = user_group
3364 3365 n.permission = permission
3365 3366 Session().add(n)
3366 3367 return n
3367 3368
3368 3369 def __unicode__(self):
3369 3370 return u'<%s => %s >' % (self.user, self.user_group)
3370 3371
3371 3372
3372 3373 class UserToPerm(Base, BaseModel):
3373 3374 __tablename__ = 'user_to_perm'
3374 3375 __table_args__ = (
3375 3376 UniqueConstraint('user_id', 'permission_id'),
3376 3377 base_table_args
3377 3378 )
3378 3379
3379 3380 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3380 3381 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3381 3382 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3382 3383
3383 3384 user = relationship('User')
3384 3385 permission = relationship('Permission', lazy='joined')
3385 3386
3386 3387 def __unicode__(self):
3387 3388 return u'<%s => %s >' % (self.user, self.permission)
3388 3389
3389 3390
3390 3391 class UserGroupRepoToPerm(Base, BaseModel):
3391 3392 __tablename__ = 'users_group_repo_to_perm'
3392 3393 __table_args__ = (
3393 3394 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
3394 3395 base_table_args
3395 3396 )
3396 3397
3397 3398 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3398 3399 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3399 3400 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3400 3401 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
3401 3402
3402 3403 users_group = relationship('UserGroup')
3403 3404 permission = relationship('Permission')
3404 3405 repository = relationship('Repository')
3405 3406 user_group_branch_perms = relationship('UserGroupToRepoBranchPermission', cascade='all')
3406 3407
3407 3408 @classmethod
3408 3409 def create(cls, users_group, repository, permission):
3409 3410 n = cls()
3410 3411 n.users_group = users_group
3411 3412 n.repository = repository
3412 3413 n.permission = permission
3413 3414 Session().add(n)
3414 3415 return n
3415 3416
3416 3417 def __unicode__(self):
3417 3418 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
3418 3419
3419 3420
3420 3421 class UserGroupUserGroupToPerm(Base, BaseModel):
3421 3422 __tablename__ = 'user_group_user_group_to_perm'
3422 3423 __table_args__ = (
3423 3424 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
3424 3425 CheckConstraint('target_user_group_id != user_group_id'),
3425 3426 base_table_args
3426 3427 )
3427 3428
3428 3429 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)
3429 3430 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3430 3431 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3431 3432 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3432 3433
3433 3434 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
3434 3435 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
3435 3436 permission = relationship('Permission')
3436 3437
3437 3438 @classmethod
3438 3439 def create(cls, target_user_group, user_group, permission):
3439 3440 n = cls()
3440 3441 n.target_user_group = target_user_group
3441 3442 n.user_group = user_group
3442 3443 n.permission = permission
3443 3444 Session().add(n)
3444 3445 return n
3445 3446
3446 3447 def __unicode__(self):
3447 3448 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
3448 3449
3449 3450
3450 3451 class UserGroupToPerm(Base, BaseModel):
3451 3452 __tablename__ = 'users_group_to_perm'
3452 3453 __table_args__ = (
3453 3454 UniqueConstraint('users_group_id', 'permission_id',),
3454 3455 base_table_args
3455 3456 )
3456 3457
3457 3458 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3458 3459 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3459 3460 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3460 3461
3461 3462 users_group = relationship('UserGroup')
3462 3463 permission = relationship('Permission')
3463 3464
3464 3465
3465 3466 class UserRepoGroupToPerm(Base, BaseModel):
3466 3467 __tablename__ = 'user_repo_group_to_perm'
3467 3468 __table_args__ = (
3468 3469 UniqueConstraint('user_id', 'group_id', 'permission_id'),
3469 3470 base_table_args
3470 3471 )
3471 3472
3472 3473 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3473 3474 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3474 3475 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3475 3476 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3476 3477
3477 3478 user = relationship('User')
3478 3479 group = relationship('RepoGroup')
3479 3480 permission = relationship('Permission')
3480 3481
3481 3482 @classmethod
3482 3483 def create(cls, user, repository_group, permission):
3483 3484 n = cls()
3484 3485 n.user = user
3485 3486 n.group = repository_group
3486 3487 n.permission = permission
3487 3488 Session().add(n)
3488 3489 return n
3489 3490
3490 3491
3491 3492 class UserGroupRepoGroupToPerm(Base, BaseModel):
3492 3493 __tablename__ = 'users_group_repo_group_to_perm'
3493 3494 __table_args__ = (
3494 3495 UniqueConstraint('users_group_id', 'group_id'),
3495 3496 base_table_args
3496 3497 )
3497 3498
3498 3499 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)
3499 3500 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3500 3501 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3501 3502 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3502 3503
3503 3504 users_group = relationship('UserGroup')
3504 3505 permission = relationship('Permission')
3505 3506 group = relationship('RepoGroup')
3506 3507
3507 3508 @classmethod
3508 3509 def create(cls, user_group, repository_group, permission):
3509 3510 n = cls()
3510 3511 n.users_group = user_group
3511 3512 n.group = repository_group
3512 3513 n.permission = permission
3513 3514 Session().add(n)
3514 3515 return n
3515 3516
3516 3517 def __unicode__(self):
3517 3518 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3518 3519
3519 3520
3520 3521 class Statistics(Base, BaseModel):
3521 3522 __tablename__ = 'statistics'
3522 3523 __table_args__ = (
3523 3524 base_table_args
3524 3525 )
3525 3526
3526 3527 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3527 3528 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3528 3529 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3529 3530 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3530 3531 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3531 3532 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3532 3533
3533 3534 repository = relationship('Repository', single_parent=True)
3534 3535
3535 3536
3536 3537 class UserFollowing(Base, BaseModel):
3537 3538 __tablename__ = 'user_followings'
3538 3539 __table_args__ = (
3539 3540 UniqueConstraint('user_id', 'follows_repository_id'),
3540 3541 UniqueConstraint('user_id', 'follows_user_id'),
3541 3542 base_table_args
3542 3543 )
3543 3544
3544 3545 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3545 3546 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3546 3547 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3547 3548 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3548 3549 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3549 3550
3550 3551 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3551 3552
3552 3553 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3553 3554 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3554 3555
3555 3556 @classmethod
3556 3557 def get_repo_followers(cls, repo_id):
3557 3558 return cls.query().filter(cls.follows_repo_id == repo_id)
3558 3559
3559 3560
3560 3561 class CacheKey(Base, BaseModel):
3561 3562 __tablename__ = 'cache_invalidation'
3562 3563 __table_args__ = (
3563 3564 UniqueConstraint('cache_key'),
3564 3565 Index('key_idx', 'cache_key'),
3565 3566 base_table_args,
3566 3567 )
3567 3568
3568 3569 CACHE_TYPE_FEED = 'FEED'
3569 3570
3570 3571 # namespaces used to register process/thread aware caches
3571 3572 REPO_INVALIDATION_NAMESPACE = 'repo_cache:{repo_id}'
3572 3573 SETTINGS_INVALIDATION_NAMESPACE = 'system_settings'
3573 3574
3574 3575 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3575 3576 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3576 3577 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3577 3578 cache_state_uid = Column("cache_state_uid", String(255), nullable=True, unique=None, default=None)
3578 3579 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3579 3580
3580 3581 def __init__(self, cache_key, cache_args='', cache_state_uid=None):
3581 3582 self.cache_key = cache_key
3582 3583 self.cache_args = cache_args
3583 3584 self.cache_active = False
3584 3585 # first key should be same for all entries, since all workers should share it
3585 3586 self.cache_state_uid = cache_state_uid or self.generate_new_state_uid()
3586 3587
3587 3588 def __unicode__(self):
3588 3589 return u"<%s('%s:%s[%s]')>" % (
3589 3590 self.__class__.__name__,
3590 3591 self.cache_id, self.cache_key, self.cache_active)
3591 3592
3592 3593 def _cache_key_partition(self):
3593 3594 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3594 3595 return prefix, repo_name, suffix
3595 3596
3596 3597 def get_prefix(self):
3597 3598 """
3598 3599 Try to extract prefix from existing cache key. The key could consist
3599 3600 of prefix, repo_name, suffix
3600 3601 """
3601 3602 # this returns prefix, repo_name, suffix
3602 3603 return self._cache_key_partition()[0]
3603 3604
3604 3605 def get_suffix(self):
3605 3606 """
3606 3607 get suffix that might have been used in _get_cache_key to
3607 3608 generate self.cache_key. Only used for informational purposes
3608 3609 in repo_edit.mako.
3609 3610 """
3610 3611 # prefix, repo_name, suffix
3611 3612 return self._cache_key_partition()[2]
3612 3613
3613 3614 @classmethod
3614 3615 def generate_new_state_uid(cls, based_on=None):
3615 3616 if based_on:
3616 3617 return str(uuid.uuid5(uuid.NAMESPACE_URL, safe_str(based_on)))
3617 3618 else:
3618 3619 return str(uuid.uuid4())
3619 3620
3620 3621 @classmethod
3621 3622 def delete_all_cache(cls):
3622 3623 """
3623 3624 Delete all cache keys from database.
3624 3625 Should only be run when all instances are down and all entries
3625 3626 thus stale.
3626 3627 """
3627 3628 cls.query().delete()
3628 3629 Session().commit()
3629 3630
3630 3631 @classmethod
3631 3632 def set_invalidate(cls, cache_uid, delete=False):
3632 3633 """
3633 3634 Mark all caches of a repo as invalid in the database.
3634 3635 """
3635 3636
3636 3637 try:
3637 3638 qry = Session().query(cls).filter(cls.cache_args == cache_uid)
3638 3639 if delete:
3639 3640 qry.delete()
3640 3641 log.debug('cache objects deleted for cache args %s',
3641 3642 safe_str(cache_uid))
3642 3643 else:
3643 3644 qry.update({"cache_active": False,
3644 3645 "cache_state_uid": cls.generate_new_state_uid()})
3645 3646 log.debug('cache objects marked as invalid for cache args %s',
3646 3647 safe_str(cache_uid))
3647 3648
3648 3649 Session().commit()
3649 3650 except Exception:
3650 3651 log.exception(
3651 3652 'Cache key invalidation failed for cache args %s',
3652 3653 safe_str(cache_uid))
3653 3654 Session().rollback()
3654 3655
3655 3656 @classmethod
3656 3657 def get_active_cache(cls, cache_key):
3657 3658 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3658 3659 if inv_obj:
3659 3660 return inv_obj
3660 3661 return None
3661 3662
3662 3663 @classmethod
3663 3664 def get_namespace_map(cls, namespace):
3664 3665 return {
3665 3666 x.cache_key: x
3666 3667 for x in cls.query().filter(cls.cache_args == namespace)}
3667 3668
3668 3669
3669 3670 class ChangesetComment(Base, BaseModel):
3670 3671 __tablename__ = 'changeset_comments'
3671 3672 __table_args__ = (
3672 3673 Index('cc_revision_idx', 'revision'),
3673 3674 base_table_args,
3674 3675 )
3675 3676
3676 3677 COMMENT_OUTDATED = u'comment_outdated'
3677 3678 COMMENT_TYPE_NOTE = u'note'
3678 3679 COMMENT_TYPE_TODO = u'todo'
3679 3680 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3680 3681
3681 3682 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3682 3683 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3683 3684 revision = Column('revision', String(40), nullable=True)
3684 3685 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3685 3686 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3686 3687 line_no = Column('line_no', Unicode(10), nullable=True)
3687 3688 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3688 3689 f_path = Column('f_path', Unicode(1000), nullable=True)
3689 3690 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3690 3691 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3691 3692 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3692 3693 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3693 3694 renderer = Column('renderer', Unicode(64), nullable=True)
3694 3695 display_state = Column('display_state', Unicode(128), nullable=True)
3695 3696
3696 3697 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3697 3698 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3698 3699
3699 3700 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, back_populates='resolved_by')
3700 3701 resolved_by = relationship('ChangesetComment', back_populates='resolved_comment')
3701 3702
3702 3703 author = relationship('User', lazy='joined')
3703 3704 repo = relationship('Repository')
3704 3705 status_change = relationship('ChangesetStatus', cascade="all, delete-orphan", lazy='joined')
3705 3706 pull_request = relationship('PullRequest', lazy='joined')
3706 3707 pull_request_version = relationship('PullRequestVersion')
3707 3708
3708 3709 @classmethod
3709 3710 def get_users(cls, revision=None, pull_request_id=None):
3710 3711 """
3711 3712 Returns user associated with this ChangesetComment. ie those
3712 3713 who actually commented
3713 3714
3714 3715 :param cls:
3715 3716 :param revision:
3716 3717 """
3717 3718 q = Session().query(User)\
3718 3719 .join(ChangesetComment.author)
3719 3720 if revision:
3720 3721 q = q.filter(cls.revision == revision)
3721 3722 elif pull_request_id:
3722 3723 q = q.filter(cls.pull_request_id == pull_request_id)
3723 3724 return q.all()
3724 3725
3725 3726 @classmethod
3726 3727 def get_index_from_version(cls, pr_version, versions):
3727 3728 num_versions = [x.pull_request_version_id for x in versions]
3728 3729 try:
3729 3730 return num_versions.index(pr_version) +1
3730 3731 except (IndexError, ValueError):
3731 3732 return
3732 3733
3733 3734 @property
3734 3735 def outdated(self):
3735 3736 return self.display_state == self.COMMENT_OUTDATED
3736 3737
3737 3738 def outdated_at_version(self, version):
3738 3739 """
3739 3740 Checks if comment is outdated for given pull request version
3740 3741 """
3741 3742 return self.outdated and self.pull_request_version_id != version
3742 3743
3743 3744 def older_than_version(self, version):
3744 3745 """
3745 3746 Checks if comment is made from previous version than given
3746 3747 """
3747 3748 if version is None:
3748 3749 return self.pull_request_version_id is not None
3749 3750
3750 3751 return self.pull_request_version_id < version
3751 3752
3752 3753 @property
3753 3754 def resolved(self):
3754 3755 return self.resolved_by[0] if self.resolved_by else None
3755 3756
3756 3757 @property
3757 3758 def is_todo(self):
3758 3759 return self.comment_type == self.COMMENT_TYPE_TODO
3759 3760
3760 3761 @property
3761 3762 def is_inline(self):
3762 3763 return self.line_no and self.f_path
3763 3764
3764 3765 def get_index_version(self, versions):
3765 3766 return self.get_index_from_version(
3766 3767 self.pull_request_version_id, versions)
3767 3768
3768 3769 def __repr__(self):
3769 3770 if self.comment_id:
3770 3771 return '<DB:Comment #%s>' % self.comment_id
3771 3772 else:
3772 3773 return '<DB:Comment at %#x>' % id(self)
3773 3774
3774 3775 def get_api_data(self):
3775 3776 comment = self
3776 3777 data = {
3777 3778 'comment_id': comment.comment_id,
3778 3779 'comment_type': comment.comment_type,
3779 3780 'comment_text': comment.text,
3780 3781 'comment_status': comment.status_change,
3781 3782 'comment_f_path': comment.f_path,
3782 3783 'comment_lineno': comment.line_no,
3783 3784 'comment_author': comment.author,
3784 3785 'comment_created_on': comment.created_on,
3785 3786 'comment_resolved_by': self.resolved
3786 3787 }
3787 3788 return data
3788 3789
3789 3790 def __json__(self):
3790 3791 data = dict()
3791 3792 data.update(self.get_api_data())
3792 3793 return data
3793 3794
3794 3795
3795 3796 class ChangesetStatus(Base, BaseModel):
3796 3797 __tablename__ = 'changeset_statuses'
3797 3798 __table_args__ = (
3798 3799 Index('cs_revision_idx', 'revision'),
3799 3800 Index('cs_version_idx', 'version'),
3800 3801 UniqueConstraint('repo_id', 'revision', 'version'),
3801 3802 base_table_args
3802 3803 )
3803 3804
3804 3805 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3805 3806 STATUS_APPROVED = 'approved'
3806 3807 STATUS_REJECTED = 'rejected'
3807 3808 STATUS_UNDER_REVIEW = 'under_review'
3808 3809
3809 3810 STATUSES = [
3810 3811 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3811 3812 (STATUS_APPROVED, _("Approved")),
3812 3813 (STATUS_REJECTED, _("Rejected")),
3813 3814 (STATUS_UNDER_REVIEW, _("Under Review")),
3814 3815 ]
3815 3816
3816 3817 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3817 3818 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3818 3819 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3819 3820 revision = Column('revision', String(40), nullable=False)
3820 3821 status = Column('status', String(128), nullable=False, default=DEFAULT)
3821 3822 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3822 3823 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3823 3824 version = Column('version', Integer(), nullable=False, default=0)
3824 3825 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3825 3826
3826 3827 author = relationship('User', lazy='joined')
3827 3828 repo = relationship('Repository')
3828 3829 comment = relationship('ChangesetComment', lazy='joined')
3829 3830 pull_request = relationship('PullRequest', lazy='joined')
3830 3831
3831 3832 def __unicode__(self):
3832 3833 return u"<%s('%s[v%s]:%s')>" % (
3833 3834 self.__class__.__name__,
3834 3835 self.status, self.version, self.author
3835 3836 )
3836 3837
3837 3838 @classmethod
3838 3839 def get_status_lbl(cls, value):
3839 3840 return dict(cls.STATUSES).get(value)
3840 3841
3841 3842 @property
3842 3843 def status_lbl(self):
3843 3844 return ChangesetStatus.get_status_lbl(self.status)
3844 3845
3845 3846 def get_api_data(self):
3846 3847 status = self
3847 3848 data = {
3848 3849 'status_id': status.changeset_status_id,
3849 3850 'status': status.status,
3850 3851 }
3851 3852 return data
3852 3853
3853 3854 def __json__(self):
3854 3855 data = dict()
3855 3856 data.update(self.get_api_data())
3856 3857 return data
3857 3858
3858 3859
3859 3860 class _SetState(object):
3860 3861 """
3861 3862 Context processor allowing changing state for sensitive operation such as
3862 3863 pull request update or merge
3863 3864 """
3864 3865
3865 3866 def __init__(self, pull_request, pr_state, back_state=None):
3866 3867 self._pr = pull_request
3867 3868 self._org_state = back_state or pull_request.pull_request_state
3868 3869 self._pr_state = pr_state
3869 3870 self._current_state = None
3870 3871
3871 3872 def __enter__(self):
3872 3873 log.debug('StateLock: entering set state context, setting state to: `%s`',
3873 3874 self._pr_state)
3874 3875 self.set_pr_state(self._pr_state)
3875 3876 return self
3876 3877
3877 3878 def __exit__(self, exc_type, exc_val, exc_tb):
3878 3879 if exc_val is not None:
3879 3880 log.error(traceback.format_exc(exc_tb))
3880 3881 return None
3881 3882
3882 3883 self.set_pr_state(self._org_state)
3883 3884 log.debug('StateLock: exiting set state context, setting state to: `%s`',
3884 3885 self._org_state)
3885 3886 @property
3886 3887 def state(self):
3887 3888 return self._current_state
3888 3889
3889 3890 def set_pr_state(self, pr_state):
3890 3891 try:
3891 3892 self._pr.pull_request_state = pr_state
3892 3893 Session().add(self._pr)
3893 3894 Session().commit()
3894 3895 self._current_state = pr_state
3895 3896 except Exception:
3896 3897 log.exception('Failed to set PullRequest %s state to %s', self._pr, pr_state)
3897 3898 raise
3898 3899
3899 3900
3900 3901 class _PullRequestBase(BaseModel):
3901 3902 """
3902 3903 Common attributes of pull request and version entries.
3903 3904 """
3904 3905
3905 3906 # .status values
3906 3907 STATUS_NEW = u'new'
3907 3908 STATUS_OPEN = u'open'
3908 3909 STATUS_CLOSED = u'closed'
3909 3910
3910 3911 # available states
3911 3912 STATE_CREATING = u'creating'
3912 3913 STATE_UPDATING = u'updating'
3913 3914 STATE_MERGING = u'merging'
3914 3915 STATE_CREATED = u'created'
3915 3916
3916 3917 title = Column('title', Unicode(255), nullable=True)
3917 3918 description = Column(
3918 3919 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3919 3920 nullable=True)
3920 3921 description_renderer = Column('description_renderer', Unicode(64), nullable=True)
3921 3922
3922 3923 # new/open/closed status of pull request (not approve/reject/etc)
3923 3924 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3924 3925 created_on = Column(
3925 3926 'created_on', DateTime(timezone=False), nullable=False,
3926 3927 default=datetime.datetime.now)
3927 3928 updated_on = Column(
3928 3929 'updated_on', DateTime(timezone=False), nullable=False,
3929 3930 default=datetime.datetime.now)
3930 3931
3931 3932 pull_request_state = Column("pull_request_state", String(255), nullable=True)
3932 3933
3933 3934 @declared_attr
3934 3935 def user_id(cls):
3935 3936 return Column(
3936 3937 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3937 3938 unique=None)
3938 3939
3939 3940 # 500 revisions max
3940 3941 _revisions = Column(
3941 3942 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3942 3943
3943 3944 @declared_attr
3944 3945 def source_repo_id(cls):
3945 3946 # TODO: dan: rename column to source_repo_id
3946 3947 return Column(
3947 3948 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3948 3949 nullable=False)
3949 3950
3950 3951 _source_ref = Column('org_ref', Unicode(255), nullable=False)
3951 3952
3952 3953 @hybrid_property
3953 3954 def source_ref(self):
3954 3955 return self._source_ref
3955 3956
3956 3957 @source_ref.setter
3957 3958 def source_ref(self, val):
3958 3959 parts = (val or '').split(':')
3959 3960 if len(parts) != 3:
3960 3961 raise ValueError(
3961 3962 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3962 3963 self._source_ref = safe_unicode(val)
3963 3964
3964 3965 _target_ref = Column('other_ref', Unicode(255), nullable=False)
3965 3966
3966 3967 @hybrid_property
3967 3968 def target_ref(self):
3968 3969 return self._target_ref
3969 3970
3970 3971 @target_ref.setter
3971 3972 def target_ref(self, val):
3972 3973 parts = (val or '').split(':')
3973 3974 if len(parts) != 3:
3974 3975 raise ValueError(
3975 3976 'Invalid reference format given: {}, expected X:Y:Z'.format(val))
3976 3977 self._target_ref = safe_unicode(val)
3977 3978
3978 3979 @declared_attr
3979 3980 def target_repo_id(cls):
3980 3981 # TODO: dan: rename column to target_repo_id
3981 3982 return Column(
3982 3983 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3983 3984 nullable=False)
3984 3985
3985 3986 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3986 3987
3987 3988 # TODO: dan: rename column to last_merge_source_rev
3988 3989 _last_merge_source_rev = Column(
3989 3990 'last_merge_org_rev', String(40), nullable=True)
3990 3991 # TODO: dan: rename column to last_merge_target_rev
3991 3992 _last_merge_target_rev = Column(
3992 3993 'last_merge_other_rev', String(40), nullable=True)
3993 3994 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3994 3995 merge_rev = Column('merge_rev', String(40), nullable=True)
3995 3996
3996 3997 reviewer_data = Column(
3997 3998 'reviewer_data_json', MutationObj.as_mutable(
3998 3999 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3999 4000
4000 4001 @property
4001 4002 def reviewer_data_json(self):
4002 4003 return json.dumps(self.reviewer_data)
4003 4004
4004 4005 @hybrid_property
4005 4006 def description_safe(self):
4006 4007 from rhodecode.lib import helpers as h
4007 4008 return h.escape(self.description)
4008 4009
4009 4010 @hybrid_property
4010 4011 def revisions(self):
4011 4012 return self._revisions.split(':') if self._revisions else []
4012 4013
4013 4014 @revisions.setter
4014 4015 def revisions(self, val):
4015 4016 self._revisions = u':'.join(val)
4016 4017
4017 4018 @hybrid_property
4018 4019 def last_merge_status(self):
4019 4020 return safe_int(self._last_merge_status)
4020 4021
4021 4022 @last_merge_status.setter
4022 4023 def last_merge_status(self, val):
4023 4024 self._last_merge_status = val
4024 4025
4025 4026 @declared_attr
4026 4027 def author(cls):
4027 4028 return relationship('User', lazy='joined')
4028 4029
4029 4030 @declared_attr
4030 4031 def source_repo(cls):
4031 4032 return relationship(
4032 4033 'Repository',
4033 4034 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
4034 4035
4035 4036 @property
4036 4037 def source_ref_parts(self):
4037 4038 return self.unicode_to_reference(self.source_ref)
4038 4039
4039 4040 @declared_attr
4040 4041 def target_repo(cls):
4041 4042 return relationship(
4042 4043 'Repository',
4043 4044 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
4044 4045
4045 4046 @property
4046 4047 def target_ref_parts(self):
4047 4048 return self.unicode_to_reference(self.target_ref)
4048 4049
4049 4050 @property
4050 4051 def shadow_merge_ref(self):
4051 4052 return self.unicode_to_reference(self._shadow_merge_ref)
4052 4053
4053 4054 @shadow_merge_ref.setter
4054 4055 def shadow_merge_ref(self, ref):
4055 4056 self._shadow_merge_ref = self.reference_to_unicode(ref)
4056 4057
4057 4058 @staticmethod
4058 4059 def unicode_to_reference(raw):
4059 4060 """
4060 4061 Convert a unicode (or string) to a reference object.
4061 4062 If unicode evaluates to False it returns None.
4062 4063 """
4063 4064 if raw:
4064 4065 refs = raw.split(':')
4065 4066 return Reference(*refs)
4066 4067 else:
4067 4068 return None
4068 4069
4069 4070 @staticmethod
4070 4071 def reference_to_unicode(ref):
4071 4072 """
4072 4073 Convert a reference object to unicode.
4073 4074 If reference is None it returns None.
4074 4075 """
4075 4076 if ref:
4076 4077 return u':'.join(ref)
4077 4078 else:
4078 4079 return None
4079 4080
4080 4081 def get_api_data(self, with_merge_state=True):
4081 4082 from rhodecode.model.pull_request import PullRequestModel
4082 4083
4083 4084 pull_request = self
4084 4085 if with_merge_state:
4085 4086 merge_status = PullRequestModel().merge_status(pull_request)
4086 4087 merge_state = {
4087 4088 'status': merge_status[0],
4088 4089 'message': safe_unicode(merge_status[1]),
4089 4090 }
4090 4091 else:
4091 4092 merge_state = {'status': 'not_available',
4092 4093 'message': 'not_available'}
4093 4094
4094 4095 merge_data = {
4095 4096 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
4096 4097 'reference': (
4097 4098 pull_request.shadow_merge_ref._asdict()
4098 4099 if pull_request.shadow_merge_ref else None),
4099 4100 }
4100 4101
4101 4102 data = {
4102 4103 'pull_request_id': pull_request.pull_request_id,
4103 4104 'url': PullRequestModel().get_url(pull_request),
4104 4105 'title': pull_request.title,
4105 4106 'description': pull_request.description,
4106 4107 'status': pull_request.status,
4107 4108 'state': pull_request.pull_request_state,
4108 4109 'created_on': pull_request.created_on,
4109 4110 'updated_on': pull_request.updated_on,
4110 4111 'commit_ids': pull_request.revisions,
4111 4112 'review_status': pull_request.calculated_review_status(),
4112 4113 'mergeable': merge_state,
4113 4114 'source': {
4114 4115 'clone_url': pull_request.source_repo.clone_url(),
4115 4116 'repository': pull_request.source_repo.repo_name,
4116 4117 'reference': {
4117 4118 'name': pull_request.source_ref_parts.name,
4118 4119 'type': pull_request.source_ref_parts.type,
4119 4120 'commit_id': pull_request.source_ref_parts.commit_id,
4120 4121 },
4121 4122 },
4122 4123 'target': {
4123 4124 'clone_url': pull_request.target_repo.clone_url(),
4124 4125 'repository': pull_request.target_repo.repo_name,
4125 4126 'reference': {
4126 4127 'name': pull_request.target_ref_parts.name,
4127 4128 'type': pull_request.target_ref_parts.type,
4128 4129 'commit_id': pull_request.target_ref_parts.commit_id,
4129 4130 },
4130 4131 },
4131 4132 'merge': merge_data,
4132 4133 'author': pull_request.author.get_api_data(include_secrets=False,
4133 4134 details='basic'),
4134 4135 'reviewers': [
4135 4136 {
4136 4137 'user': reviewer.get_api_data(include_secrets=False,
4137 4138 details='basic'),
4138 4139 'reasons': reasons,
4139 4140 'review_status': st[0][1].status if st else 'not_reviewed',
4140 4141 }
4141 4142 for obj, reviewer, reasons, mandatory, st in
4142 4143 pull_request.reviewers_statuses()
4143 4144 ]
4144 4145 }
4145 4146
4146 4147 return data
4147 4148
4148 4149 def set_state(self, pull_request_state, final_state=None):
4149 4150 """
4150 4151 # goes from initial state to updating to initial state.
4151 4152 # initial state can be changed by specifying back_state=
4152 4153 with pull_request_obj.set_state(PullRequest.STATE_UPDATING):
4153 4154 pull_request.merge()
4154 4155
4155 4156 :param pull_request_state:
4156 4157 :param final_state:
4157 4158
4158 4159 """
4159 4160
4160 4161 return _SetState(self, pull_request_state, back_state=final_state)
4161 4162
4162 4163
4163 4164 class PullRequest(Base, _PullRequestBase):
4164 4165 __tablename__ = 'pull_requests'
4165 4166 __table_args__ = (
4166 4167 base_table_args,
4167 4168 )
4168 4169
4169 4170 pull_request_id = Column(
4170 4171 'pull_request_id', Integer(), nullable=False, primary_key=True)
4171 4172
4172 4173 def __repr__(self):
4173 4174 if self.pull_request_id:
4174 4175 return '<DB:PullRequest #%s>' % self.pull_request_id
4175 4176 else:
4176 4177 return '<DB:PullRequest at %#x>' % id(self)
4177 4178
4178 4179 reviewers = relationship('PullRequestReviewers', cascade="all, delete-orphan")
4179 4180 statuses = relationship('ChangesetStatus', cascade="all, delete-orphan")
4180 4181 comments = relationship('ChangesetComment', cascade="all, delete-orphan")
4181 4182 versions = relationship('PullRequestVersion', cascade="all, delete-orphan",
4182 4183 lazy='dynamic')
4183 4184
4184 4185 @classmethod
4185 4186 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
4186 4187 internal_methods=None):
4187 4188
4188 4189 class PullRequestDisplay(object):
4189 4190 """
4190 4191 Special object wrapper for showing PullRequest data via Versions
4191 4192 It mimics PR object as close as possible. This is read only object
4192 4193 just for display
4193 4194 """
4194 4195
4195 4196 def __init__(self, attrs, internal=None):
4196 4197 self.attrs = attrs
4197 4198 # internal have priority over the given ones via attrs
4198 4199 self.internal = internal or ['versions']
4199 4200
4200 4201 def __getattr__(self, item):
4201 4202 if item in self.internal:
4202 4203 return getattr(self, item)
4203 4204 try:
4204 4205 return self.attrs[item]
4205 4206 except KeyError:
4206 4207 raise AttributeError(
4207 4208 '%s object has no attribute %s' % (self, item))
4208 4209
4209 4210 def __repr__(self):
4210 4211 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
4211 4212
4212 4213 def versions(self):
4213 4214 return pull_request_obj.versions.order_by(
4214 4215 PullRequestVersion.pull_request_version_id).all()
4215 4216
4216 4217 def is_closed(self):
4217 4218 return pull_request_obj.is_closed()
4218 4219
4219 4220 @property
4220 4221 def pull_request_version_id(self):
4221 4222 return getattr(pull_request_obj, 'pull_request_version_id', None)
4222 4223
4223 4224 attrs = StrictAttributeDict(pull_request_obj.get_api_data(with_merge_state=False))
4224 4225
4225 4226 attrs.author = StrictAttributeDict(
4226 4227 pull_request_obj.author.get_api_data())
4227 4228 if pull_request_obj.target_repo:
4228 4229 attrs.target_repo = StrictAttributeDict(
4229 4230 pull_request_obj.target_repo.get_api_data())
4230 4231 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
4231 4232
4232 4233 if pull_request_obj.source_repo:
4233 4234 attrs.source_repo = StrictAttributeDict(
4234 4235 pull_request_obj.source_repo.get_api_data())
4235 4236 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
4236 4237
4237 4238 attrs.source_ref_parts = pull_request_obj.source_ref_parts
4238 4239 attrs.target_ref_parts = pull_request_obj.target_ref_parts
4239 4240 attrs.revisions = pull_request_obj.revisions
4240 4241
4241 4242 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
4242 4243 attrs.reviewer_data = org_pull_request_obj.reviewer_data
4243 4244 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
4244 4245
4245 4246 return PullRequestDisplay(attrs, internal=internal_methods)
4246 4247
4247 4248 def is_closed(self):
4248 4249 return self.status == self.STATUS_CLOSED
4249 4250
4250 4251 def __json__(self):
4251 4252 return {
4252 4253 'revisions': self.revisions,
4253 4254 }
4254 4255
4255 4256 def calculated_review_status(self):
4256 4257 from rhodecode.model.changeset_status import ChangesetStatusModel
4257 4258 return ChangesetStatusModel().calculated_review_status(self)
4258 4259
4259 4260 def reviewers_statuses(self):
4260 4261 from rhodecode.model.changeset_status import ChangesetStatusModel
4261 4262 return ChangesetStatusModel().reviewers_statuses(self)
4262 4263
4263 4264 @property
4264 4265 def workspace_id(self):
4265 4266 from rhodecode.model.pull_request import PullRequestModel
4266 4267 return PullRequestModel()._workspace_id(self)
4267 4268
4268 4269 def get_shadow_repo(self):
4269 4270 workspace_id = self.workspace_id
4270 4271 shadow_repository_path = self.target_repo.get_shadow_repository_path(workspace_id)
4271 4272 if os.path.isdir(shadow_repository_path):
4272 4273 vcs_obj = self.target_repo.scm_instance()
4273 4274 return vcs_obj.get_shadow_instance(shadow_repository_path)
4274 4275
4275 4276
4276 4277 class PullRequestVersion(Base, _PullRequestBase):
4277 4278 __tablename__ = 'pull_request_versions'
4278 4279 __table_args__ = (
4279 4280 base_table_args,
4280 4281 )
4281 4282
4282 4283 pull_request_version_id = Column(
4283 4284 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
4284 4285 pull_request_id = Column(
4285 4286 'pull_request_id', Integer(),
4286 4287 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4287 4288 pull_request = relationship('PullRequest')
4288 4289
4289 4290 def __repr__(self):
4290 4291 if self.pull_request_version_id:
4291 4292 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
4292 4293 else:
4293 4294 return '<DB:PullRequestVersion at %#x>' % id(self)
4294 4295
4295 4296 @property
4296 4297 def reviewers(self):
4297 4298 return self.pull_request.reviewers
4298 4299
4299 4300 @property
4300 4301 def versions(self):
4301 4302 return self.pull_request.versions
4302 4303
4303 4304 def is_closed(self):
4304 4305 # calculate from original
4305 4306 return self.pull_request.status == self.STATUS_CLOSED
4306 4307
4307 4308 def calculated_review_status(self):
4308 4309 return self.pull_request.calculated_review_status()
4309 4310
4310 4311 def reviewers_statuses(self):
4311 4312 return self.pull_request.reviewers_statuses()
4312 4313
4313 4314
4314 4315 class PullRequestReviewers(Base, BaseModel):
4315 4316 __tablename__ = 'pull_request_reviewers'
4316 4317 __table_args__ = (
4317 4318 base_table_args,
4318 4319 )
4319 4320
4320 4321 @hybrid_property
4321 4322 def reasons(self):
4322 4323 if not self._reasons:
4323 4324 return []
4324 4325 return self._reasons
4325 4326
4326 4327 @reasons.setter
4327 4328 def reasons(self, val):
4328 4329 val = val or []
4329 4330 if any(not isinstance(x, compat.string_types) for x in val):
4330 4331 raise Exception('invalid reasons type, must be list of strings')
4331 4332 self._reasons = val
4332 4333
4333 4334 pull_requests_reviewers_id = Column(
4334 4335 'pull_requests_reviewers_id', Integer(), nullable=False,
4335 4336 primary_key=True)
4336 4337 pull_request_id = Column(
4337 4338 "pull_request_id", Integer(),
4338 4339 ForeignKey('pull_requests.pull_request_id'), nullable=False)
4339 4340 user_id = Column(
4340 4341 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
4341 4342 _reasons = Column(
4342 4343 'reason', MutationList.as_mutable(
4343 4344 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
4344 4345
4345 4346 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4346 4347 user = relationship('User')
4347 4348 pull_request = relationship('PullRequest')
4348 4349
4349 4350 rule_data = Column(
4350 4351 'rule_data_json',
4351 4352 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
4352 4353
4353 4354 def rule_user_group_data(self):
4354 4355 """
4355 4356 Returns the voting user group rule data for this reviewer
4356 4357 """
4357 4358
4358 4359 if self.rule_data and 'vote_rule' in self.rule_data:
4359 4360 user_group_data = {}
4360 4361 if 'rule_user_group_entry_id' in self.rule_data:
4361 4362 # means a group with voting rules !
4362 4363 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
4363 4364 user_group_data['name'] = self.rule_data['rule_name']
4364 4365 user_group_data['vote_rule'] = self.rule_data['vote_rule']
4365 4366
4366 4367 return user_group_data
4367 4368
4368 4369 def __unicode__(self):
4369 4370 return u"<%s('id:%s')>" % (self.__class__.__name__,
4370 4371 self.pull_requests_reviewers_id)
4371 4372
4372 4373
4373 4374 class Notification(Base, BaseModel):
4374 4375 __tablename__ = 'notifications'
4375 4376 __table_args__ = (
4376 4377 Index('notification_type_idx', 'type'),
4377 4378 base_table_args,
4378 4379 )
4379 4380
4380 4381 TYPE_CHANGESET_COMMENT = u'cs_comment'
4381 4382 TYPE_MESSAGE = u'message'
4382 4383 TYPE_MENTION = u'mention'
4383 4384 TYPE_REGISTRATION = u'registration'
4384 4385 TYPE_PULL_REQUEST = u'pull_request'
4385 4386 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
4386 4387
4387 4388 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
4388 4389 subject = Column('subject', Unicode(512), nullable=True)
4389 4390 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
4390 4391 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
4391 4392 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4392 4393 type_ = Column('type', Unicode(255))
4393 4394
4394 4395 created_by_user = relationship('User')
4395 4396 notifications_to_users = relationship('UserNotification', lazy='joined',
4396 4397 cascade="all, delete-orphan")
4397 4398
4398 4399 @property
4399 4400 def recipients(self):
4400 4401 return [x.user for x in UserNotification.query()\
4401 4402 .filter(UserNotification.notification == self)\
4402 4403 .order_by(UserNotification.user_id.asc()).all()]
4403 4404
4404 4405 @classmethod
4405 4406 def create(cls, created_by, subject, body, recipients, type_=None):
4406 4407 if type_ is None:
4407 4408 type_ = Notification.TYPE_MESSAGE
4408 4409
4409 4410 notification = cls()
4410 4411 notification.created_by_user = created_by
4411 4412 notification.subject = subject
4412 4413 notification.body = body
4413 4414 notification.type_ = type_
4414 4415 notification.created_on = datetime.datetime.now()
4415 4416
4416 4417 # For each recipient link the created notification to his account
4417 4418 for u in recipients:
4418 4419 assoc = UserNotification()
4419 4420 assoc.user_id = u.user_id
4420 4421 assoc.notification = notification
4421 4422
4422 4423 # if created_by is inside recipients mark his notification
4423 4424 # as read
4424 4425 if u.user_id == created_by.user_id:
4425 4426 assoc.read = True
4426 4427 Session().add(assoc)
4427 4428
4428 4429 Session().add(notification)
4429 4430
4430 4431 return notification
4431 4432
4432 4433
4433 4434 class UserNotification(Base, BaseModel):
4434 4435 __tablename__ = 'user_to_notification'
4435 4436 __table_args__ = (
4436 4437 UniqueConstraint('user_id', 'notification_id'),
4437 4438 base_table_args
4438 4439 )
4439 4440
4440 4441 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4441 4442 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
4442 4443 read = Column('read', Boolean, default=False)
4443 4444 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
4444 4445
4445 4446 user = relationship('User', lazy="joined")
4446 4447 notification = relationship('Notification', lazy="joined",
4447 4448 order_by=lambda: Notification.created_on.desc(),)
4448 4449
4449 4450 def mark_as_read(self):
4450 4451 self.read = True
4451 4452 Session().add(self)
4452 4453
4453 4454
4454 4455 class Gist(Base, BaseModel):
4455 4456 __tablename__ = 'gists'
4456 4457 __table_args__ = (
4457 4458 Index('g_gist_access_id_idx', 'gist_access_id'),
4458 4459 Index('g_created_on_idx', 'created_on'),
4459 4460 base_table_args
4460 4461 )
4461 4462
4462 4463 GIST_PUBLIC = u'public'
4463 4464 GIST_PRIVATE = u'private'
4464 4465 DEFAULT_FILENAME = u'gistfile1.txt'
4465 4466
4466 4467 ACL_LEVEL_PUBLIC = u'acl_public'
4467 4468 ACL_LEVEL_PRIVATE = u'acl_private'
4468 4469
4469 4470 gist_id = Column('gist_id', Integer(), primary_key=True)
4470 4471 gist_access_id = Column('gist_access_id', Unicode(250))
4471 4472 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
4472 4473 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
4473 4474 gist_expires = Column('gist_expires', Float(53), nullable=False)
4474 4475 gist_type = Column('gist_type', Unicode(128), nullable=False)
4475 4476 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4476 4477 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4477 4478 acl_level = Column('acl_level', Unicode(128), nullable=True)
4478 4479
4479 4480 owner = relationship('User')
4480 4481
4481 4482 def __repr__(self):
4482 4483 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
4483 4484
4484 4485 @hybrid_property
4485 4486 def description_safe(self):
4486 4487 from rhodecode.lib import helpers as h
4487 4488 return h.escape(self.gist_description)
4488 4489
4489 4490 @classmethod
4490 4491 def get_or_404(cls, id_):
4491 4492 from pyramid.httpexceptions import HTTPNotFound
4492 4493
4493 4494 res = cls.query().filter(cls.gist_access_id == id_).scalar()
4494 4495 if not res:
4495 4496 raise HTTPNotFound()
4496 4497 return res
4497 4498
4498 4499 @classmethod
4499 4500 def get_by_access_id(cls, gist_access_id):
4500 4501 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
4501 4502
4502 4503 def gist_url(self):
4503 4504 from rhodecode.model.gist import GistModel
4504 4505 return GistModel().get_url(self)
4505 4506
4506 4507 @classmethod
4507 4508 def base_path(cls):
4508 4509 """
4509 4510 Returns base path when all gists are stored
4510 4511
4511 4512 :param cls:
4512 4513 """
4513 4514 from rhodecode.model.gist import GIST_STORE_LOC
4514 4515 q = Session().query(RhodeCodeUi)\
4515 4516 .filter(RhodeCodeUi.ui_key == URL_SEP)
4516 4517 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
4517 4518 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
4518 4519
4519 4520 def get_api_data(self):
4520 4521 """
4521 4522 Common function for generating gist related data for API
4522 4523 """
4523 4524 gist = self
4524 4525 data = {
4525 4526 'gist_id': gist.gist_id,
4526 4527 'type': gist.gist_type,
4527 4528 'access_id': gist.gist_access_id,
4528 4529 'description': gist.gist_description,
4529 4530 'url': gist.gist_url(),
4530 4531 'expires': gist.gist_expires,
4531 4532 'created_on': gist.created_on,
4532 4533 'modified_at': gist.modified_at,
4533 4534 'content': None,
4534 4535 'acl_level': gist.acl_level,
4535 4536 }
4536 4537 return data
4537 4538
4538 4539 def __json__(self):
4539 4540 data = dict(
4540 4541 )
4541 4542 data.update(self.get_api_data())
4542 4543 return data
4543 4544 # SCM functions
4544 4545
4545 4546 def scm_instance(self, **kwargs):
4546 4547 """
4547 4548 Get an instance of VCS Repository
4548 4549
4549 4550 :param kwargs:
4550 4551 """
4551 4552 from rhodecode.model.gist import GistModel
4552 4553 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4553 4554 return get_vcs_instance(
4554 4555 repo_path=safe_str(full_repo_path), create=False,
4555 4556 _vcs_alias=GistModel.vcs_backend)
4556 4557
4557 4558
4558 4559 class ExternalIdentity(Base, BaseModel):
4559 4560 __tablename__ = 'external_identities'
4560 4561 __table_args__ = (
4561 4562 Index('local_user_id_idx', 'local_user_id'),
4562 4563 Index('external_id_idx', 'external_id'),
4563 4564 base_table_args
4564 4565 )
4565 4566
4566 4567 external_id = Column('external_id', Unicode(255), default=u'', primary_key=True)
4567 4568 external_username = Column('external_username', Unicode(1024), default=u'')
4568 4569 local_user_id = Column('local_user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
4569 4570 provider_name = Column('provider_name', Unicode(255), default=u'', primary_key=True)
4570 4571 access_token = Column('access_token', String(1024), default=u'')
4571 4572 alt_token = Column('alt_token', String(1024), default=u'')
4572 4573 token_secret = Column('token_secret', String(1024), default=u'')
4573 4574
4574 4575 @classmethod
4575 4576 def by_external_id_and_provider(cls, external_id, provider_name, local_user_id=None):
4576 4577 """
4577 4578 Returns ExternalIdentity instance based on search params
4578 4579
4579 4580 :param external_id:
4580 4581 :param provider_name:
4581 4582 :return: ExternalIdentity
4582 4583 """
4583 4584 query = cls.query()
4584 4585 query = query.filter(cls.external_id == external_id)
4585 4586 query = query.filter(cls.provider_name == provider_name)
4586 4587 if local_user_id:
4587 4588 query = query.filter(cls.local_user_id == local_user_id)
4588 4589 return query.first()
4589 4590
4590 4591 @classmethod
4591 4592 def user_by_external_id_and_provider(cls, external_id, provider_name):
4592 4593 """
4593 4594 Returns User instance based on search params
4594 4595
4595 4596 :param external_id:
4596 4597 :param provider_name:
4597 4598 :return: User
4598 4599 """
4599 4600 query = User.query()
4600 4601 query = query.filter(cls.external_id == external_id)
4601 4602 query = query.filter(cls.provider_name == provider_name)
4602 4603 query = query.filter(User.user_id == cls.local_user_id)
4603 4604 return query.first()
4604 4605
4605 4606 @classmethod
4606 4607 def by_local_user_id(cls, local_user_id):
4607 4608 """
4608 4609 Returns all tokens for user
4609 4610
4610 4611 :param local_user_id:
4611 4612 :return: ExternalIdentity
4612 4613 """
4613 4614 query = cls.query()
4614 4615 query = query.filter(cls.local_user_id == local_user_id)
4615 4616 return query
4616 4617
4617 4618 @classmethod
4618 4619 def load_provider_plugin(cls, plugin_id):
4619 4620 from rhodecode.authentication.base import loadplugin
4620 4621 _plugin_id = 'egg:rhodecode-enterprise-ee#{}'.format(plugin_id)
4621 4622 auth_plugin = loadplugin(_plugin_id)
4622 4623 return auth_plugin
4623 4624
4624 4625
4625 4626 class Integration(Base, BaseModel):
4626 4627 __tablename__ = 'integrations'
4627 4628 __table_args__ = (
4628 4629 base_table_args
4629 4630 )
4630 4631
4631 4632 integration_id = Column('integration_id', Integer(), primary_key=True)
4632 4633 integration_type = Column('integration_type', String(255))
4633 4634 enabled = Column('enabled', Boolean(), nullable=False)
4634 4635 name = Column('name', String(255), nullable=False)
4635 4636 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4636 4637 default=False)
4637 4638
4638 4639 settings = Column(
4639 4640 'settings_json', MutationObj.as_mutable(
4640 4641 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4641 4642 repo_id = Column(
4642 4643 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4643 4644 nullable=True, unique=None, default=None)
4644 4645 repo = relationship('Repository', lazy='joined')
4645 4646
4646 4647 repo_group_id = Column(
4647 4648 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4648 4649 nullable=True, unique=None, default=None)
4649 4650 repo_group = relationship('RepoGroup', lazy='joined')
4650 4651
4651 4652 @property
4652 4653 def scope(self):
4653 4654 if self.repo:
4654 4655 return repr(self.repo)
4655 4656 if self.repo_group:
4656 4657 if self.child_repos_only:
4657 4658 return repr(self.repo_group) + ' (child repos only)'
4658 4659 else:
4659 4660 return repr(self.repo_group) + ' (recursive)'
4660 4661 if self.child_repos_only:
4661 4662 return 'root_repos'
4662 4663 return 'global'
4663 4664
4664 4665 def __repr__(self):
4665 4666 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4666 4667
4667 4668
4668 4669 class RepoReviewRuleUser(Base, BaseModel):
4669 4670 __tablename__ = 'repo_review_rules_users'
4670 4671 __table_args__ = (
4671 4672 base_table_args
4672 4673 )
4673 4674
4674 4675 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4675 4676 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4676 4677 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4677 4678 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4678 4679 user = relationship('User')
4679 4680
4680 4681 def rule_data(self):
4681 4682 return {
4682 4683 'mandatory': self.mandatory
4683 4684 }
4684 4685
4685 4686
4686 4687 class RepoReviewRuleUserGroup(Base, BaseModel):
4687 4688 __tablename__ = 'repo_review_rules_users_groups'
4688 4689 __table_args__ = (
4689 4690 base_table_args
4690 4691 )
4691 4692
4692 4693 VOTE_RULE_ALL = -1
4693 4694
4694 4695 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4695 4696 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4696 4697 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4697 4698 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4698 4699 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4699 4700 users_group = relationship('UserGroup')
4700 4701
4701 4702 def rule_data(self):
4702 4703 return {
4703 4704 'mandatory': self.mandatory,
4704 4705 'vote_rule': self.vote_rule
4705 4706 }
4706 4707
4707 4708 @property
4708 4709 def vote_rule_label(self):
4709 4710 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4710 4711 return 'all must vote'
4711 4712 else:
4712 4713 return 'min. vote {}'.format(self.vote_rule)
4713 4714
4714 4715
4715 4716 class RepoReviewRule(Base, BaseModel):
4716 4717 __tablename__ = 'repo_review_rules'
4717 4718 __table_args__ = (
4718 4719 base_table_args
4719 4720 )
4720 4721
4721 4722 repo_review_rule_id = Column(
4722 4723 'repo_review_rule_id', Integer(), primary_key=True)
4723 4724 repo_id = Column(
4724 4725 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4725 4726 repo = relationship('Repository', backref='review_rules')
4726 4727
4727 4728 review_rule_name = Column('review_rule_name', String(255))
4728 4729 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4729 4730 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4730 4731 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4731 4732
4732 4733 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4733 4734 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4734 4735 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4735 4736 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4736 4737
4737 4738 rule_users = relationship('RepoReviewRuleUser')
4738 4739 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4739 4740
4740 4741 def _validate_pattern(self, value):
4741 4742 re.compile('^' + glob2re(value) + '$')
4742 4743
4743 4744 @hybrid_property
4744 4745 def source_branch_pattern(self):
4745 4746 return self._branch_pattern or '*'
4746 4747
4747 4748 @source_branch_pattern.setter
4748 4749 def source_branch_pattern(self, value):
4749 4750 self._validate_pattern(value)
4750 4751 self._branch_pattern = value or '*'
4751 4752
4752 4753 @hybrid_property
4753 4754 def target_branch_pattern(self):
4754 4755 return self._target_branch_pattern or '*'
4755 4756
4756 4757 @target_branch_pattern.setter
4757 4758 def target_branch_pattern(self, value):
4758 4759 self._validate_pattern(value)
4759 4760 self._target_branch_pattern = value or '*'
4760 4761
4761 4762 @hybrid_property
4762 4763 def file_pattern(self):
4763 4764 return self._file_pattern or '*'
4764 4765
4765 4766 @file_pattern.setter
4766 4767 def file_pattern(self, value):
4767 4768 self._validate_pattern(value)
4768 4769 self._file_pattern = value or '*'
4769 4770
4770 4771 def matches(self, source_branch, target_branch, files_changed):
4771 4772 """
4772 4773 Check if this review rule matches a branch/files in a pull request
4773 4774
4774 4775 :param source_branch: source branch name for the commit
4775 4776 :param target_branch: target branch name for the commit
4776 4777 :param files_changed: list of file paths changed in the pull request
4777 4778 """
4778 4779
4779 4780 source_branch = source_branch or ''
4780 4781 target_branch = target_branch or ''
4781 4782 files_changed = files_changed or []
4782 4783
4783 4784 branch_matches = True
4784 4785 if source_branch or target_branch:
4785 4786 if self.source_branch_pattern == '*':
4786 4787 source_branch_match = True
4787 4788 else:
4788 4789 if self.source_branch_pattern.startswith('re:'):
4789 4790 source_pattern = self.source_branch_pattern[3:]
4790 4791 else:
4791 4792 source_pattern = '^' + glob2re(self.source_branch_pattern) + '$'
4792 4793 source_branch_regex = re.compile(source_pattern)
4793 4794 source_branch_match = bool(source_branch_regex.search(source_branch))
4794 4795 if self.target_branch_pattern == '*':
4795 4796 target_branch_match = True
4796 4797 else:
4797 4798 if self.target_branch_pattern.startswith('re:'):
4798 4799 target_pattern = self.target_branch_pattern[3:]
4799 4800 else:
4800 4801 target_pattern = '^' + glob2re(self.target_branch_pattern) + '$'
4801 4802 target_branch_regex = re.compile(target_pattern)
4802 4803 target_branch_match = bool(target_branch_regex.search(target_branch))
4803 4804
4804 4805 branch_matches = source_branch_match and target_branch_match
4805 4806
4806 4807 files_matches = True
4807 4808 if self.file_pattern != '*':
4808 4809 files_matches = False
4809 4810 if self.file_pattern.startswith('re:'):
4810 4811 file_pattern = self.file_pattern[3:]
4811 4812 else:
4812 4813 file_pattern = glob2re(self.file_pattern)
4813 4814 file_regex = re.compile(file_pattern)
4814 4815 for filename in files_changed:
4815 4816 if file_regex.search(filename):
4816 4817 files_matches = True
4817 4818 break
4818 4819
4819 4820 return branch_matches and files_matches
4820 4821
4821 4822 @property
4822 4823 def review_users(self):
4823 4824 """ Returns the users which this rule applies to """
4824 4825
4825 4826 users = collections.OrderedDict()
4826 4827
4827 4828 for rule_user in self.rule_users:
4828 4829 if rule_user.user.active:
4829 4830 if rule_user.user not in users:
4830 4831 users[rule_user.user.username] = {
4831 4832 'user': rule_user.user,
4832 4833 'source': 'user',
4833 4834 'source_data': {},
4834 4835 'data': rule_user.rule_data()
4835 4836 }
4836 4837
4837 4838 for rule_user_group in self.rule_user_groups:
4838 4839 source_data = {
4839 4840 'user_group_id': rule_user_group.users_group.users_group_id,
4840 4841 'name': rule_user_group.users_group.users_group_name,
4841 4842 'members': len(rule_user_group.users_group.members)
4842 4843 }
4843 4844 for member in rule_user_group.users_group.members:
4844 4845 if member.user.active:
4845 4846 key = member.user.username
4846 4847 if key in users:
4847 4848 # skip this member as we have him already
4848 4849 # this prevents from override the "first" matched
4849 4850 # users with duplicates in multiple groups
4850 4851 continue
4851 4852
4852 4853 users[key] = {
4853 4854 'user': member.user,
4854 4855 'source': 'user_group',
4855 4856 'source_data': source_data,
4856 4857 'data': rule_user_group.rule_data()
4857 4858 }
4858 4859
4859 4860 return users
4860 4861
4861 4862 def user_group_vote_rule(self, user_id):
4862 4863
4863 4864 rules = []
4864 4865 if not self.rule_user_groups:
4865 4866 return rules
4866 4867
4867 4868 for user_group in self.rule_user_groups:
4868 4869 user_group_members = [x.user_id for x in user_group.users_group.members]
4869 4870 if user_id in user_group_members:
4870 4871 rules.append(user_group)
4871 4872 return rules
4872 4873
4873 4874 def __repr__(self):
4874 4875 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4875 4876 self.repo_review_rule_id, self.repo)
4876 4877
4877 4878
4878 4879 class ScheduleEntry(Base, BaseModel):
4879 4880 __tablename__ = 'schedule_entries'
4880 4881 __table_args__ = (
4881 4882 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4882 4883 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4883 4884 base_table_args,
4884 4885 )
4885 4886
4886 4887 schedule_types = ['crontab', 'timedelta', 'integer']
4887 4888 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4888 4889
4889 4890 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4890 4891 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4891 4892 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4892 4893
4893 4894 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4894 4895 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4895 4896
4896 4897 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4897 4898 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4898 4899
4899 4900 # task
4900 4901 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4901 4902 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4902 4903 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4903 4904 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4904 4905
4905 4906 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4906 4907 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4907 4908
4908 4909 @hybrid_property
4909 4910 def schedule_type(self):
4910 4911 return self._schedule_type
4911 4912
4912 4913 @schedule_type.setter
4913 4914 def schedule_type(self, val):
4914 4915 if val not in self.schedule_types:
4915 4916 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4916 4917 val, self.schedule_type))
4917 4918
4918 4919 self._schedule_type = val
4919 4920
4920 4921 @classmethod
4921 4922 def get_uid(cls, obj):
4922 4923 args = obj.task_args
4923 4924 kwargs = obj.task_kwargs
4924 4925 if isinstance(args, JsonRaw):
4925 4926 try:
4926 4927 args = json.loads(args)
4927 4928 except ValueError:
4928 4929 args = tuple()
4929 4930
4930 4931 if isinstance(kwargs, JsonRaw):
4931 4932 try:
4932 4933 kwargs = json.loads(kwargs)
4933 4934 except ValueError:
4934 4935 kwargs = dict()
4935 4936
4936 4937 dot_notation = obj.task_dot_notation
4937 4938 val = '.'.join(map(safe_str, [
4938 4939 sorted(dot_notation), args, sorted(kwargs.items())]))
4939 4940 return hashlib.sha1(val).hexdigest()
4940 4941
4941 4942 @classmethod
4942 4943 def get_by_schedule_name(cls, schedule_name):
4943 4944 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4944 4945
4945 4946 @classmethod
4946 4947 def get_by_schedule_id(cls, schedule_id):
4947 4948 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4948 4949
4949 4950 @property
4950 4951 def task(self):
4951 4952 return self.task_dot_notation
4952 4953
4953 4954 @property
4954 4955 def schedule(self):
4955 4956 from rhodecode.lib.celerylib.utils import raw_2_schedule
4956 4957 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4957 4958 return schedule
4958 4959
4959 4960 @property
4960 4961 def args(self):
4961 4962 try:
4962 4963 return list(self.task_args or [])
4963 4964 except ValueError:
4964 4965 return list()
4965 4966
4966 4967 @property
4967 4968 def kwargs(self):
4968 4969 try:
4969 4970 return dict(self.task_kwargs or {})
4970 4971 except ValueError:
4971 4972 return dict()
4972 4973
4973 4974 def _as_raw(self, val):
4974 4975 if hasattr(val, 'de_coerce'):
4975 4976 val = val.de_coerce()
4976 4977 if val:
4977 4978 val = json.dumps(val)
4978 4979
4979 4980 return val
4980 4981
4981 4982 @property
4982 4983 def schedule_definition_raw(self):
4983 4984 return self._as_raw(self.schedule_definition)
4984 4985
4985 4986 @property
4986 4987 def args_raw(self):
4987 4988 return self._as_raw(self.task_args)
4988 4989
4989 4990 @property
4990 4991 def kwargs_raw(self):
4991 4992 return self._as_raw(self.task_kwargs)
4992 4993
4993 4994 def __repr__(self):
4994 4995 return '<DB:ScheduleEntry({}:{})>'.format(
4995 4996 self.schedule_entry_id, self.schedule_name)
4996 4997
4997 4998
4998 4999 @event.listens_for(ScheduleEntry, 'before_update')
4999 5000 def update_task_uid(mapper, connection, target):
5000 5001 target.task_uid = ScheduleEntry.get_uid(target)
5001 5002
5002 5003
5003 5004 @event.listens_for(ScheduleEntry, 'before_insert')
5004 5005 def set_task_uid(mapper, connection, target):
5005 5006 target.task_uid = ScheduleEntry.get_uid(target)
5006 5007
5007 5008
5008 5009 class _BaseBranchPerms(BaseModel):
5009 5010 @classmethod
5010 5011 def compute_hash(cls, value):
5011 5012 return sha1_safe(value)
5012 5013
5013 5014 @hybrid_property
5014 5015 def branch_pattern(self):
5015 5016 return self._branch_pattern or '*'
5016 5017
5017 5018 @hybrid_property
5018 5019 def branch_hash(self):
5019 5020 return self._branch_hash
5020 5021
5021 5022 def _validate_glob(self, value):
5022 5023 re.compile('^' + glob2re(value) + '$')
5023 5024
5024 5025 @branch_pattern.setter
5025 5026 def branch_pattern(self, value):
5026 5027 self._validate_glob(value)
5027 5028 self._branch_pattern = value or '*'
5028 5029 # set the Hash when setting the branch pattern
5029 5030 self._branch_hash = self.compute_hash(self._branch_pattern)
5030 5031
5031 5032 def matches(self, branch):
5032 5033 """
5033 5034 Check if this the branch matches entry
5034 5035
5035 5036 :param branch: branch name for the commit
5036 5037 """
5037 5038
5038 5039 branch = branch or ''
5039 5040
5040 5041 branch_matches = True
5041 5042 if branch:
5042 5043 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
5043 5044 branch_matches = bool(branch_regex.search(branch))
5044 5045
5045 5046 return branch_matches
5046 5047
5047 5048
5048 5049 class UserToRepoBranchPermission(Base, _BaseBranchPerms):
5049 5050 __tablename__ = 'user_to_repo_branch_permissions'
5050 5051 __table_args__ = (
5051 5052 base_table_args
5052 5053 )
5053 5054
5054 5055 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5055 5056
5056 5057 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5057 5058 repo = relationship('Repository', backref='user_branch_perms')
5058 5059
5059 5060 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5060 5061 permission = relationship('Permission')
5061 5062
5062 5063 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('repo_to_perm.repo_to_perm_id'), nullable=False, unique=None, default=None)
5063 5064 user_repo_to_perm = relationship('UserRepoToPerm')
5064 5065
5065 5066 rule_order = Column('rule_order', Integer(), nullable=False)
5066 5067 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5067 5068 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5068 5069
5069 5070 def __unicode__(self):
5070 5071 return u'<UserBranchPermission(%s => %r)>' % (
5071 5072 self.user_repo_to_perm, self.branch_pattern)
5072 5073
5073 5074
5074 5075 class UserGroupToRepoBranchPermission(Base, _BaseBranchPerms):
5075 5076 __tablename__ = 'user_group_to_repo_branch_permissions'
5076 5077 __table_args__ = (
5077 5078 base_table_args
5078 5079 )
5079 5080
5080 5081 branch_rule_id = Column('branch_rule_id', Integer(), primary_key=True)
5081 5082
5082 5083 repository_id = Column('repository_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
5083 5084 repo = relationship('Repository', backref='user_group_branch_perms')
5084 5085
5085 5086 permission_id = Column('permission_id', Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
5086 5087 permission = relationship('Permission')
5087 5088
5088 5089 rule_to_perm_id = Column('rule_to_perm_id', Integer(), ForeignKey('users_group_repo_to_perm.users_group_to_perm_id'), nullable=False, unique=None, default=None)
5089 5090 user_group_repo_to_perm = relationship('UserGroupRepoToPerm')
5090 5091
5091 5092 rule_order = Column('rule_order', Integer(), nullable=False)
5092 5093 _branch_pattern = Column('branch_pattern', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), default=u'*') # glob
5093 5094 _branch_hash = Column('branch_hash', UnicodeText().with_variant(UnicodeText(2048), 'mysql'))
5094 5095
5095 5096 def __unicode__(self):
5096 5097 return u'<UserBranchPermission(%s => %r)>' % (
5097 5098 self.user_group_repo_to_perm, self.branch_pattern)
5098 5099
5099 5100
5100 5101 class UserBookmark(Base, BaseModel):
5101 5102 __tablename__ = 'user_bookmarks'
5102 5103 __table_args__ = (
5103 5104 UniqueConstraint('user_id', 'bookmark_repo_id'),
5104 5105 UniqueConstraint('user_id', 'bookmark_repo_group_id'),
5105 5106 UniqueConstraint('user_id', 'bookmark_position'),
5106 5107 base_table_args
5107 5108 )
5108 5109
5109 5110 user_bookmark_id = Column("user_bookmark_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
5110 5111 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
5111 5112 position = Column("bookmark_position", Integer(), nullable=False)
5112 5113 title = Column("bookmark_title", String(255), nullable=True, unique=None, default=None)
5113 5114 redirect_url = Column("bookmark_redirect_url", String(10240), nullable=True, unique=None, default=None)
5114 5115 created_on = Column("created_on", DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5115 5116
5116 5117 bookmark_repo_id = Column("bookmark_repo_id", Integer(), ForeignKey("repositories.repo_id"), nullable=True, unique=None, default=None)
5117 5118 bookmark_repo_group_id = Column("bookmark_repo_group_id", Integer(), ForeignKey("groups.group_id"), nullable=True, unique=None, default=None)
5118 5119
5119 5120 user = relationship("User")
5120 5121
5121 5122 repository = relationship("Repository")
5122 5123 repository_group = relationship("RepoGroup")
5123 5124
5124 5125 @classmethod
5125 5126 def get_by_position_for_user(cls, position, user_id):
5126 5127 return cls.query() \
5127 5128 .filter(UserBookmark.user_id == user_id) \
5128 5129 .filter(UserBookmark.position == position).scalar()
5129 5130
5130 5131 @classmethod
5131 5132 def get_bookmarks_for_user(cls, user_id):
5132 5133 return cls.query() \
5133 5134 .filter(UserBookmark.user_id == user_id) \
5134 5135 .options(joinedload(UserBookmark.repository)) \
5135 5136 .options(joinedload(UserBookmark.repository_group)) \
5136 5137 .order_by(UserBookmark.position.asc()) \
5137 5138 .all()
5138 5139
5139 5140 def __unicode__(self):
5140 5141 return u'<UserBookmark(%s @ %r)>' % (self.position, self.redirect_url)
5141 5142
5142 5143
5143 5144 class FileStore(Base, BaseModel):
5144 5145 __tablename__ = 'file_store'
5145 5146 __table_args__ = (
5146 5147 base_table_args
5147 5148 )
5148 5149
5149 5150 file_store_id = Column('file_store_id', Integer(), primary_key=True)
5150 5151 file_uid = Column('file_uid', String(1024), nullable=False)
5151 5152 file_display_name = Column('file_display_name', UnicodeText().with_variant(UnicodeText(2048), 'mysql'), nullable=True)
5152 5153 file_description = Column('file_description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=True)
5153 5154 file_org_name = Column('file_org_name', UnicodeText().with_variant(UnicodeText(10240), 'mysql'), nullable=False)
5154 5155
5155 5156 # sha256 hash
5156 5157 file_hash = Column('file_hash', String(512), nullable=False)
5157 5158 file_size = Column('file_size', BigInteger(), nullable=False)
5158 5159
5159 5160 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
5160 5161 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True)
5161 5162 accessed_count = Column('accessed_count', Integer(), default=0)
5162 5163
5163 5164 enabled = Column('enabled', Boolean(), nullable=False, default=True)
5164 5165
5165 5166 # if repo/repo_group reference is set, check for permissions
5166 5167 check_acl = Column('check_acl', Boolean(), nullable=False, default=True)
5167 5168
5168 5169 # hidden defines an attachment that should be hidden from showing in artifact listing
5169 5170 hidden = Column('hidden', Boolean(), nullable=False, default=False)
5170 5171
5171 5172 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
5172 5173 upload_user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.user_id')
5173 5174
5174 5175 file_metadata = relationship('FileStoreMetadata', lazy='joined')
5175 5176
5176 5177 # scope limited to user, which requester have access to
5177 5178 scope_user_id = Column(
5178 5179 'scope_user_id', Integer(), ForeignKey('users.user_id'),
5179 5180 nullable=True, unique=None, default=None)
5180 5181 user = relationship('User', lazy='joined', primaryjoin='User.user_id==FileStore.scope_user_id')
5181 5182
5182 5183 # scope limited to user group, which requester have access to
5183 5184 scope_user_group_id = Column(
5184 5185 'scope_user_group_id', Integer(), ForeignKey('users_groups.users_group_id'),
5185 5186 nullable=True, unique=None, default=None)
5186 5187 user_group = relationship('UserGroup', lazy='joined')
5187 5188
5188 5189 # scope limited to repo, which requester have access to
5189 5190 scope_repo_id = Column(
5190 5191 'scope_repo_id', Integer(), ForeignKey('repositories.repo_id'),
5191 5192 nullable=True, unique=None, default=None)
5192 5193 repo = relationship('Repository', lazy='joined')
5193 5194
5194 5195 # scope limited to repo group, which requester have access to
5195 5196 scope_repo_group_id = Column(
5196 5197 'scope_repo_group_id', Integer(), ForeignKey('groups.group_id'),
5197 5198 nullable=True, unique=None, default=None)
5198 5199 repo_group = relationship('RepoGroup', lazy='joined')
5199 5200
5200 5201 @classmethod
5201 5202 def get_by_store_uid(cls, file_store_uid):
5202 5203 return FileStore.query().filter(FileStore.file_uid == file_store_uid).scalar()
5203 5204
5204 5205 @classmethod
5205 5206 def create(cls, file_uid, filename, file_hash, file_size, file_display_name='',
5206 5207 file_description='', enabled=True, hidden=False, check_acl=True,
5207 5208 user_id=None, scope_user_id=None, scope_repo_id=None, scope_repo_group_id=None):
5208 5209
5209 5210 store_entry = FileStore()
5210 5211 store_entry.file_uid = file_uid
5211 5212 store_entry.file_display_name = file_display_name
5212 5213 store_entry.file_org_name = filename
5213 5214 store_entry.file_size = file_size
5214 5215 store_entry.file_hash = file_hash
5215 5216 store_entry.file_description = file_description
5216 5217
5217 5218 store_entry.check_acl = check_acl
5218 5219 store_entry.enabled = enabled
5219 5220 store_entry.hidden = hidden
5220 5221
5221 5222 store_entry.user_id = user_id
5222 5223 store_entry.scope_user_id = scope_user_id
5223 5224 store_entry.scope_repo_id = scope_repo_id
5224 5225 store_entry.scope_repo_group_id = scope_repo_group_id
5225 5226
5226 5227 return store_entry
5227 5228
5228 5229 @classmethod
5229 5230 def store_metadata(cls, file_store_id, args, commit=True):
5230 5231 file_store = FileStore.get(file_store_id)
5231 5232 if file_store is None:
5232 5233 return
5233 5234
5234 5235 for section, key, value, value_type in args:
5235 5236 has_key = FileStoreMetadata().query() \
5236 5237 .filter(FileStoreMetadata.file_store_id == file_store.file_store_id) \
5237 5238 .filter(FileStoreMetadata.file_store_meta_section == section) \
5238 5239 .filter(FileStoreMetadata.file_store_meta_key == key) \
5239 5240 .scalar()
5240 5241 if has_key:
5241 5242 msg = 'key `{}` already defined under section `{}` for this file.'\
5242 5243 .format(key, section)
5243 5244 raise ArtifactMetadataDuplicate(msg, err_section=section, err_key=key)
5244 5245
5245 5246 # NOTE(marcink): raises ArtifactMetadataBadValueType
5246 5247 FileStoreMetadata.valid_value_type(value_type)
5247 5248
5248 5249 meta_entry = FileStoreMetadata()
5249 5250 meta_entry.file_store = file_store
5250 5251 meta_entry.file_store_meta_section = section
5251 5252 meta_entry.file_store_meta_key = key
5252 5253 meta_entry.file_store_meta_value_type = value_type
5253 5254 meta_entry.file_store_meta_value = value
5254 5255
5255 5256 Session().add(meta_entry)
5256 5257
5257 5258 try:
5258 5259 if commit:
5259 5260 Session().commit()
5260 5261 except IntegrityError:
5261 5262 Session().rollback()
5262 5263 raise ArtifactMetadataDuplicate('Duplicate section/key found for this file.')
5263 5264
5264 5265 @classmethod
5265 5266 def bump_access_counter(cls, file_uid, commit=True):
5266 5267 FileStore().query()\
5267 5268 .filter(FileStore.file_uid == file_uid)\
5268 5269 .update({FileStore.accessed_count: (FileStore.accessed_count + 1),
5269 5270 FileStore.accessed_on: datetime.datetime.now()})
5270 5271 if commit:
5271 5272 Session().commit()
5272 5273
5273 5274 def __json__(self):
5274 5275 data = {
5275 5276 'filename': self.file_display_name,
5276 5277 'filename_org': self.file_org_name,
5277 5278 'file_uid': self.file_uid,
5278 5279 'description': self.file_description,
5279 5280 'hidden': self.hidden,
5280 5281 'size': self.file_size,
5281 5282 'created_on': self.created_on,
5282 5283 'uploaded_by': self.upload_user.get_api_data(details='basic'),
5283 5284 'downloaded_times': self.accessed_count,
5284 5285 'sha256': self.file_hash,
5285 5286 'metadata': self.file_metadata,
5286 5287 }
5287 5288
5288 5289 return data
5289 5290
5290 5291 def __repr__(self):
5291 5292 return '<FileStore({})>'.format(self.file_store_id)
5292 5293
5293 5294
5294 5295 class FileStoreMetadata(Base, BaseModel):
5295 5296 __tablename__ = 'file_store_metadata'
5296 5297 __table_args__ = (
5297 5298 UniqueConstraint('file_store_id', 'file_store_meta_section_hash', 'file_store_meta_key_hash'),
5298 5299 Index('file_store_meta_section_idx', 'file_store_meta_section', mysql_length=255),
5299 5300 Index('file_store_meta_key_idx', 'file_store_meta_key', mysql_length=255),
5300 5301 base_table_args
5301 5302 )
5302 5303 SETTINGS_TYPES = {
5303 5304 'str': safe_str,
5304 5305 'int': safe_int,
5305 5306 'unicode': safe_unicode,
5306 5307 'bool': str2bool,
5307 5308 'list': functools.partial(aslist, sep=',')
5308 5309 }
5309 5310
5310 5311 file_store_meta_id = Column(
5311 5312 "file_store_meta_id", Integer(), nullable=False, unique=True, default=None,
5312 5313 primary_key=True)
5313 5314 _file_store_meta_section = Column(
5314 5315 "file_store_meta_section", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5315 5316 nullable=True, unique=None, default=None)
5316 5317 _file_store_meta_section_hash = Column(
5317 5318 "file_store_meta_section_hash", String(255),
5318 5319 nullable=True, unique=None, default=None)
5319 5320 _file_store_meta_key = Column(
5320 5321 "file_store_meta_key", UnicodeText().with_variant(UnicodeText(1024), 'mysql'),
5321 5322 nullable=True, unique=None, default=None)
5322 5323 _file_store_meta_key_hash = Column(
5323 5324 "file_store_meta_key_hash", String(255), nullable=True, unique=None, default=None)
5324 5325 _file_store_meta_value = Column(
5325 5326 "file_store_meta_value", UnicodeText().with_variant(UnicodeText(20480), 'mysql'),
5326 5327 nullable=True, unique=None, default=None)
5327 5328 _file_store_meta_value_type = Column(
5328 5329 "file_store_meta_value_type", String(255), nullable=True, unique=None,
5329 5330 default='unicode')
5330 5331
5331 5332 file_store_id = Column(
5332 5333 'file_store_id', Integer(), ForeignKey('file_store.file_store_id'),
5333 5334 nullable=True, unique=None, default=None)
5334 5335
5335 5336 file_store = relationship('FileStore', lazy='joined')
5336 5337
5337 5338 @classmethod
5338 5339 def valid_value_type(cls, value):
5339 5340 if value.split('.')[0] not in cls.SETTINGS_TYPES:
5340 5341 raise ArtifactMetadataBadValueType(
5341 5342 'value_type must be one of %s got %s' % (cls.SETTINGS_TYPES.keys(), value))
5342 5343
5343 5344 @hybrid_property
5344 5345 def file_store_meta_section(self):
5345 5346 return self._file_store_meta_section
5346 5347
5347 5348 @file_store_meta_section.setter
5348 5349 def file_store_meta_section(self, value):
5349 5350 self._file_store_meta_section = value
5350 5351 self._file_store_meta_section_hash = _hash_key(value)
5351 5352
5352 5353 @hybrid_property
5353 5354 def file_store_meta_key(self):
5354 5355 return self._file_store_meta_key
5355 5356
5356 5357 @file_store_meta_key.setter
5357 5358 def file_store_meta_key(self, value):
5358 5359 self._file_store_meta_key = value
5359 5360 self._file_store_meta_key_hash = _hash_key(value)
5360 5361
5361 5362 @hybrid_property
5362 5363 def file_store_meta_value(self):
5363 5364 val = self._file_store_meta_value
5364 5365
5365 5366 if self._file_store_meta_value_type:
5366 5367 # e.g unicode.encrypted == unicode
5367 5368 _type = self._file_store_meta_value_type.split('.')[0]
5368 5369 # decode the encrypted value if it's encrypted field type
5369 5370 if '.encrypted' in self._file_store_meta_value_type:
5370 5371 cipher = EncryptedTextValue()
5371 5372 val = safe_unicode(cipher.process_result_value(val, None))
5372 5373 # do final type conversion
5373 5374 converter = self.SETTINGS_TYPES.get(_type) or self.SETTINGS_TYPES['unicode']
5374 5375 val = converter(val)
5375 5376
5376 5377 return val
5377 5378
5378 5379 @file_store_meta_value.setter
5379 5380 def file_store_meta_value(self, val):
5380 5381 val = safe_unicode(val)
5381 5382 # encode the encrypted value
5382 5383 if '.encrypted' in self.file_store_meta_value_type:
5383 5384 cipher = EncryptedTextValue()
5384 5385 val = safe_unicode(cipher.process_bind_param(val, None))
5385 5386 self._file_store_meta_value = val
5386 5387
5387 5388 @hybrid_property
5388 5389 def file_store_meta_value_type(self):
5389 5390 return self._file_store_meta_value_type
5390 5391
5391 5392 @file_store_meta_value_type.setter
5392 5393 def file_store_meta_value_type(self, val):
5393 5394 # e.g unicode.encrypted
5394 5395 self.valid_value_type(val)
5395 5396 self._file_store_meta_value_type = val
5396 5397
5397 5398 def __json__(self):
5398 5399 data = {
5399 5400 'artifact': self.file_store.file_uid,
5400 5401 'section': self.file_store_meta_section,
5401 5402 'key': self.file_store_meta_key,
5402 5403 'value': self.file_store_meta_value,
5403 5404 }
5404 5405
5405 5406 return data
5406 5407
5407 5408 def __repr__(self):
5408 5409 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.file_store_meta_section,
5409 5410 self.file_store_meta_key, self.file_store_meta_value)
5410 5411
5411 5412
5412 5413 class DbMigrateVersion(Base, BaseModel):
5413 5414 __tablename__ = 'db_migrate_version'
5414 5415 __table_args__ = (
5415 5416 base_table_args,
5416 5417 )
5417 5418
5418 5419 repository_id = Column('repository_id', String(250), primary_key=True)
5419 5420 repository_path = Column('repository_path', Text)
5420 5421 version = Column('version', Integer)
5421 5422
5422 5423 @classmethod
5423 5424 def set_version(cls, version):
5424 5425 """
5425 5426 Helper for forcing a different version, usually for debugging purposes via ishell.
5426 5427 """
5427 5428 ver = DbMigrateVersion.query().first()
5428 5429 ver.version = version
5429 5430 Session().commit()
5430 5431
5431 5432
5432 5433 class DbSession(Base, BaseModel):
5433 5434 __tablename__ = 'db_session'
5434 5435 __table_args__ = (
5435 5436 base_table_args,
5436 5437 )
5437 5438
5438 5439 def __repr__(self):
5439 5440 return '<DB:DbSession({})>'.format(self.id)
5440 5441
5441 5442 id = Column('id', Integer())
5442 5443 namespace = Column('namespace', String(255), primary_key=True)
5443 5444 accessed = Column('accessed', DateTime, nullable=False)
5444 5445 created = Column('created', DateTime, nullable=False)
5445 5446 data = Column('data', PickleType, nullable=False)
@@ -1,1003 +1,1005 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 users model for RhodeCode
23 23 """
24 24
25 25 import logging
26 26 import traceback
27 27 import datetime
28 28 import ipaddress
29 29
30 30 from pyramid.threadlocal import get_current_request
31 31 from sqlalchemy.exc import DatabaseError
32 32
33 33 from rhodecode import events
34 34 from rhodecode.lib.user_log_filter import user_log_filter
35 35 from rhodecode.lib.utils2 import (
36 36 safe_unicode, get_current_rhodecode_user, action_logger_generic,
37 37 AttributeDict, str2bool)
38 38 from rhodecode.lib.exceptions import (
39 39 DefaultUserException, UserOwnsReposException, UserOwnsRepoGroupsException,
40 40 UserOwnsUserGroupsException, NotAllowedToCreateUserError, UserOwnsArtifactsException)
41 41 from rhodecode.lib.caching_query import FromCache
42 42 from rhodecode.model import BaseModel
43 43 from rhodecode.model.auth_token import AuthTokenModel
44 44 from rhodecode.model.db import (
45 45 _hash_key, true, false, or_, joinedload, User, UserToPerm,
46 46 UserEmailMap, UserIpMap, UserLog)
47 47 from rhodecode.model.meta import Session
48 48 from rhodecode.model.repo_group import RepoGroupModel
49 49
50 50
51 51 log = logging.getLogger(__name__)
52 52
53 53
54 54 class UserModel(BaseModel):
55 55 cls = User
56 56
57 57 def get(self, user_id, cache=False):
58 58 user = self.sa.query(User)
59 59 if cache:
60 60 user = user.options(
61 61 FromCache("sql_cache_short", "get_user_%s" % user_id))
62 62 return user.get(user_id)
63 63
64 64 def get_user(self, user):
65 65 return self._get_user(user)
66 66
67 67 def _serialize_user(self, user):
68 68 import rhodecode.lib.helpers as h
69 69
70 70 return {
71 71 'id': user.user_id,
72 72 'first_name': user.first_name,
73 73 'last_name': user.last_name,
74 74 'username': user.username,
75 75 'email': user.email,
76 76 'icon_link': h.gravatar_url(user.email, 30),
77 77 'profile_link': h.link_to_user(user),
78 78 'value_display': h.escape(h.person(user)),
79 79 'value': user.username,
80 80 'value_type': 'user',
81 81 'active': user.active,
82 82 }
83 83
84 84 def get_users(self, name_contains=None, limit=20, only_active=True):
85 85
86 86 query = self.sa.query(User)
87 87 if only_active:
88 88 query = query.filter(User.active == true())
89 89
90 90 if name_contains:
91 91 ilike_expression = u'%{}%'.format(safe_unicode(name_contains))
92 92 query = query.filter(
93 93 or_(
94 94 User.name.ilike(ilike_expression),
95 95 User.lastname.ilike(ilike_expression),
96 96 User.username.ilike(ilike_expression)
97 97 )
98 98 )
99 99 query = query.limit(limit)
100 100 users = query.all()
101 101
102 102 _users = [
103 103 self._serialize_user(user) for user in users
104 104 ]
105 105 return _users
106 106
107 107 def get_by_username(self, username, cache=False, case_insensitive=False):
108 108
109 109 if case_insensitive:
110 110 user = self.sa.query(User).filter(User.username.ilike(username))
111 111 else:
112 112 user = self.sa.query(User)\
113 113 .filter(User.username == username)
114 114 if cache:
115 115 name_key = _hash_key(username)
116 116 user = user.options(
117 117 FromCache("sql_cache_short", "get_user_%s" % name_key))
118 118 return user.scalar()
119 119
120 120 def get_by_email(self, email, cache=False, case_insensitive=False):
121 121 return User.get_by_email(email, case_insensitive, cache)
122 122
123 123 def get_by_auth_token(self, auth_token, cache=False):
124 124 return User.get_by_auth_token(auth_token, cache)
125 125
126 126 def get_active_user_count(self, cache=False):
127 127 qry = User.query().filter(
128 128 User.active == true()).filter(
129 129 User.username != User.DEFAULT_USER)
130 130 if cache:
131 131 qry = qry.options(
132 132 FromCache("sql_cache_short", "get_active_users"))
133 133 return qry.count()
134 134
135 135 def create(self, form_data, cur_user=None):
136 136 if not cur_user:
137 137 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
138 138
139 139 user_data = {
140 140 'username': form_data['username'],
141 141 'password': form_data['password'],
142 142 'email': form_data['email'],
143 143 'firstname': form_data['firstname'],
144 144 'lastname': form_data['lastname'],
145 145 'active': form_data['active'],
146 146 'extern_type': form_data['extern_type'],
147 147 'extern_name': form_data['extern_name'],
148 148 'admin': False,
149 149 'cur_user': cur_user
150 150 }
151 151
152 152 if 'create_repo_group' in form_data:
153 153 user_data['create_repo_group'] = str2bool(
154 154 form_data.get('create_repo_group'))
155 155
156 156 try:
157 157 if form_data.get('password_change'):
158 158 user_data['force_password_change'] = True
159 159 return UserModel().create_or_update(**user_data)
160 160 except Exception:
161 161 log.error(traceback.format_exc())
162 162 raise
163 163
164 164 def update_user(self, user, skip_attrs=None, **kwargs):
165 165 from rhodecode.lib.auth import get_crypt_password
166 166
167 167 user = self._get_user(user)
168 168 if user.username == User.DEFAULT_USER:
169 169 raise DefaultUserException(
170 170 "You can't edit this user (`%(username)s`) since it's "
171 171 "crucial for entire application" % {
172 172 'username': user.username})
173 173
174 174 # first store only defaults
175 175 user_attrs = {
176 176 'updating_user_id': user.user_id,
177 177 'username': user.username,
178 178 'password': user.password,
179 179 'email': user.email,
180 180 'firstname': user.name,
181 181 'lastname': user.lastname,
182 182 'description': user.description,
183 183 'active': user.active,
184 184 'admin': user.admin,
185 185 'extern_name': user.extern_name,
186 186 'extern_type': user.extern_type,
187 187 'language': user.user_data.get('language')
188 188 }
189 189
190 190 # in case there's new_password, that comes from form, use it to
191 191 # store password
192 192 if kwargs.get('new_password'):
193 193 kwargs['password'] = kwargs['new_password']
194 194
195 195 # cleanups, my_account password change form
196 196 kwargs.pop('current_password', None)
197 197 kwargs.pop('new_password', None)
198 198
199 199 # cleanups, user edit password change form
200 200 kwargs.pop('password_confirmation', None)
201 201 kwargs.pop('password_change', None)
202 202
203 203 # create repo group on user creation
204 204 kwargs.pop('create_repo_group', None)
205 205
206 206 # legacy forms send name, which is the firstname
207 207 firstname = kwargs.pop('name', None)
208 208 if firstname:
209 209 kwargs['firstname'] = firstname
210 210
211 211 for k, v in kwargs.items():
212 212 # skip if we don't want to update this
213 213 if skip_attrs and k in skip_attrs:
214 214 continue
215 215
216 216 user_attrs[k] = v
217 217
218 218 try:
219 219 return self.create_or_update(**user_attrs)
220 220 except Exception:
221 221 log.error(traceback.format_exc())
222 222 raise
223 223
224 224 def create_or_update(
225 225 self, username, password, email, firstname='', lastname='',
226 226 active=True, admin=False, extern_type=None, extern_name=None,
227 227 cur_user=None, plugin=None, force_password_change=False,
228 228 allow_to_create_user=True, create_repo_group=None,
229 updating_user_id=None, language=None, description=None,
229 updating_user_id=None, language=None, description='',
230 230 strict_creation_check=True):
231 231 """
232 232 Creates a new instance if not found, or updates current one
233 233
234 234 :param username:
235 235 :param password:
236 236 :param email:
237 237 :param firstname:
238 238 :param lastname:
239 239 :param active:
240 240 :param admin:
241 241 :param extern_type:
242 242 :param extern_name:
243 243 :param cur_user:
244 244 :param plugin: optional plugin this method was called from
245 245 :param force_password_change: toggles new or existing user flag
246 246 for password change
247 247 :param allow_to_create_user: Defines if the method can actually create
248 248 new users
249 249 :param create_repo_group: Defines if the method should also
250 250 create an repo group with user name, and owner
251 251 :param updating_user_id: if we set it up this is the user we want to
252 252 update this allows to editing username.
253 253 :param language: language of user from interface.
254 :param description: user description
255 :param strict_creation_check: checks for allowed creation license wise etc.
254 256
255 257 :returns: new User object with injected `is_new_user` attribute.
256 258 """
257 259
258 260 if not cur_user:
259 261 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
260 262
261 263 from rhodecode.lib.auth import (
262 264 get_crypt_password, check_password, generate_auth_token)
263 265 from rhodecode.lib.hooks_base import (
264 266 log_create_user, check_allowed_create_user)
265 267
266 268 def _password_change(new_user, password):
267 269 old_password = new_user.password or ''
268 270 # empty password
269 271 if not old_password:
270 272 return False
271 273
272 274 # password check is only needed for RhodeCode internal auth calls
273 275 # in case it's a plugin we don't care
274 276 if not plugin:
275 277
276 278 # first check if we gave crypted password back, and if it
277 279 # matches it's not password change
278 280 if new_user.password == password:
279 281 return False
280 282
281 283 password_match = check_password(password, old_password)
282 284 if not password_match:
283 285 return True
284 286
285 287 return False
286 288
287 289 # read settings on default personal repo group creation
288 290 if create_repo_group is None:
289 291 default_create_repo_group = RepoGroupModel()\
290 292 .get_default_create_personal_repo_group()
291 293 create_repo_group = default_create_repo_group
292 294
293 295 user_data = {
294 296 'username': username,
295 297 'password': password,
296 298 'email': email,
297 299 'firstname': firstname,
298 300 'lastname': lastname,
299 301 'active': active,
300 302 'admin': admin
301 303 }
302 304
303 305 if updating_user_id:
304 306 log.debug('Checking for existing account in RhodeCode '
305 307 'database with user_id `%s` ', updating_user_id)
306 308 user = User.get(updating_user_id)
307 309 else:
308 310 log.debug('Checking for existing account in RhodeCode '
309 311 'database with username `%s` ', username)
310 312 user = User.get_by_username(username, case_insensitive=True)
311 313
312 314 if user is None:
313 315 # we check internal flag if this method is actually allowed to
314 316 # create new user
315 317 if not allow_to_create_user:
316 318 msg = ('Method wants to create new user, but it is not '
317 319 'allowed to do so')
318 320 log.warning(msg)
319 321 raise NotAllowedToCreateUserError(msg)
320 322
321 323 log.debug('Creating new user %s', username)
322 324
323 325 # only if we create user that is active
324 326 new_active_user = active
325 327 if new_active_user and strict_creation_check:
326 328 # raises UserCreationError if it's not allowed for any reason to
327 329 # create new active user, this also executes pre-create hooks
328 330 check_allowed_create_user(user_data, cur_user, strict_check=True)
329 331 events.trigger(events.UserPreCreate(user_data))
330 332 new_user = User()
331 333 edit = False
332 334 else:
333 335 log.debug('updating user `%s`', username)
334 336 events.trigger(events.UserPreUpdate(user, user_data))
335 337 new_user = user
336 338 edit = True
337 339
338 340 # we're not allowed to edit default user
339 341 if user.username == User.DEFAULT_USER:
340 342 raise DefaultUserException(
341 343 "You can't edit this user (`%(username)s`) since it's "
342 344 "crucial for entire application"
343 345 % {'username': user.username})
344 346
345 347 # inject special attribute that will tell us if User is new or old
346 348 new_user.is_new_user = not edit
347 349 # for users that didn's specify auth type, we use RhodeCode built in
348 350 from rhodecode.authentication.plugins import auth_rhodecode
349 351 extern_name = extern_name or auth_rhodecode.RhodeCodeAuthPlugin.uid
350 352 extern_type = extern_type or auth_rhodecode.RhodeCodeAuthPlugin.uid
351 353
352 354 try:
353 355 new_user.username = username
354 356 new_user.admin = admin
355 357 new_user.email = email
356 358 new_user.active = active
357 359 new_user.extern_name = safe_unicode(extern_name)
358 360 new_user.extern_type = safe_unicode(extern_type)
359 361 new_user.name = firstname
360 362 new_user.lastname = lastname
361 363 new_user.description = description
362 364
363 365 # set password only if creating an user or password is changed
364 366 if not edit or _password_change(new_user, password):
365 367 reason = 'new password' if edit else 'new user'
366 368 log.debug('Updating password reason=>%s', reason)
367 369 new_user.password = get_crypt_password(password) if password else None
368 370
369 371 if force_password_change:
370 372 new_user.update_userdata(force_password_change=True)
371 373 if language:
372 374 new_user.update_userdata(language=language)
373 375 new_user.update_userdata(notification_status=True)
374 376
375 377 self.sa.add(new_user)
376 378
377 379 if not edit and create_repo_group:
378 380 RepoGroupModel().create_personal_repo_group(
379 381 new_user, commit_early=False)
380 382
381 383 if not edit:
382 384 # add the RSS token
383 385 self.add_auth_token(
384 386 user=username, lifetime_minutes=-1,
385 387 role=self.auth_token_role.ROLE_FEED,
386 388 description=u'Generated feed token')
387 389
388 390 kwargs = new_user.get_dict()
389 391 # backward compat, require api_keys present
390 392 kwargs['api_keys'] = kwargs['auth_tokens']
391 393 log_create_user(created_by=cur_user, **kwargs)
392 394 events.trigger(events.UserPostCreate(user_data))
393 395 return new_user
394 396 except (DatabaseError,):
395 397 log.error(traceback.format_exc())
396 398 raise
397 399
398 400 def create_registration(self, form_data,
399 401 extern_name='rhodecode', extern_type='rhodecode'):
400 402 from rhodecode.model.notification import NotificationModel
401 403 from rhodecode.model.notification import EmailNotificationModel
402 404
403 405 try:
404 406 form_data['admin'] = False
405 407 form_data['extern_name'] = extern_name
406 408 form_data['extern_type'] = extern_type
407 409 new_user = self.create(form_data)
408 410
409 411 self.sa.add(new_user)
410 412 self.sa.flush()
411 413
412 414 user_data = new_user.get_dict()
413 415 kwargs = {
414 416 # use SQLALCHEMY safe dump of user data
415 417 'user': AttributeDict(user_data),
416 418 'date': datetime.datetime.now()
417 419 }
418 420 notification_type = EmailNotificationModel.TYPE_REGISTRATION
419 421 # pre-generate the subject for notification itself
420 422 (subject,
421 423 _h, _e, # we don't care about those
422 424 body_plaintext) = EmailNotificationModel().render_email(
423 425 notification_type, **kwargs)
424 426
425 427 # create notification objects, and emails
426 428 NotificationModel().create(
427 429 created_by=new_user,
428 430 notification_subject=subject,
429 431 notification_body=body_plaintext,
430 432 notification_type=notification_type,
431 433 recipients=None, # all admins
432 434 email_kwargs=kwargs,
433 435 )
434 436
435 437 return new_user
436 438 except Exception:
437 439 log.error(traceback.format_exc())
438 440 raise
439 441
440 442 def _handle_user_repos(self, username, repositories, handle_mode=None):
441 443 _superadmin = self.cls.get_first_super_admin()
442 444 left_overs = True
443 445
444 446 from rhodecode.model.repo import RepoModel
445 447
446 448 if handle_mode == 'detach':
447 449 for obj in repositories:
448 450 obj.user = _superadmin
449 451 # set description we know why we super admin now owns
450 452 # additional repositories that were orphaned !
451 453 obj.description += ' \n::detached repository from deleted user: %s' % (username,)
452 454 self.sa.add(obj)
453 455 left_overs = False
454 456 elif handle_mode == 'delete':
455 457 for obj in repositories:
456 458 RepoModel().delete(obj, forks='detach')
457 459 left_overs = False
458 460
459 461 # if nothing is done we have left overs left
460 462 return left_overs
461 463
462 464 def _handle_user_repo_groups(self, username, repository_groups,
463 465 handle_mode=None):
464 466 _superadmin = self.cls.get_first_super_admin()
465 467 left_overs = True
466 468
467 469 from rhodecode.model.repo_group import RepoGroupModel
468 470
469 471 if handle_mode == 'detach':
470 472 for r in repository_groups:
471 473 r.user = _superadmin
472 474 # set description we know why we super admin now owns
473 475 # additional repositories that were orphaned !
474 476 r.group_description += ' \n::detached repository group from deleted user: %s' % (username,)
475 477 r.personal = False
476 478 self.sa.add(r)
477 479 left_overs = False
478 480 elif handle_mode == 'delete':
479 481 for r in repository_groups:
480 482 RepoGroupModel().delete(r)
481 483 left_overs = False
482 484
483 485 # if nothing is done we have left overs left
484 486 return left_overs
485 487
486 488 def _handle_user_user_groups(self, username, user_groups, handle_mode=None):
487 489 _superadmin = self.cls.get_first_super_admin()
488 490 left_overs = True
489 491
490 492 from rhodecode.model.user_group import UserGroupModel
491 493
492 494 if handle_mode == 'detach':
493 495 for r in user_groups:
494 496 for user_user_group_to_perm in r.user_user_group_to_perm:
495 497 if user_user_group_to_perm.user.username == username:
496 498 user_user_group_to_perm.user = _superadmin
497 499 r.user = _superadmin
498 500 # set description we know why we super admin now owns
499 501 # additional repositories that were orphaned !
500 502 r.user_group_description += ' \n::detached user group from deleted user: %s' % (username,)
501 503 self.sa.add(r)
502 504 left_overs = False
503 505 elif handle_mode == 'delete':
504 506 for r in user_groups:
505 507 UserGroupModel().delete(r)
506 508 left_overs = False
507 509
508 510 # if nothing is done we have left overs left
509 511 return left_overs
510 512
511 513 def _handle_user_artifacts(self, username, artifacts, handle_mode=None):
512 514 _superadmin = self.cls.get_first_super_admin()
513 515 left_overs = True
514 516
515 517 if handle_mode == 'detach':
516 518 for a in artifacts:
517 519 a.upload_user = _superadmin
518 520 # set description we know why we super admin now owns
519 521 # additional artifacts that were orphaned !
520 522 a.file_description += ' \n::detached artifact from deleted user: %s' % (username,)
521 523 self.sa.add(a)
522 524 left_overs = False
523 525 elif handle_mode == 'delete':
524 526 from rhodecode.apps.file_store import utils as store_utils
525 527 storage = store_utils.get_file_storage(self.request.registry.settings)
526 528 for a in artifacts:
527 529 file_uid = a.file_uid
528 530 storage.delete(file_uid)
529 531 self.sa.delete(a)
530 532
531 533 left_overs = False
532 534
533 535 # if nothing is done we have left overs left
534 536 return left_overs
535 537
536 538 def delete(self, user, cur_user=None, handle_repos=None,
537 539 handle_repo_groups=None, handle_user_groups=None, handle_artifacts=None):
538 540 from rhodecode.lib.hooks_base import log_delete_user
539 541
540 542 if not cur_user:
541 543 cur_user = getattr(get_current_rhodecode_user(), 'username', None)
542 544 user = self._get_user(user)
543 545
544 546 try:
545 547 if user.username == User.DEFAULT_USER:
546 548 raise DefaultUserException(
547 549 u"You can't remove this user since it's"
548 550 u" crucial for entire application")
549 551
550 552 left_overs = self._handle_user_repos(
551 553 user.username, user.repositories, handle_repos)
552 554 if left_overs and user.repositories:
553 555 repos = [x.repo_name for x in user.repositories]
554 556 raise UserOwnsReposException(
555 557 u'user "%(username)s" still owns %(len_repos)s repositories and cannot be '
556 558 u'removed. Switch owners or remove those repositories:%(list_repos)s'
557 559 % {'username': user.username, 'len_repos': len(repos),
558 560 'list_repos': ', '.join(repos)})
559 561
560 562 left_overs = self._handle_user_repo_groups(
561 563 user.username, user.repository_groups, handle_repo_groups)
562 564 if left_overs and user.repository_groups:
563 565 repo_groups = [x.group_name for x in user.repository_groups]
564 566 raise UserOwnsRepoGroupsException(
565 567 u'user "%(username)s" still owns %(len_repo_groups)s repository groups and cannot be '
566 568 u'removed. Switch owners or remove those repository groups:%(list_repo_groups)s'
567 569 % {'username': user.username, 'len_repo_groups': len(repo_groups),
568 570 'list_repo_groups': ', '.join(repo_groups)})
569 571
570 572 left_overs = self._handle_user_user_groups(
571 573 user.username, user.user_groups, handle_user_groups)
572 574 if left_overs and user.user_groups:
573 575 user_groups = [x.users_group_name for x in user.user_groups]
574 576 raise UserOwnsUserGroupsException(
575 577 u'user "%s" still owns %s user groups and cannot be '
576 578 u'removed. Switch owners or remove those user groups:%s'
577 579 % (user.username, len(user_groups), ', '.join(user_groups)))
578 580
579 581 left_overs = self._handle_user_artifacts(
580 582 user.username, user.artifacts, handle_artifacts)
581 583 if left_overs and user.artifacts:
582 584 artifacts = [x.file_uid for x in user.artifacts]
583 585 raise UserOwnsArtifactsException(
584 586 u'user "%s" still owns %s artifacts and cannot be '
585 587 u'removed. Switch owners or remove those artifacts:%s'
586 588 % (user.username, len(artifacts), ', '.join(artifacts)))
587 589
588 590 user_data = user.get_dict() # fetch user data before expire
589 591
590 592 # we might change the user data with detach/delete, make sure
591 593 # the object is marked as expired before actually deleting !
592 594 self.sa.expire(user)
593 595 self.sa.delete(user)
594 596
595 597 log_delete_user(deleted_by=cur_user, **user_data)
596 598 except Exception:
597 599 log.error(traceback.format_exc())
598 600 raise
599 601
600 602 def reset_password_link(self, data, pwd_reset_url):
601 603 from rhodecode.lib.celerylib import tasks, run_task
602 604 from rhodecode.model.notification import EmailNotificationModel
603 605 user_email = data['email']
604 606 try:
605 607 user = User.get_by_email(user_email)
606 608 if user:
607 609 log.debug('password reset user found %s', user)
608 610
609 611 email_kwargs = {
610 612 'password_reset_url': pwd_reset_url,
611 613 'user': user,
612 614 'email': user_email,
613 615 'date': datetime.datetime.now()
614 616 }
615 617
616 618 (subject, headers, email_body,
617 619 email_body_plaintext) = EmailNotificationModel().render_email(
618 620 EmailNotificationModel.TYPE_PASSWORD_RESET, **email_kwargs)
619 621
620 622 recipients = [user_email]
621 623
622 624 action_logger_generic(
623 625 'sending password reset email to user: {}'.format(
624 626 user), namespace='security.password_reset')
625 627
626 628 run_task(tasks.send_email, recipients, subject,
627 629 email_body_plaintext, email_body)
628 630
629 631 else:
630 632 log.debug("password reset email %s not found", user_email)
631 633 except Exception:
632 634 log.error(traceback.format_exc())
633 635 return False
634 636
635 637 return True
636 638
637 639 def reset_password(self, data):
638 640 from rhodecode.lib.celerylib import tasks, run_task
639 641 from rhodecode.model.notification import EmailNotificationModel
640 642 from rhodecode.lib import auth
641 643 user_email = data['email']
642 644 pre_db = True
643 645 try:
644 646 user = User.get_by_email(user_email)
645 647 new_passwd = auth.PasswordGenerator().gen_password(
646 648 12, auth.PasswordGenerator.ALPHABETS_BIG_SMALL)
647 649 if user:
648 650 user.password = auth.get_crypt_password(new_passwd)
649 651 # also force this user to reset his password !
650 652 user.update_userdata(force_password_change=True)
651 653
652 654 Session().add(user)
653 655
654 656 # now delete the token in question
655 657 UserApiKeys = AuthTokenModel.cls
656 658 UserApiKeys().query().filter(
657 659 UserApiKeys.api_key == data['token']).delete()
658 660
659 661 Session().commit()
660 662 log.info('successfully reset password for `%s`', user_email)
661 663
662 664 if new_passwd is None:
663 665 raise Exception('unable to generate new password')
664 666
665 667 pre_db = False
666 668
667 669 email_kwargs = {
668 670 'new_password': new_passwd,
669 671 'user': user,
670 672 'email': user_email,
671 673 'date': datetime.datetime.now()
672 674 }
673 675
674 676 (subject, headers, email_body,
675 677 email_body_plaintext) = EmailNotificationModel().render_email(
676 678 EmailNotificationModel.TYPE_PASSWORD_RESET_CONFIRMATION,
677 679 **email_kwargs)
678 680
679 681 recipients = [user_email]
680 682
681 683 action_logger_generic(
682 684 'sent new password to user: {} with email: {}'.format(
683 685 user, user_email), namespace='security.password_reset')
684 686
685 687 run_task(tasks.send_email, recipients, subject,
686 688 email_body_plaintext, email_body)
687 689
688 690 except Exception:
689 691 log.error('Failed to update user password')
690 692 log.error(traceback.format_exc())
691 693 if pre_db:
692 694 # we rollback only if local db stuff fails. If it goes into
693 695 # run_task, we're pass rollback state this wouldn't work then
694 696 Session().rollback()
695 697
696 698 return True
697 699
698 700 def fill_data(self, auth_user, user_id=None, api_key=None, username=None):
699 701 """
700 702 Fetches auth_user by user_id,or api_key if present.
701 703 Fills auth_user attributes with those taken from database.
702 704 Additionally set's is_authenitated if lookup fails
703 705 present in database
704 706
705 707 :param auth_user: instance of user to set attributes
706 708 :param user_id: user id to fetch by
707 709 :param api_key: api key to fetch by
708 710 :param username: username to fetch by
709 711 """
710 712 def token_obfuscate(token):
711 713 if token:
712 714 return token[:4] + "****"
713 715
714 716 if user_id is None and api_key is None and username is None:
715 717 raise Exception('You need to pass user_id, api_key or username')
716 718
717 719 log.debug(
718 720 'AuthUser: fill data execution based on: '
719 721 'user_id:%s api_key:%s username:%s', user_id, api_key, username)
720 722 try:
721 723 dbuser = None
722 724 if user_id:
723 725 dbuser = self.get(user_id)
724 726 elif api_key:
725 727 dbuser = self.get_by_auth_token(api_key)
726 728 elif username:
727 729 dbuser = self.get_by_username(username)
728 730
729 731 if not dbuser:
730 732 log.warning(
731 733 'Unable to lookup user by id:%s api_key:%s username:%s',
732 734 user_id, token_obfuscate(api_key), username)
733 735 return False
734 736 if not dbuser.active:
735 737 log.debug('User `%s:%s` is inactive, skipping fill data',
736 738 username, user_id)
737 739 return False
738 740
739 741 log.debug('AuthUser: filling found user:%s data', dbuser)
740 742
741 743 attrs = {
742 744 'user_id': dbuser.user_id,
743 745 'username': dbuser.username,
744 746 'name': dbuser.name,
745 747 'first_name': dbuser.first_name,
746 748 'firstname': dbuser.firstname,
747 749 'last_name': dbuser.last_name,
748 750 'lastname': dbuser.lastname,
749 751 'admin': dbuser.admin,
750 752 'active': dbuser.active,
751 753
752 754 'email': dbuser.email,
753 755 'emails': dbuser.emails_cached(),
754 756 'short_contact': dbuser.short_contact,
755 757 'full_contact': dbuser.full_contact,
756 758 'full_name': dbuser.full_name,
757 759 'full_name_or_username': dbuser.full_name_or_username,
758 760
759 761 '_api_key': dbuser._api_key,
760 762 '_user_data': dbuser._user_data,
761 763
762 764 'created_on': dbuser.created_on,
763 765 'extern_name': dbuser.extern_name,
764 766 'extern_type': dbuser.extern_type,
765 767
766 768 'inherit_default_permissions': dbuser.inherit_default_permissions,
767 769
768 770 'language': dbuser.language,
769 771 'last_activity': dbuser.last_activity,
770 772 'last_login': dbuser.last_login,
771 773 'password': dbuser.password,
772 774 }
773 775 auth_user.__dict__.update(attrs)
774 776 except Exception:
775 777 log.error(traceback.format_exc())
776 778 auth_user.is_authenticated = False
777 779 return False
778 780
779 781 return True
780 782
781 783 def has_perm(self, user, perm):
782 784 perm = self._get_perm(perm)
783 785 user = self._get_user(user)
784 786
785 787 return UserToPerm.query().filter(UserToPerm.user == user)\
786 788 .filter(UserToPerm.permission == perm).scalar() is not None
787 789
788 790 def grant_perm(self, user, perm):
789 791 """
790 792 Grant user global permissions
791 793
792 794 :param user:
793 795 :param perm:
794 796 """
795 797 user = self._get_user(user)
796 798 perm = self._get_perm(perm)
797 799 # if this permission is already granted skip it
798 800 _perm = UserToPerm.query()\
799 801 .filter(UserToPerm.user == user)\
800 802 .filter(UserToPerm.permission == perm)\
801 803 .scalar()
802 804 if _perm:
803 805 return
804 806 new = UserToPerm()
805 807 new.user = user
806 808 new.permission = perm
807 809 self.sa.add(new)
808 810 return new
809 811
810 812 def revoke_perm(self, user, perm):
811 813 """
812 814 Revoke users global permissions
813 815
814 816 :param user:
815 817 :param perm:
816 818 """
817 819 user = self._get_user(user)
818 820 perm = self._get_perm(perm)
819 821
820 822 obj = UserToPerm.query()\
821 823 .filter(UserToPerm.user == user)\
822 824 .filter(UserToPerm.permission == perm)\
823 825 .scalar()
824 826 if obj:
825 827 self.sa.delete(obj)
826 828
827 829 def add_extra_email(self, user, email):
828 830 """
829 831 Adds email address to UserEmailMap
830 832
831 833 :param user:
832 834 :param email:
833 835 """
834 836
835 837 user = self._get_user(user)
836 838
837 839 obj = UserEmailMap()
838 840 obj.user = user
839 841 obj.email = email
840 842 self.sa.add(obj)
841 843 return obj
842 844
843 845 def delete_extra_email(self, user, email_id):
844 846 """
845 847 Removes email address from UserEmailMap
846 848
847 849 :param user:
848 850 :param email_id:
849 851 """
850 852 user = self._get_user(user)
851 853 obj = UserEmailMap.query().get(email_id)
852 854 if obj and obj.user_id == user.user_id:
853 855 self.sa.delete(obj)
854 856
855 857 def parse_ip_range(self, ip_range):
856 858 ip_list = []
857 859
858 860 def make_unique(value):
859 861 seen = []
860 862 return [c for c in value if not (c in seen or seen.append(c))]
861 863
862 864 # firsts split by commas
863 865 for ip_range in ip_range.split(','):
864 866 if not ip_range:
865 867 continue
866 868 ip_range = ip_range.strip()
867 869 if '-' in ip_range:
868 870 start_ip, end_ip = ip_range.split('-', 1)
869 871 start_ip = ipaddress.ip_address(safe_unicode(start_ip.strip()))
870 872 end_ip = ipaddress.ip_address(safe_unicode(end_ip.strip()))
871 873 parsed_ip_range = []
872 874
873 875 for index in xrange(int(start_ip), int(end_ip) + 1):
874 876 new_ip = ipaddress.ip_address(index)
875 877 parsed_ip_range.append(str(new_ip))
876 878 ip_list.extend(parsed_ip_range)
877 879 else:
878 880 ip_list.append(ip_range)
879 881
880 882 return make_unique(ip_list)
881 883
882 884 def add_extra_ip(self, user, ip, description=None):
883 885 """
884 886 Adds ip address to UserIpMap
885 887
886 888 :param user:
887 889 :param ip:
888 890 """
889 891
890 892 user = self._get_user(user)
891 893 obj = UserIpMap()
892 894 obj.user = user
893 895 obj.ip_addr = ip
894 896 obj.description = description
895 897 self.sa.add(obj)
896 898 return obj
897 899
898 900 auth_token_role = AuthTokenModel.cls
899 901
900 902 def add_auth_token(self, user, lifetime_minutes, role, description=u'',
901 903 scope_callback=None):
902 904 """
903 905 Add AuthToken for user.
904 906
905 907 :param user: username/user_id
906 908 :param lifetime_minutes: in minutes the lifetime for token, -1 equals no limit
907 909 :param role: one of AuthTokenModel.cls.ROLE_*
908 910 :param description: optional string description
909 911 """
910 912
911 913 token = AuthTokenModel().create(
912 914 user, description, lifetime_minutes, role)
913 915 if scope_callback and callable(scope_callback):
914 916 # call the callback if we provide, used to attach scope for EE edition
915 917 scope_callback(token)
916 918 return token
917 919
918 920 def delete_extra_ip(self, user, ip_id):
919 921 """
920 922 Removes ip address from UserIpMap
921 923
922 924 :param user:
923 925 :param ip_id:
924 926 """
925 927 user = self._get_user(user)
926 928 obj = UserIpMap.query().get(ip_id)
927 929 if obj and obj.user_id == user.user_id:
928 930 self.sa.delete(obj)
929 931
930 932 def get_accounts_in_creation_order(self, current_user=None):
931 933 """
932 934 Get accounts in order of creation for deactivation for license limits
933 935
934 936 pick currently logged in user, and append to the list in position 0
935 937 pick all super-admins in order of creation date and add it to the list
936 938 pick all other accounts in order of creation and add it to the list.
937 939
938 940 Based on that list, the last accounts can be disabled as they are
939 941 created at the end and don't include any of the super admins as well
940 942 as the current user.
941 943
942 944 :param current_user: optionally current user running this operation
943 945 """
944 946
945 947 if not current_user:
946 948 current_user = get_current_rhodecode_user()
947 949 active_super_admins = [
948 950 x.user_id for x in User.query()
949 951 .filter(User.user_id != current_user.user_id)
950 952 .filter(User.active == true())
951 953 .filter(User.admin == true())
952 954 .order_by(User.created_on.asc())]
953 955
954 956 active_regular_users = [
955 957 x.user_id for x in User.query()
956 958 .filter(User.user_id != current_user.user_id)
957 959 .filter(User.active == true())
958 960 .filter(User.admin == false())
959 961 .order_by(User.created_on.asc())]
960 962
961 963 list_of_accounts = [current_user.user_id]
962 964 list_of_accounts += active_super_admins
963 965 list_of_accounts += active_regular_users
964 966
965 967 return list_of_accounts
966 968
967 969 def deactivate_last_users(self, expected_users, current_user=None):
968 970 """
969 971 Deactivate accounts that are over the license limits.
970 972 Algorithm of which accounts to disabled is based on the formula:
971 973
972 974 Get current user, then super admins in creation order, then regular
973 975 active users in creation order.
974 976
975 977 Using that list we mark all accounts from the end of it as inactive.
976 978 This way we block only latest created accounts.
977 979
978 980 :param expected_users: list of users in special order, we deactivate
979 981 the end N amount of users from that list
980 982 """
981 983
982 984 list_of_accounts = self.get_accounts_in_creation_order(
983 985 current_user=current_user)
984 986
985 987 for acc_id in list_of_accounts[expected_users + 1:]:
986 988 user = User.get(acc_id)
987 989 log.info('Deactivating account %s for license unlock', user)
988 990 user.active = False
989 991 Session().add(user)
990 992 Session().commit()
991 993
992 994 return
993 995
994 996 def get_user_log(self, user, filter_term):
995 997 user_log = UserLog.query()\
996 998 .filter(or_(UserLog.user_id == user.user_id,
997 999 UserLog.username == user.username))\
998 1000 .options(joinedload(UserLog.user))\
999 1001 .options(joinedload(UserLog.repository))\
1000 1002 .order_by(UserLog.action_date.desc())
1001 1003
1002 1004 user_log = user_log_filter(user_log, filter_term)
1003 1005 return user_log
@@ -1,195 +1,198 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import re
22 22 import colander
23 23
24 24 from rhodecode import forms
25 25 from rhodecode.model.db import User, UserEmailMap
26 26 from rhodecode.model.validation_schema import types, validators
27 27 from rhodecode.translation import _
28 28 from rhodecode.lib.auth import check_password
29 29 from rhodecode.lib import helpers as h
30 30
31 31
32 32 @colander.deferred
33 33 def deferred_user_password_validator(node, kw):
34 34 username = kw.get('username')
35 35 user = User.get_by_username(username)
36 36
37 37 def _user_password_validator(node, value):
38 38 if not check_password(value, user.password):
39 39 msg = _('Password is incorrect')
40 40 raise colander.Invalid(node, msg)
41 41 return _user_password_validator
42 42
43 43
44 44
45 45 class ChangePasswordSchema(colander.Schema):
46 46
47 47 current_password = colander.SchemaNode(
48 48 colander.String(),
49 49 missing=colander.required,
50 50 widget=forms.widget.PasswordWidget(redisplay=True),
51 51 validator=deferred_user_password_validator)
52 52
53 53 new_password = colander.SchemaNode(
54 54 colander.String(),
55 55 missing=colander.required,
56 56 widget=forms.widget.CheckedPasswordWidget(redisplay=True),
57 57 validator=colander.Length(min=6))
58 58
59 59 def validator(self, form, values):
60 60 if values['current_password'] == values['new_password']:
61 61 exc = colander.Invalid(form)
62 62 exc['new_password'] = _('New password must be different '
63 63 'to old password')
64 64 raise exc
65 65
66 66
67 67 @colander.deferred
68 68 def deferred_username_validator(node, kw):
69 69
70 70 def name_validator(node, value):
71 71 msg = _(
72 72 u'Username may only contain alphanumeric characters '
73 73 u'underscores, periods or dashes and must begin with '
74 74 u'alphanumeric character or underscore')
75 75
76 76 if not re.match(r'^[\w]{1}[\w\-\.]{0,254}$', value):
77 77 raise colander.Invalid(node, msg)
78 78
79 79 return name_validator
80 80
81 81
82 82 @colander.deferred
83 83 def deferred_email_validator(node, kw):
84 84 # NOTE(marcink): we might provide uniqueness validation later here...
85 85 return colander.Email()
86 86
87 87
88 88 class UserSchema(colander.Schema):
89 89 username = colander.SchemaNode(
90 90 colander.String(),
91 91 validator=deferred_username_validator)
92 92
93 93 email = colander.SchemaNode(
94 94 colander.String(),
95 95 validator=deferred_email_validator)
96 96
97 97 password = colander.SchemaNode(
98 98 colander.String(), missing='')
99 99
100 100 first_name = colander.SchemaNode(
101 101 colander.String(), missing='')
102 102
103 103 last_name = colander.SchemaNode(
104 104 colander.String(), missing='')
105 105
106 description = colander.SchemaNode(
107 colander.String(), missing='')
108
106 109 active = colander.SchemaNode(
107 110 types.StringBooleanType(),
108 111 missing=False)
109 112
110 113 admin = colander.SchemaNode(
111 114 types.StringBooleanType(),
112 115 missing=False)
113 116
114 117 extern_name = colander.SchemaNode(
115 118 colander.String(), missing='')
116 119
117 120 extern_type = colander.SchemaNode(
118 121 colander.String(), missing='')
119 122
120 123 def deserialize(self, cstruct):
121 124 """
122 125 Custom deserialize that allows to chain validation, and verify
123 126 permissions, and as last step uniqueness
124 127 """
125 128
126 129 appstruct = super(UserSchema, self).deserialize(cstruct)
127 130 return appstruct
128 131
129 132
130 133 @colander.deferred
131 134 def deferred_user_email_in_emails_validator(node, kw):
132 135 return colander.OneOf(kw.get('user_emails'))
133 136
134 137
135 138 @colander.deferred
136 139 def deferred_additional_email_validator(node, kw):
137 140 emails = kw.get('user_emails')
138 141
139 142 def name_validator(node, value):
140 143 if value in emails:
141 144 msg = _('This e-mail address is already taken')
142 145 raise colander.Invalid(node, msg)
143 146 user = User.get_by_email(value, case_insensitive=True)
144 147 if user:
145 148 msg = _(u'This e-mail address is already taken')
146 149 raise colander.Invalid(node, msg)
147 150 c = colander.Email()
148 151 return c(node, value)
149 152 return name_validator
150 153
151 154
152 155 @colander.deferred
153 156 def deferred_user_email_in_emails_widget(node, kw):
154 157 import deform.widget
155 158 emails = [(email, email) for email in kw.get('user_emails')]
156 159 return deform.widget.Select2Widget(values=emails)
157 160
158 161
159 162 class UserProfileSchema(colander.Schema):
160 163 username = colander.SchemaNode(
161 164 colander.String(),
162 165 validator=deferred_username_validator)
163 166
164 167 firstname = colander.SchemaNode(
165 168 colander.String(), missing='', title='First name')
166 169
167 170 lastname = colander.SchemaNode(
168 171 colander.String(), missing='', title='Last name')
169 172
170 173 description = colander.SchemaNode(
171 174 colander.String(), missing='', title='Personal Description',
172 175 widget=forms.widget.TextAreaWidget(),
173 176 validator=colander.Length(max=250)
174 177 )
175 178
176 179 email = colander.SchemaNode(
177 180 colander.String(), widget=deferred_user_email_in_emails_widget,
178 181 validator=deferred_user_email_in_emails_validator,
179 182 description=h.literal(
180 183 _('Additional emails can be specified at <a href="{}">extra emails</a> page.').format(
181 184 '/_admin/my_account/emails')),
182 185 )
183 186
184 187
185 188
186 189 class AddEmailSchema(colander.Schema):
187 190 current_password = colander.SchemaNode(
188 191 colander.String(),
189 192 missing=colander.required,
190 193 widget=forms.widget.PasswordWidget(redisplay=True),
191 194 validator=deferred_user_password_validator)
192 195
193 196 email = colander.SchemaNode(
194 197 colander.String(), title='New Email',
195 198 validator=deferred_additional_email_validator)
@@ -1,155 +1,161 b''
1 1 <%namespace name="base" file="/base/base.mako"/>
2 2
3 3 <div class="panel panel-default user-profile">
4 4 <div class="panel-heading">
5 5 <h3 class="panel-title">${_('User Profile')}</h3>
6 6 </div>
7 7 <div class="panel-body">
8 8 <div class="user-profile-content">
9 9 ${h.secure_form(h.route_path('user_update', user_id=c.user.user_id), class_='form', request=request)}
10 10 <% readonly = None %>
11 11 <% disabled = "" %>
12 12 %if c.extern_type != 'rhodecode':
13 13 <% readonly = "readonly" %>
14 14 <% disabled = " disabled" %>
15 15 <div class="alert-warning" style="margin:0px 0px 20px 0px; padding: 10px">
16 16 <strong>${_('This user was created from external source (%s). Editing some of the settings is limited.' % c.extern_type)}</strong>
17 17 </div>
18 18 %endif
19 19 <div class="form">
20 20 <div class="fields">
21 21 <div class="field">
22 22 <div class="label photo">
23 23 ${_('Photo')}:
24 24 </div>
25 25 <div class="input profile">
26 26 %if c.visual.use_gravatar:
27 27 ${base.gravatar(c.user.email, 100)}
28 28 <p class="help-block">${_('Change the avatar at')} <a href="http://gravatar.com">gravatar.com</a>.</p>
29 29 %else:
30 30 ${base.gravatar(c.user.email, 100)}
31 31 %endif
32 32 </div>
33 33 </div>
34 34 <div class="field">
35 35 <div class="label">
36 36 ${_('Username')}:
37 37 </div>
38 38 <div class="input">
39 39 ${h.text('username', class_='%s medium' % disabled, readonly=readonly)}
40 40 </div>
41 41 </div>
42 42 <div class="field">
43 43 <div class="label">
44 44 <label for="name">${_('First Name')}:</label>
45 45 </div>
46 46 <div class="input">
47 47 ${h.text('firstname', class_="medium")}
48 48 </div>
49 49 </div>
50 50
51 51 <div class="field">
52 52 <div class="label">
53 53 <label for="lastname">${_('Last Name')}:</label>
54 54 </div>
55 55 <div class="input">
56 56 ${h.text('lastname', class_="medium")}
57 57 </div>
58 58 </div>
59 59
60 60 <div class="field">
61 61 <div class="label">
62 62 <label for="email">${_('Email')}:</label>
63 63 </div>
64 64 <div class="input">
65 65 ## we should be able to edit email !
66 66 ${h.text('email', class_="medium")}
67 67 </div>
68 68 </div>
69 69 <div class="field">
70 70 <div class="label">
71 71 <label for="description">${_('Description')}:</label>
72 72 </div>
73 73 <div class="input textarea editor">
74 ${h.textarea('description', class_="medium")}
74 ${h.textarea('description', rows=10, class_="medium")}
75 <% metatags_url = h.literal('''<a href="#metatagsShow" onclick="$('#meta-tags-desc').toggle();return false">meta-tags</a>''') %>
76 <span class="help-block">${_('Plain text format with support of {metatags}. Add a README file for longer descriptions').format(metatags=metatags_url)|n}</span>
77 <span id="meta-tags-desc" style="display: none">
78 <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
79 ${dt.metatags_help()}
80 </span>
75 81 </div>
76 82 </div>
77 83 <div class="field">
78 84 <div class="label">
79 85 ${_('New Password')}:
80 86 </div>
81 87 <div class="input">
82 88 ${h.password('new_password',class_='%s medium' % disabled,autocomplete="off",readonly=readonly)}
83 89 </div>
84 90 </div>
85 91 <div class="field">
86 92 <div class="label">
87 93 ${_('New Password Confirmation')}:
88 94 </div>
89 95 <div class="input">
90 96 ${h.password('password_confirmation',class_="%s medium" % disabled,autocomplete="off",readonly=readonly)}
91 97 </div>
92 98 </div>
93 99 <div class="field">
94 100 <div class="label-text">
95 101 ${_('Active')}:
96 102 </div>
97 103 <div class="input user-checkbox">
98 104 ${h.checkbox('active',value=True)}
99 105 </div>
100 106 </div>
101 107 <div class="field">
102 108 <div class="label-text">
103 109 ${_('Super Admin')}:
104 110 </div>
105 111 <div class="input user-checkbox">
106 112 ${h.checkbox('admin',value=True)}
107 113 </div>
108 114 </div>
109 115 <div class="field">
110 116 <div class="label-text">
111 117 ${_('Authentication type')}:
112 118 </div>
113 119 <div class="input">
114 120 ${h.select('extern_type', c.extern_type, c.allowed_extern_types)}
115 121 <p class="help-block">${_('When user was created using an external source. He is bound to authentication using this method.')}</p>
116 122 </div>
117 123 </div>
118 124 <div class="field">
119 125 <div class="label-text">
120 126 ${_('Name in Source of Record')}:
121 127 </div>
122 128 <div class="input">
123 129 <p>${c.extern_name}</p>
124 130 ${h.hidden('extern_name', readonly="readonly")}
125 131 </div>
126 132 </div>
127 133 <div class="field">
128 134 <div class="label">
129 135 ${_('Language')}:
130 136 </div>
131 137 <div class="input">
132 138 ## allowed_languages is defined in the users.py
133 139 ## c.language comes from base.py as a default language
134 140 ${h.select('language', c.language, c.allowed_languages)}
135 141 <p class="help-block">${h.literal(_('User interface language. Help translate %(rc_link)s into your language.') % {'rc_link': h.link_to('RhodeCode Enterprise', h.route_url('rhodecode_translations'))})}</p>
136 142 </div>
137 143 </div>
138 144 <div class="buttons">
139 145 ${h.submit('save', _('Save'), class_="btn")}
140 146 ${h.reset('reset', _('Reset'), class_="btn")}
141 147 </div>
142 148 </div>
143 149 </div>
144 150 ${h.end_form()}
145 151 </div>
146 152 </div>
147 153 </div>
148 154
149 155 <script>
150 156 $('#language').select2({
151 157 'containerCssClass': "drop-menu",
152 158 'dropdownCssClass': "drop-menu-dropdown",
153 159 'dropdownAutoWidth': true
154 160 });
155 161 </script>
@@ -1,415 +1,416 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2019 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Helpers for fixture generation
23 23 """
24 24
25 25 import os
26 26 import time
27 27 import tempfile
28 28 import shutil
29 29
30 30 import configobj
31 31
32 32 from rhodecode.tests import *
33 33 from rhodecode.model.db import Repository, User, RepoGroup, UserGroup, Gist, UserEmailMap
34 34 from rhodecode.model.meta import Session
35 35 from rhodecode.model.repo import RepoModel
36 36 from rhodecode.model.user import UserModel
37 37 from rhodecode.model.repo_group import RepoGroupModel
38 38 from rhodecode.model.user_group import UserGroupModel
39 39 from rhodecode.model.gist import GistModel
40 40 from rhodecode.model.auth_token import AuthTokenModel
41 41 from rhodecode.authentication.plugins.auth_rhodecode import \
42 42 RhodeCodeAuthPlugin
43 43
44 44 dn = os.path.dirname
45 45 FIXTURES = os.path.join(dn(dn(os.path.abspath(__file__))), 'tests', 'fixtures')
46 46
47 47
48 48 def error_function(*args, **kwargs):
49 49 raise Exception('Total Crash !')
50 50
51 51
52 52 class TestINI(object):
53 53 """
54 54 Allows to create a new test.ini file as a copy of existing one with edited
55 55 data. Example usage::
56 56
57 57 with TestINI('test.ini', [{'section':{'key':val'}]) as new_test_ini_path:
58 58 print('paster server %s' % new_test_ini)
59 59 """
60 60
61 61 def __init__(self, ini_file_path, ini_params, new_file_prefix='DEFAULT',
62 62 destroy=True, dir=None):
63 63 self.ini_file_path = ini_file_path
64 64 self.ini_params = ini_params
65 65 self.new_path = None
66 66 self.new_path_prefix = new_file_prefix
67 67 self._destroy = destroy
68 68 self._dir = dir
69 69
70 70 def __enter__(self):
71 71 return self.create()
72 72
73 73 def __exit__(self, exc_type, exc_val, exc_tb):
74 74 self.destroy()
75 75
76 76 def create(self):
77 77 config = configobj.ConfigObj(
78 78 self.ini_file_path, file_error=True, write_empty_values=True)
79 79
80 80 for data in self.ini_params:
81 81 section, ini_params = data.items()[0]
82 82 for key, val in ini_params.items():
83 83 config[section][key] = val
84 84 with tempfile.NamedTemporaryFile(
85 85 prefix=self.new_path_prefix, suffix='.ini', dir=self._dir,
86 86 delete=False) as new_ini_file:
87 87 config.write(new_ini_file)
88 88 self.new_path = new_ini_file.name
89 89
90 90 return self.new_path
91 91
92 92 def destroy(self):
93 93 if self._destroy:
94 94 os.remove(self.new_path)
95 95
96 96
97 97 class Fixture(object):
98 98
99 99 def anon_access(self, status):
100 100 """
101 101 Context process for disabling anonymous access. use like:
102 102 fixture = Fixture()
103 103 with fixture.anon_access(False):
104 104 #tests
105 105
106 106 after this block anon access will be set to `not status`
107 107 """
108 108
109 109 class context(object):
110 110 def __enter__(self):
111 111 anon = User.get_default_user()
112 112 anon.active = status
113 113 Session().add(anon)
114 114 Session().commit()
115 115 time.sleep(1.5) # must sleep for cache (1s to expire)
116 116
117 117 def __exit__(self, exc_type, exc_val, exc_tb):
118 118 anon = User.get_default_user()
119 119 anon.active = not status
120 120 Session().add(anon)
121 121 Session().commit()
122 122
123 123 return context()
124 124
125 125 def auth_restriction(self, auth_restriction):
126 126 """
127 127 Context process for changing the builtin rhodecode plugin auth restrictions.
128 128 Use like:
129 129 fixture = Fixture()
130 130 with fixture.auth_restriction('super_admin'):
131 131 #tests
132 132
133 133 after this block auth restriction will be taken off
134 134 """
135 135
136 136 class context(object):
137 137 def _get_pluing(self):
138 138 plugin_id = 'egg:rhodecode-enterprise-ce#{}'.format(
139 139 RhodeCodeAuthPlugin.uid)
140 140 plugin = RhodeCodeAuthPlugin(plugin_id)
141 141 return plugin
142 142
143 143 def __enter__(self):
144 144 plugin = self._get_pluing()
145 145 plugin.create_or_update_setting(
146 146 'auth_restriction', auth_restriction)
147 147 Session().commit()
148 148
149 149 def __exit__(self, exc_type, exc_val, exc_tb):
150 150 plugin = self._get_pluing()
151 151 plugin.create_or_update_setting(
152 152 'auth_restriction', RhodeCodeAuthPlugin.AUTH_RESTRICTION_NONE)
153 153 Session().commit()
154 154
155 155 return context()
156 156
157 157 def scope_restriction(self, scope_restriction):
158 158 """
159 159 Context process for changing the builtin rhodecode plugin scope restrictions.
160 160 Use like:
161 161 fixture = Fixture()
162 162 with fixture.scope_restriction('scope_http'):
163 163 #tests
164 164
165 165 after this block scope restriction will be taken off
166 166 """
167 167
168 168 class context(object):
169 169 def _get_pluing(self):
170 170 plugin_id = 'egg:rhodecode-enterprise-ce#{}'.format(
171 171 RhodeCodeAuthPlugin.uid)
172 172 plugin = RhodeCodeAuthPlugin(plugin_id)
173 173 return plugin
174 174
175 175 def __enter__(self):
176 176 plugin = self._get_pluing()
177 177 plugin.create_or_update_setting(
178 178 'scope_restriction', scope_restriction)
179 179 Session().commit()
180 180
181 181 def __exit__(self, exc_type, exc_val, exc_tb):
182 182 plugin = self._get_pluing()
183 183 plugin.create_or_update_setting(
184 184 'scope_restriction', RhodeCodeAuthPlugin.AUTH_RESTRICTION_SCOPE_ALL)
185 185 Session().commit()
186 186
187 187 return context()
188 188
189 189 def _get_repo_create_params(self, **custom):
190 190 defs = {
191 191 'repo_name': None,
192 192 'repo_type': 'hg',
193 193 'clone_uri': '',
194 194 'push_uri': '',
195 195 'repo_group': '-1',
196 196 'repo_description': 'DESC',
197 197 'repo_private': False,
198 198 'repo_landing_rev': 'rev:tip',
199 199 'repo_copy_permissions': False,
200 200 'repo_state': Repository.STATE_CREATED,
201 201 }
202 202 defs.update(custom)
203 203 if 'repo_name_full' not in custom:
204 204 defs.update({'repo_name_full': defs['repo_name']})
205 205
206 206 # fix the repo name if passed as repo_name_full
207 207 if defs['repo_name']:
208 208 defs['repo_name'] = defs['repo_name'].split('/')[-1]
209 209
210 210 return defs
211 211
212 212 def _get_group_create_params(self, **custom):
213 213 defs = {
214 214 'group_name': None,
215 215 'group_description': 'DESC',
216 216 'perm_updates': [],
217 217 'perm_additions': [],
218 218 'perm_deletions': [],
219 219 'group_parent_id': -1,
220 220 'enable_locking': False,
221 221 'recursive': False,
222 222 }
223 223 defs.update(custom)
224 224
225 225 return defs
226 226
227 227 def _get_user_create_params(self, name, **custom):
228 228 defs = {
229 229 'username': name,
230 230 'password': 'qweqwe',
231 231 'email': '%s+test@rhodecode.org' % name,
232 232 'firstname': 'TestUser',
233 233 'lastname': 'Test',
234 'description': 'test description',
234 235 'active': True,
235 236 'admin': False,
236 237 'extern_type': 'rhodecode',
237 238 'extern_name': None,
238 239 }
239 240 defs.update(custom)
240 241
241 242 return defs
242 243
243 244 def _get_user_group_create_params(self, name, **custom):
244 245 defs = {
245 246 'users_group_name': name,
246 247 'user_group_description': 'DESC',
247 248 'users_group_active': True,
248 249 'user_group_data': {},
249 250 }
250 251 defs.update(custom)
251 252
252 253 return defs
253 254
254 255 def create_repo(self, name, **kwargs):
255 256 repo_group = kwargs.get('repo_group')
256 257 if isinstance(repo_group, RepoGroup):
257 258 kwargs['repo_group'] = repo_group.group_id
258 259 name = name.split(Repository.NAME_SEP)[-1]
259 260 name = Repository.NAME_SEP.join((repo_group.group_name, name))
260 261
261 262 if 'skip_if_exists' in kwargs:
262 263 del kwargs['skip_if_exists']
263 264 r = Repository.get_by_repo_name(name)
264 265 if r:
265 266 return r
266 267
267 268 form_data = self._get_repo_create_params(repo_name=name, **kwargs)
268 269 cur_user = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
269 270 RepoModel().create(form_data, cur_user)
270 271 Session().commit()
271 272 repo = Repository.get_by_repo_name(name)
272 273 assert repo
273 274 return repo
274 275
275 276 def create_fork(self, repo_to_fork, fork_name, **kwargs):
276 277 repo_to_fork = Repository.get_by_repo_name(repo_to_fork)
277 278
278 279 form_data = self._get_repo_create_params(repo_name=fork_name,
279 280 fork_parent_id=repo_to_fork.repo_id,
280 281 repo_type=repo_to_fork.repo_type,
281 282 **kwargs)
282 283 #TODO: fix it !!
283 284 form_data['description'] = form_data['repo_description']
284 285 form_data['private'] = form_data['repo_private']
285 286 form_data['landing_rev'] = form_data['repo_landing_rev']
286 287
287 288 owner = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
288 289 RepoModel().create_fork(form_data, cur_user=owner)
289 290 Session().commit()
290 291 r = Repository.get_by_repo_name(fork_name)
291 292 assert r
292 293 return r
293 294
294 295 def destroy_repo(self, repo_name, **kwargs):
295 296 RepoModel().delete(repo_name, pull_requests='delete', **kwargs)
296 297 Session().commit()
297 298
298 299 def destroy_repo_on_filesystem(self, repo_name):
299 300 rm_path = os.path.join(RepoModel().repos_path, repo_name)
300 301 if os.path.isdir(rm_path):
301 302 shutil.rmtree(rm_path)
302 303
303 304 def create_repo_group(self, name, **kwargs):
304 305 if 'skip_if_exists' in kwargs:
305 306 del kwargs['skip_if_exists']
306 307 gr = RepoGroup.get_by_group_name(group_name=name)
307 308 if gr:
308 309 return gr
309 310 form_data = self._get_group_create_params(group_name=name, **kwargs)
310 311 owner = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
311 312 gr = RepoGroupModel().create(
312 313 group_name=form_data['group_name'],
313 314 group_description=form_data['group_name'],
314 315 owner=owner)
315 316 Session().commit()
316 317 gr = RepoGroup.get_by_group_name(gr.group_name)
317 318 return gr
318 319
319 320 def destroy_repo_group(self, repogroupid):
320 321 RepoGroupModel().delete(repogroupid)
321 322 Session().commit()
322 323
323 324 def create_user(self, name, **kwargs):
324 325 if 'skip_if_exists' in kwargs:
325 326 del kwargs['skip_if_exists']
326 327 user = User.get_by_username(name)
327 328 if user:
328 329 return user
329 330 form_data = self._get_user_create_params(name, **kwargs)
330 331 user = UserModel().create(form_data)
331 332
332 333 # create token for user
333 334 AuthTokenModel().create(
334 335 user=user, description=u'TEST_USER_TOKEN')
335 336
336 337 Session().commit()
337 338 user = User.get_by_username(user.username)
338 339 return user
339 340
340 341 def destroy_user(self, userid):
341 342 UserModel().delete(userid)
342 343 Session().commit()
343 344
344 345 def create_additional_user_email(self, user, email):
345 346 uem = UserEmailMap()
346 347 uem.user = user
347 348 uem.email = email
348 349 Session().add(uem)
349 350 return uem
350 351
351 352 def destroy_users(self, userid_iter):
352 353 for user_id in userid_iter:
353 354 if User.get_by_username(user_id):
354 355 UserModel().delete(user_id)
355 356 Session().commit()
356 357
357 358 def create_user_group(self, name, **kwargs):
358 359 if 'skip_if_exists' in kwargs:
359 360 del kwargs['skip_if_exists']
360 361 gr = UserGroup.get_by_group_name(group_name=name)
361 362 if gr:
362 363 return gr
363 364 # map active flag to the real attribute. For API consistency of fixtures
364 365 if 'active' in kwargs:
365 366 kwargs['users_group_active'] = kwargs['active']
366 367 del kwargs['active']
367 368 form_data = self._get_user_group_create_params(name, **kwargs)
368 369 owner = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
369 370 user_group = UserGroupModel().create(
370 371 name=form_data['users_group_name'],
371 372 description=form_data['user_group_description'],
372 373 owner=owner, active=form_data['users_group_active'],
373 374 group_data=form_data['user_group_data'])
374 375 Session().commit()
375 376 user_group = UserGroup.get_by_group_name(user_group.users_group_name)
376 377 return user_group
377 378
378 379 def destroy_user_group(self, usergroupid):
379 380 UserGroupModel().delete(user_group=usergroupid, force=True)
380 381 Session().commit()
381 382
382 383 def create_gist(self, **kwargs):
383 384 form_data = {
384 385 'description': 'new-gist',
385 386 'owner': TEST_USER_ADMIN_LOGIN,
386 387 'gist_type': GistModel.cls.GIST_PUBLIC,
387 388 'lifetime': -1,
388 389 'acl_level': Gist.ACL_LEVEL_PUBLIC,
389 390 'gist_mapping': {'filename1.txt': {'content': 'hello world'},}
390 391 }
391 392 form_data.update(kwargs)
392 393 gist = GistModel().create(
393 394 description=form_data['description'], owner=form_data['owner'],
394 395 gist_mapping=form_data['gist_mapping'], gist_type=form_data['gist_type'],
395 396 lifetime=form_data['lifetime'], gist_acl_level=form_data['acl_level']
396 397 )
397 398 Session().commit()
398 399 return gist
399 400
400 401 def destroy_gists(self, gistid=None):
401 402 for g in GistModel.cls.get_all():
402 403 if gistid:
403 404 if gistid == g.gist_access_id:
404 405 GistModel().delete(g)
405 406 else:
406 407 GistModel().delete(g)
407 408 Session().commit()
408 409
409 410 def load_resource(self, resource_name, strip=False):
410 411 with open(os.path.join(FIXTURES, resource_name)) as f:
411 412 source = f.read()
412 413 if strip:
413 414 source = source.strip()
414 415
415 416 return source
General Comments 0
You need to be logged in to leave comments. Login now