##// END OF EJS Templates
users: ported controllers from pylons into pyramid views.
marcink -
r2114:6e357177 default
parent child Browse files
Show More
@@ -30,6 +30,7 b' from rhodecode.lib.vcs.exceptions import'
30 from rhodecode.model import repo
30 from rhodecode.model import repo
31 from rhodecode.model import repo_group
31 from rhodecode.model import repo_group
32 from rhodecode.model import user_group
32 from rhodecode.model import user_group
33 from rhodecode.model import user
33 from rhodecode.model.db import User
34 from rhodecode.model.db import User
34 from rhodecode.model.scm import ScmModel
35 from rhodecode.model.scm import ScmModel
35
36
@@ -267,6 +268,20 b' class UserGroupAppView(BaseAppView):'
267 self.db_user_group_name = self.db_user_group.users_group_name
268 self.db_user_group_name = self.db_user_group.users_group_name
268
269
269
270
271 class UserAppView(BaseAppView):
272 def __init__(self, context, request):
273 super(UserAppView, self).__init__(context, request)
274 self.db_user = request.db_user
275 self.db_user_id = self.db_user.user_id
276
277 _ = self.request.translate
278 if not request.db_user_supports_default:
279 if self.db_user.username == User.DEFAULT_USER:
280 h.flash(_("Editing user `{}` is disabled.".format(
281 User.DEFAULT_USER)), category='warning')
282 raise HTTPFound(h.route_path('users'))
283
284
270 class DataGridAppView(object):
285 class DataGridAppView(object):
271 """
286 """
272 Common class to have re-usable grid rendering components
287 Common class to have re-usable grid rendering components
@@ -483,17 +498,63 b' class UserGroupRoutePredicate(object):'
483
498
484 user_group_id = info['match']['user_group_id']
499 user_group_id = info['match']['user_group_id']
485 user_group_model = user_group.UserGroup()
500 user_group_model = user_group.UserGroup()
486 by_name_match = user_group_model.get(
501 by_id_match = user_group_model.get(
487 user_group_id, cache=True)
502 user_group_id, cache=True)
488
503
489 if by_name_match:
504 if by_id_match:
490 # register this as request object we can re-use later
505 # register this as request object we can re-use later
491 request.db_user_group = by_name_match
506 request.db_user_group = by_id_match
492 return True
507 return True
493
508
494 return False
509 return False
495
510
496
511
512 class UserRoutePredicateBase(object):
513 supports_default = None
514
515 def __init__(self, val, config):
516 self.val = val
517
518 def text(self):
519 raise NotImplementedError()
520
521 def __call__(self, info, request):
522 if hasattr(request, 'vcs_call'):
523 # skip vcs calls
524 return
525
526 user_id = info['match']['user_id']
527 user_model = user.User()
528 by_id_match = user_model.get(
529 user_id, cache=True)
530
531 if by_id_match:
532 # register this as request object we can re-use later
533 request.db_user = by_id_match
534 request.db_user_supports_default = self.supports_default
535 return True
536
537 return False
538
539
540 class UserRoutePredicate(UserRoutePredicateBase):
541 supports_default = False
542
543 def text(self):
544 return 'user_route = %s' % self.val
545
546 phash = text
547
548
549 class UserRouteWithDefaultPredicate(UserRoutePredicateBase):
550 supports_default = True
551
552 def text(self):
553 return 'user_with_default_route = %s' % self.val
554
555 phash = text
556
557
497 def includeme(config):
558 def includeme(config):
498 config.add_route_predicate(
559 config.add_route_predicate(
499 'repo_route', RepoRoutePredicate)
560 'repo_route', RepoRoutePredicate)
@@ -503,3 +564,7 b' def includeme(config):'
503 'repo_group_route', RepoGroupRoutePredicate)
564 'repo_group_route', RepoGroupRoutePredicate)
504 config.add_route_predicate(
565 config.add_route_predicate(
505 'user_group_route', UserGroupRoutePredicate)
566 'user_group_route', UserGroupRoutePredicate)
567 config.add_route_predicate(
568 'user_route_with_default', UserRouteWithDefaultPredicate)
569 config.add_route_predicate(
570 'user_route', UserRoutePredicate) No newline at end of file
@@ -137,74 +137,133 b' def admin_routes(config):'
137 name='users_data',
137 name='users_data',
138 pattern='/users_data')
138 pattern='/users_data')
139
139
140 config.add_route(
141 name='users_create',
142 pattern='/users/create')
143
144 config.add_route(
145 name='users_new',
146 pattern='/users/new')
147
148 # user management
149 config.add_route(
150 name='user_edit',
151 pattern='/users/{user_id:\d+}/edit',
152 user_route=True)
153 config.add_route(
154 name='user_edit_advanced',
155 pattern='/users/{user_id:\d+}/edit/advanced',
156 user_route=True)
157 config.add_route(
158 name='user_edit_global_perms',
159 pattern='/users/{user_id:\d+}/edit/global_permissions',
160 user_route=True)
161 config.add_route(
162 name='user_edit_global_perms_update',
163 pattern='/users/{user_id:\d+}/edit/global_permissions/update',
164 user_route=True)
165 config.add_route(
166 name='user_update',
167 pattern='/users/{user_id:\d+}/update',
168 user_route=True)
169 config.add_route(
170 name='user_delete',
171 pattern='/users/{user_id:\d+}/delete',
172 user_route=True)
173 config.add_route(
174 name='user_force_password_reset',
175 pattern='/users/{user_id:\d+}/password_reset',
176 user_route=True)
177 config.add_route(
178 name='user_create_personal_repo_group',
179 pattern='/users/{user_id:\d+}/create_repo_group',
180 user_route=True)
181
140 # user auth tokens
182 # user auth tokens
141 config.add_route(
183 config.add_route(
142 name='edit_user_auth_tokens',
184 name='edit_user_auth_tokens',
143 pattern='/users/{user_id:\d+}/edit/auth_tokens')
185 pattern='/users/{user_id:\d+}/edit/auth_tokens',
186 user_route=True)
144 config.add_route(
187 config.add_route(
145 name='edit_user_auth_tokens_add',
188 name='edit_user_auth_tokens_add',
146 pattern='/users/{user_id:\d+}/edit/auth_tokens/new')
189 pattern='/users/{user_id:\d+}/edit/auth_tokens/new',
190 user_route=True)
147 config.add_route(
191 config.add_route(
148 name='edit_user_auth_tokens_delete',
192 name='edit_user_auth_tokens_delete',
149 pattern='/users/{user_id:\d+}/edit/auth_tokens/delete')
193 pattern='/users/{user_id:\d+}/edit/auth_tokens/delete',
194 user_route=True)
150
195
151 # user ssh keys
196 # user ssh keys
152 config.add_route(
197 config.add_route(
153 name='edit_user_ssh_keys',
198 name='edit_user_ssh_keys',
154 pattern='/users/{user_id:\d+}/edit/ssh_keys')
199 pattern='/users/{user_id:\d+}/edit/ssh_keys',
200 user_route=True)
155 config.add_route(
201 config.add_route(
156 name='edit_user_ssh_keys_generate_keypair',
202 name='edit_user_ssh_keys_generate_keypair',
157 pattern='/users/{user_id:\d+}/edit/ssh_keys/generate')
203 pattern='/users/{user_id:\d+}/edit/ssh_keys/generate',
204 user_route=True)
158 config.add_route(
205 config.add_route(
159 name='edit_user_ssh_keys_add',
206 name='edit_user_ssh_keys_add',
160 pattern='/users/{user_id:\d+}/edit/ssh_keys/new')
207 pattern='/users/{user_id:\d+}/edit/ssh_keys/new',
208 user_route=True)
161 config.add_route(
209 config.add_route(
162 name='edit_user_ssh_keys_delete',
210 name='edit_user_ssh_keys_delete',
163 pattern='/users/{user_id:\d+}/edit/ssh_keys/delete')
211 pattern='/users/{user_id:\d+}/edit/ssh_keys/delete',
212 user_route=True)
164
213
165 # user emails
214 # user emails
166 config.add_route(
215 config.add_route(
167 name='edit_user_emails',
216 name='edit_user_emails',
168 pattern='/users/{user_id:\d+}/edit/emails')
217 pattern='/users/{user_id:\d+}/edit/emails',
218 user_route=True)
169 config.add_route(
219 config.add_route(
170 name='edit_user_emails_add',
220 name='edit_user_emails_add',
171 pattern='/users/{user_id:\d+}/edit/emails/new')
221 pattern='/users/{user_id:\d+}/edit/emails/new',
222 user_route=True)
172 config.add_route(
223 config.add_route(
173 name='edit_user_emails_delete',
224 name='edit_user_emails_delete',
174 pattern='/users/{user_id:\d+}/edit/emails/delete')
225 pattern='/users/{user_id:\d+}/edit/emails/delete',
226 user_route=True)
175
227
176 # user IPs
228 # user IPs
177 config.add_route(
229 config.add_route(
178 name='edit_user_ips',
230 name='edit_user_ips',
179 pattern='/users/{user_id:\d+}/edit/ips')
231 pattern='/users/{user_id:\d+}/edit/ips',
232 user_route=True)
180 config.add_route(
233 config.add_route(
181 name='edit_user_ips_add',
234 name='edit_user_ips_add',
182 pattern='/users/{user_id:\d+}/edit/ips/new')
235 pattern='/users/{user_id:\d+}/edit/ips/new',
236 user_route_with_default=True) # enabled for default user too
183 config.add_route(
237 config.add_route(
184 name='edit_user_ips_delete',
238 name='edit_user_ips_delete',
185 pattern='/users/{user_id:\d+}/edit/ips/delete')
239 pattern='/users/{user_id:\d+}/edit/ips/delete',
240 user_route_with_default=True) # enabled for default user too
186
241
187 # user perms
242 # user perms
188 config.add_route(
243 config.add_route(
189 name='edit_user_perms_summary',
244 name='edit_user_perms_summary',
190 pattern='/users/{user_id:\d+}/edit/permissions_summary')
245 pattern='/users/{user_id:\d+}/edit/permissions_summary',
246 user_route=True)
191 config.add_route(
247 config.add_route(
192 name='edit_user_perms_summary_json',
248 name='edit_user_perms_summary_json',
193 pattern='/users/{user_id:\d+}/edit/permissions_summary/json')
249 pattern='/users/{user_id:\d+}/edit/permissions_summary/json',
250 user_route=True)
194
251
195 # user user groups management
252 # user user groups management
196 config.add_route(
253 config.add_route(
197 name='edit_user_groups_management',
254 name='edit_user_groups_management',
198 pattern='/users/{user_id:\d+}/edit/groups_management')
255 pattern='/users/{user_id:\d+}/edit/groups_management',
256 user_route=True)
199
257
200 config.add_route(
258 config.add_route(
201 name='edit_user_groups_management_updates',
259 name='edit_user_groups_management_updates',
202 pattern='/users/{user_id:\d+}/edit/edit_user_groups_management/updates')
260 pattern='/users/{user_id:\d+}/edit/edit_user_groups_management/updates',
261 user_route=True)
203
262
204 # user audit logs
263 # user audit logs
205 config.add_route(
264 config.add_route(
206 name='edit_user_audit_logs',
265 name='edit_user_audit_logs',
207 pattern='/users/{user_id:\d+}/edit/audit')
266 pattern='/users/{user_id:\d+}/edit/audit', user_route=True)
208
267
209 # user-groups admin
268 # user-groups admin
210 config.add_route(
269 config.add_route(
This diff has been collapsed as it changes many lines, (516 lines changed) Show them Hide them
@@ -19,8 +19,12 b''
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import pytest
21 import pytest
22 from sqlalchemy.orm.exc import NoResultFound
22
23
23 from rhodecode.model.db import User, UserApiKeys, UserEmailMap
24 from rhodecode.lib import auth
25 from rhodecode.lib import helpers as h
26 from rhodecode.model import validators
27 from rhodecode.model.db import User, UserApiKeys, UserEmailMap, Repository
24 from rhodecode.model.meta import Session
28 from rhodecode.model.meta import Session
25 from rhodecode.model.user import UserModel
29 from rhodecode.model.user import UserModel
26
30
@@ -40,6 +44,27 b' def route_path(name, params=None, **kwar'
40 ADMIN_PREFIX + '/users',
44 ADMIN_PREFIX + '/users',
41 'users_data':
45 'users_data':
42 ADMIN_PREFIX + '/users_data',
46 ADMIN_PREFIX + '/users_data',
47 'users_create':
48 ADMIN_PREFIX + '/users/create',
49 'users_new':
50 ADMIN_PREFIX + '/users/new',
51 'user_edit':
52 ADMIN_PREFIX + '/users/{user_id}/edit',
53 'user_edit_advanced':
54 ADMIN_PREFIX + '/users/{user_id}/edit/advanced',
55 'user_edit_global_perms':
56 ADMIN_PREFIX + '/users/{user_id}/edit/global_permissions',
57 'user_edit_global_perms_update':
58 ADMIN_PREFIX + '/users/{user_id}/edit/global_permissions/update',
59 'user_update':
60 ADMIN_PREFIX + '/users/{user_id}/update',
61 'user_delete':
62 ADMIN_PREFIX + '/users/{user_id}/delete',
63 'user_force_password_reset':
64 ADMIN_PREFIX + '/users/{user_id}/password_reset',
65 'user_create_personal_repo_group':
66 ADMIN_PREFIX + '/users/{user_id}/create_repo_group',
67
43 'edit_user_auth_tokens':
68 'edit_user_auth_tokens':
44 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens',
69 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens',
45 'edit_user_auth_tokens_add':
70 'edit_user_auth_tokens_add':
@@ -60,6 +85,15 b' def route_path(name, params=None, **kwar'
60 ADMIN_PREFIX + '/users/{user_id}/edit/ips/new',
85 ADMIN_PREFIX + '/users/{user_id}/edit/ips/new',
61 'edit_user_ips_delete':
86 'edit_user_ips_delete':
62 ADMIN_PREFIX + '/users/{user_id}/edit/ips/delete',
87 ADMIN_PREFIX + '/users/{user_id}/edit/ips/delete',
88
89 'edit_user_perms_summary':
90 ADMIN_PREFIX + '/users/{user_id}/edit/permissions_summary',
91 'edit_user_perms_summary_json':
92 ADMIN_PREFIX + '/users/{user_id}/edit/permissions_summary/json',
93
94 'edit_user_audit_logs':
95 ADMIN_PREFIX + '/users/{user_id}/edit/audit',
96
63 }[name].format(**kwargs)
97 }[name].format(**kwargs)
64
98
65 if params:
99 if params:
@@ -220,7 +254,8 b' class TestAdminUsersView(TestController)'
220 def test_emails(self):
254 def test_emails(self):
221 self.log_user()
255 self.log_user()
222 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
256 user = User.get_by_username(TEST_USER_REGULAR_LOGIN)
223 response = self.app.get(route_path('edit_user_emails', user_id=user.user_id))
257 response = self.app.get(
258 route_path('edit_user_emails', user_id=user.user_id))
224 response.mustcontain('No additional emails specified')
259 response.mustcontain('No additional emails specified')
225
260
226 def test_emails_add(self, user_util):
261 def test_emails_add(self, user_util):
@@ -233,7 +268,8 b' class TestAdminUsersView(TestController)'
233 params={'new_email': 'example@rhodecode.com',
268 params={'new_email': 'example@rhodecode.com',
234 'csrf_token': self.csrf_token})
269 'csrf_token': self.csrf_token})
235
270
236 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
271 response = self.app.get(
272 route_path('edit_user_emails', user_id=user_id))
237 response.mustcontain('example@rhodecode.com')
273 response.mustcontain('example@rhodecode.com')
238
274
239 def test_emails_add_existing_email(self, user_util, user_regular):
275 def test_emails_add_existing_email(self, user_util, user_regular):
@@ -250,7 +286,8 b' class TestAdminUsersView(TestController)'
250 assert_session_flash(
286 assert_session_flash(
251 response, 'This e-mail address is already taken')
287 response, 'This e-mail address is already taken')
252
288
253 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
289 response = self.app.get(
290 route_path('edit_user_emails', user_id=user_id))
254 response.mustcontain(no=[existing_email])
291 response.mustcontain(no=[existing_email])
255
292
256 def test_emails_delete(self, user_util):
293 def test_emails_delete(self, user_util):
@@ -263,7 +300,8 b' class TestAdminUsersView(TestController)'
263 params={'new_email': 'example@rhodecode.com',
300 params={'new_email': 'example@rhodecode.com',
264 'csrf_token': self.csrf_token})
301 'csrf_token': self.csrf_token})
265
302
266 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
303 response = self.app.get(
304 route_path('edit_user_emails', user_id=user_id))
267 response.mustcontain('example@rhodecode.com')
305 response.mustcontain('example@rhodecode.com')
268
306
269 user_email = UserEmailMap.query()\
307 user_email = UserEmailMap.query()\
@@ -277,5 +315,469 b' class TestAdminUsersView(TestController)'
277 params={'del_email_id': del_email_id,
315 params={'del_email_id': del_email_id,
278 'csrf_token': self.csrf_token})
316 'csrf_token': self.csrf_token})
279
317
280 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
318 response = self.app.get(
281 response.mustcontain(no=['example@rhodecode.com']) No newline at end of file
319 route_path('edit_user_emails', user_id=user_id))
320 response.mustcontain(no=['example@rhodecode.com'])
321
322
323 def test_create(self, request, xhr_header):
324 self.log_user()
325 username = 'newtestuser'
326 password = 'test12'
327 password_confirmation = password
328 name = 'name'
329 lastname = 'lastname'
330 email = 'mail@mail.com'
331
332 self.app.get(route_path('users_new'))
333
334 response = self.app.post(route_path('users_create'), params={
335 'username': username,
336 'password': password,
337 'password_confirmation': password_confirmation,
338 'firstname': name,
339 'active': True,
340 'lastname': lastname,
341 'extern_name': 'rhodecode',
342 'extern_type': 'rhodecode',
343 'email': email,
344 'csrf_token': self.csrf_token,
345 })
346 user_link = h.link_to(
347 username,
348 route_path(
349 'user_edit', user_id=User.get_by_username(username).user_id))
350 assert_session_flash(response, 'Created user %s' % (user_link,))
351
352 @request.addfinalizer
353 def cleanup():
354 fixture.destroy_user(username)
355 Session().commit()
356
357 new_user = User.query().filter(User.username == username).one()
358
359 assert new_user.username == username
360 assert auth.check_password(password, new_user.password)
361 assert new_user.name == name
362 assert new_user.lastname == lastname
363 assert new_user.email == email
364
365 response = self.app.get(route_path('users_data'),
366 extra_environ=xhr_header)
367 response.mustcontain(username)
368
369 def test_create_err(self):
370 self.log_user()
371 username = 'new_user'
372 password = ''
373 name = 'name'
374 lastname = 'lastname'
375 email = 'errmail.com'
376
377 self.app.get(route_path('users_new'))
378
379 response = self.app.post(route_path('users_create'), params={
380 'username': username,
381 'password': password,
382 'name': name,
383 'active': False,
384 'lastname': lastname,
385 'email': email,
386 'csrf_token': self.csrf_token,
387 })
388
389 msg = validators.ValidUsername(
390 False, {})._messages['system_invalid_username']
391 msg = h.html_escape(msg % {'username': 'new_user'})
392 response.mustcontain('<span class="error-message">%s</span>' % msg)
393 response.mustcontain(
394 '<span class="error-message">Please enter a value</span>')
395 response.mustcontain(
396 '<span class="error-message">An email address must contain a'
397 ' single @</span>')
398
399 def get_user():
400 Session().query(User).filter(User.username == username).one()
401
402 with pytest.raises(NoResultFound):
403 get_user()
404
405 def test_new(self):
406 self.log_user()
407 self.app.get(route_path('users_new'))
408
409 @pytest.mark.parametrize("name, attrs", [
410 ('firstname', {'firstname': 'new_username'}),
411 ('lastname', {'lastname': 'new_username'}),
412 ('admin', {'admin': True}),
413 ('admin', {'admin': False}),
414 ('extern_type', {'extern_type': 'ldap'}),
415 ('extern_type', {'extern_type': None}),
416 ('extern_name', {'extern_name': 'test'}),
417 ('extern_name', {'extern_name': None}),
418 ('active', {'active': False}),
419 ('active', {'active': True}),
420 ('email', {'email': 'some@email.com'}),
421 ('language', {'language': 'de'}),
422 ('language', {'language': 'en'}),
423 # ('new_password', {'new_password': 'foobar123',
424 # 'password_confirmation': 'foobar123'})
425 ])
426 def test_update(self, name, attrs, user_util):
427 self.log_user()
428 usr = user_util.create_user(
429 password='qweqwe',
430 email='testme@rhodecode.org',
431 extern_type='rhodecode',
432 extern_name='xxx',
433 )
434 user_id = usr.user_id
435 Session().commit()
436
437 params = usr.get_api_data()
438 cur_lang = params['language'] or 'en'
439 params.update({
440 'password_confirmation': '',
441 'new_password': '',
442 'language': cur_lang,
443 'csrf_token': self.csrf_token,
444 })
445 params.update({'new_password': ''})
446 params.update(attrs)
447 if name == 'email':
448 params['emails'] = [attrs['email']]
449 elif name == 'extern_type':
450 # cannot update this via form, expected value is original one
451 params['extern_type'] = "rhodecode"
452 elif name == 'extern_name':
453 # cannot update this via form, expected value is original one
454 params['extern_name'] = 'xxx'
455 # special case since this user is not
456 # logged in yet his data is not filled
457 # so we use creation data
458
459 response = self.app.post(
460 route_path('user_update', user_id=usr.user_id), params)
461 assert response.status_int == 302
462 assert_session_flash(response, 'User updated successfully')
463
464 updated_user = User.get(user_id)
465 updated_params = updated_user.get_api_data()
466 updated_params.update({'password_confirmation': ''})
467 updated_params.update({'new_password': ''})
468
469 del params['csrf_token']
470 assert params == updated_params
471
472 def test_update_and_migrate_password(
473 self, autologin_user, real_crypto_backend, user_util):
474
475 user = user_util.create_user()
476 temp_user = user.username
477 user.password = auth._RhodeCodeCryptoSha256().hash_create(
478 b'test123')
479 Session().add(user)
480 Session().commit()
481
482 params = user.get_api_data()
483
484 params.update({
485 'password_confirmation': 'qweqwe123',
486 'new_password': 'qweqwe123',
487 'language': 'en',
488 'csrf_token': autologin_user.csrf_token,
489 })
490
491 response = self.app.post(
492 route_path('user_update', user_id=user.user_id), params)
493 assert response.status_int == 302
494 assert_session_flash(response, 'User updated successfully')
495
496 # new password should be bcrypted, after log-in and transfer
497 user = User.get_by_username(temp_user)
498 assert user.password.startswith('$')
499
500 updated_user = User.get_by_username(temp_user)
501 updated_params = updated_user.get_api_data()
502 updated_params.update({'password_confirmation': 'qweqwe123'})
503 updated_params.update({'new_password': 'qweqwe123'})
504
505 del params['csrf_token']
506 assert params == updated_params
507
508 def test_delete(self):
509 self.log_user()
510 username = 'newtestuserdeleteme'
511
512 fixture.create_user(name=username)
513
514 new_user = Session().query(User)\
515 .filter(User.username == username).one()
516 response = self.app.post(
517 route_path('user_delete', user_id=new_user.user_id),
518 params={'csrf_token': self.csrf_token})
519
520 assert_session_flash(response, 'Successfully deleted user')
521
522 def test_delete_owner_of_repository(self, request, user_util):
523 self.log_user()
524 obj_name = 'test_repo'
525 usr = user_util.create_user()
526 username = usr.username
527 fixture.create_repo(obj_name, cur_user=usr.username)
528
529 new_user = Session().query(User)\
530 .filter(User.username == username).one()
531 response = self.app.post(
532 route_path('user_delete', user_id=new_user.user_id),
533 params={'csrf_token': self.csrf_token})
534
535 msg = 'user "%s" still owns 1 repositories and cannot be removed. ' \
536 'Switch owners or remove those repositories:%s' % (username,
537 obj_name)
538 assert_session_flash(response, msg)
539 fixture.destroy_repo(obj_name)
540
541 def test_delete_owner_of_repository_detaching(self, request, user_util):
542 self.log_user()
543 obj_name = 'test_repo'
544 usr = user_util.create_user(auto_cleanup=False)
545 username = usr.username
546 fixture.create_repo(obj_name, cur_user=usr.username)
547
548 new_user = Session().query(User)\
549 .filter(User.username == username).one()
550 response = self.app.post(
551 route_path('user_delete', user_id=new_user.user_id),
552 params={'user_repos': 'detach', 'csrf_token': self.csrf_token})
553
554 msg = 'Detached 1 repositories'
555 assert_session_flash(response, msg)
556 fixture.destroy_repo(obj_name)
557
558 def test_delete_owner_of_repository_deleting(self, request, user_util):
559 self.log_user()
560 obj_name = 'test_repo'
561 usr = user_util.create_user(auto_cleanup=False)
562 username = usr.username
563 fixture.create_repo(obj_name, cur_user=usr.username)
564
565 new_user = Session().query(User)\
566 .filter(User.username == username).one()
567 response = self.app.post(
568 route_path('user_delete', user_id=new_user.user_id),
569 params={'user_repos': 'delete', 'csrf_token': self.csrf_token})
570
571 msg = 'Deleted 1 repositories'
572 assert_session_flash(response, msg)
573
574 def test_delete_owner_of_repository_group(self, request, user_util):
575 self.log_user()
576 obj_name = 'test_group'
577 usr = user_util.create_user()
578 username = usr.username
579 fixture.create_repo_group(obj_name, cur_user=usr.username)
580
581 new_user = Session().query(User)\
582 .filter(User.username == username).one()
583 response = self.app.post(
584 route_path('user_delete', user_id=new_user.user_id),
585 params={'csrf_token': self.csrf_token})
586
587 msg = 'user "%s" still owns 1 repository groups and cannot be removed. ' \
588 'Switch owners or remove those repository groups:%s' % (username,
589 obj_name)
590 assert_session_flash(response, msg)
591 fixture.destroy_repo_group(obj_name)
592
593 def test_delete_owner_of_repository_group_detaching(self, request, user_util):
594 self.log_user()
595 obj_name = 'test_group'
596 usr = user_util.create_user(auto_cleanup=False)
597 username = usr.username
598 fixture.create_repo_group(obj_name, cur_user=usr.username)
599
600 new_user = Session().query(User)\
601 .filter(User.username == username).one()
602 response = self.app.post(
603 route_path('user_delete', user_id=new_user.user_id),
604 params={'user_repo_groups': 'delete', 'csrf_token': self.csrf_token})
605
606 msg = 'Deleted 1 repository groups'
607 assert_session_flash(response, msg)
608
609 def test_delete_owner_of_repository_group_deleting(self, request, user_util):
610 self.log_user()
611 obj_name = 'test_group'
612 usr = user_util.create_user(auto_cleanup=False)
613 username = usr.username
614 fixture.create_repo_group(obj_name, cur_user=usr.username)
615
616 new_user = Session().query(User)\
617 .filter(User.username == username).one()
618 response = self.app.post(
619 route_path('user_delete', user_id=new_user.user_id),
620 params={'user_repo_groups': 'detach', 'csrf_token': self.csrf_token})
621
622 msg = 'Detached 1 repository groups'
623 assert_session_flash(response, msg)
624 fixture.destroy_repo_group(obj_name)
625
626 def test_delete_owner_of_user_group(self, request, user_util):
627 self.log_user()
628 obj_name = 'test_user_group'
629 usr = user_util.create_user()
630 username = usr.username
631 fixture.create_user_group(obj_name, cur_user=usr.username)
632
633 new_user = Session().query(User)\
634 .filter(User.username == username).one()
635 response = self.app.post(
636 route_path('user_delete', user_id=new_user.user_id),
637 params={'csrf_token': self.csrf_token})
638
639 msg = 'user "%s" still owns 1 user groups and cannot be removed. ' \
640 'Switch owners or remove those user groups:%s' % (username,
641 obj_name)
642 assert_session_flash(response, msg)
643 fixture.destroy_user_group(obj_name)
644
645 def test_delete_owner_of_user_group_detaching(self, request, user_util):
646 self.log_user()
647 obj_name = 'test_user_group'
648 usr = user_util.create_user(auto_cleanup=False)
649 username = usr.username
650 fixture.create_user_group(obj_name, cur_user=usr.username)
651
652 new_user = Session().query(User)\
653 .filter(User.username == username).one()
654 try:
655 response = self.app.post(
656 route_path('user_delete', user_id=new_user.user_id),
657 params={'user_user_groups': 'detach',
658 'csrf_token': self.csrf_token})
659
660 msg = 'Detached 1 user groups'
661 assert_session_flash(response, msg)
662 finally:
663 fixture.destroy_user_group(obj_name)
664
665 def test_delete_owner_of_user_group_deleting(self, request, user_util):
666 self.log_user()
667 obj_name = 'test_user_group'
668 usr = user_util.create_user(auto_cleanup=False)
669 username = usr.username
670 fixture.create_user_group(obj_name, cur_user=usr.username)
671
672 new_user = Session().query(User)\
673 .filter(User.username == username).one()
674 response = self.app.post(
675 route_path('user_delete', user_id=new_user.user_id),
676 params={'user_user_groups': 'delete', 'csrf_token': self.csrf_token})
677
678 msg = 'Deleted 1 user groups'
679 assert_session_flash(response, msg)
680
681 def test_edit(self, user_util):
682 self.log_user()
683 user = user_util.create_user()
684 self.app.get(route_path('user_edit', user_id=user.user_id))
685
686 def test_edit_default_user_redirect(self):
687 self.log_user()
688 user = User.get_default_user()
689 self.app.get(route_path('user_edit', user_id=user.user_id), status=302)
690
691 @pytest.mark.parametrize(
692 'repo_create, repo_create_write, user_group_create, repo_group_create,'
693 'fork_create, inherit_default_permissions, expect_error,'
694 'expect_form_error', [
695 ('hg.create.none', 'hg.create.write_on_repogroup.false',
696 'hg.usergroup.create.false', 'hg.repogroup.create.false',
697 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
698 ('hg.create.repository', 'hg.create.write_on_repogroup.false',
699 'hg.usergroup.create.false', 'hg.repogroup.create.false',
700 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
701 ('hg.create.repository', 'hg.create.write_on_repogroup.true',
702 'hg.usergroup.create.true', 'hg.repogroup.create.true',
703 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
704 False),
705 ('hg.create.XXX', 'hg.create.write_on_repogroup.true',
706 'hg.usergroup.create.true', 'hg.repogroup.create.true',
707 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
708 True),
709 ('', '', '', '', '', '', True, False),
710 ])
711 def test_global_perms_on_user(
712 self, repo_create, repo_create_write, user_group_create,
713 repo_group_create, fork_create, expect_error, expect_form_error,
714 inherit_default_permissions, user_util):
715 self.log_user()
716 user = user_util.create_user()
717 uid = user.user_id
718
719 # ENABLE REPO CREATE ON A GROUP
720 perm_params = {
721 'inherit_default_permissions': False,
722 'default_repo_create': repo_create,
723 'default_repo_create_on_write': repo_create_write,
724 'default_user_group_create': user_group_create,
725 'default_repo_group_create': repo_group_create,
726 'default_fork_create': fork_create,
727 'default_inherit_default_permissions': inherit_default_permissions,
728 'csrf_token': self.csrf_token,
729 }
730 response = self.app.post(
731 route_path('user_edit_global_perms_update', user_id=uid),
732 params=perm_params)
733
734 if expect_form_error:
735 assert response.status_int == 200
736 response.mustcontain('Value must be one of')
737 else:
738 if expect_error:
739 msg = 'An error occurred during permissions saving'
740 else:
741 msg = 'User global permissions updated successfully'
742 ug = User.get(uid)
743 del perm_params['inherit_default_permissions']
744 del perm_params['csrf_token']
745 assert perm_params == ug.get_default_perms()
746 assert_session_flash(response, msg)
747
748 def test_global_permissions_initial_values(self, user_util):
749 self.log_user()
750 user = user_util.create_user()
751 uid = user.user_id
752 response = self.app.get(
753 route_path('user_edit_global_perms', user_id=uid))
754 default_user = User.get_default_user()
755 default_permissions = default_user.get_default_perms()
756 assert_response = response.assert_response()
757 expected_permissions = (
758 'default_repo_create', 'default_repo_create_on_write',
759 'default_fork_create', 'default_repo_group_create',
760 'default_user_group_create', 'default_inherit_default_permissions')
761 for permission in expected_permissions:
762 css_selector = '[name={}][checked=checked]'.format(permission)
763 element = assert_response.get_element(css_selector)
764 assert element.value == default_permissions[permission]
765
766 def test_perms_summary_page(self):
767 user = self.log_user()
768 response = self.app.get(
769 route_path('edit_user_perms_summary', user_id=user['user_id']))
770 for repo in Repository.query().all():
771 response.mustcontain(repo.repo_name)
772
773 def test_perms_summary_page_json(self):
774 user = self.log_user()
775 response = self.app.get(
776 route_path('edit_user_perms_summary_json', user_id=user['user_id']))
777 for repo in Repository.query().all():
778 response.mustcontain(repo.repo_name)
779
780 def test_audit_log_page(self):
781 user = self.log_user()
782 self.app.get(
783 route_path('edit_user_audit_logs', user_id=user['user_id']))
This diff has been collapsed as it changes many lines, (691 lines changed) Show them Hide them
@@ -18,7 +18,6 b''
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import time
22 import logging
21 import logging
23 import datetime
22 import datetime
24 import formencode
23 import formencode
@@ -26,51 +25,46 b' import formencode.htmlfill'
26
25
27 from pyramid.httpexceptions import HTTPFound
26 from pyramid.httpexceptions import HTTPFound
28 from pyramid.view import view_config
27 from pyramid.view import view_config
29 from sqlalchemy.sql.functions import coalesce
28 from pyramid.renderers import render
30 from sqlalchemy.exc import IntegrityError
29 from pyramid.response import Response
31
30
32 from rhodecode.apps._base import BaseAppView, DataGridAppView
31 from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView
33 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
32 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
33 from rhodecode.authentication.plugins import auth_rhodecode
34 from rhodecode.events import trigger
34 from rhodecode.events import trigger
35
35
36 from rhodecode.lib import audit_logger
36 from rhodecode.lib import audit_logger
37 from rhodecode.lib.exceptions import (
38 UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException,
39 UserOwnsUserGroupsException, DefaultUserException)
37 from rhodecode.lib.ext_json import json
40 from rhodecode.lib.ext_json import json
38 from rhodecode.lib.auth import (
41 from rhodecode.lib.auth import (
39 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
42 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
40 from rhodecode.lib import helpers as h
43 from rhodecode.lib import helpers as h
41 from rhodecode.lib.utils2 import safe_int, safe_unicode
44 from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict
42 from rhodecode.model.auth_token import AuthTokenModel
45 from rhodecode.model.auth_token import AuthTokenModel
46 from rhodecode.model.forms import (
47 UserForm, UserIndividualPermissionsForm, UserPermissionsForm)
48 from rhodecode.model.permission import PermissionModel
49 from rhodecode.model.repo_group import RepoGroupModel
43 from rhodecode.model.ssh_key import SshKeyModel
50 from rhodecode.model.ssh_key import SshKeyModel
44 from rhodecode.model.user import UserModel
51 from rhodecode.model.user import UserModel
45 from rhodecode.model.user_group import UserGroupModel
52 from rhodecode.model.user_group import UserGroupModel
46 from rhodecode.model.db import (
53 from rhodecode.model.db import (
47 or_, User, UserIpMap, UserEmailMap, UserApiKeys, UserSshKeys)
54 or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap,
55 UserApiKeys, UserSshKeys, RepoGroup)
48 from rhodecode.model.meta import Session
56 from rhodecode.model.meta import Session
49
57
50 log = logging.getLogger(__name__)
58 log = logging.getLogger(__name__)
51
59
52
60
53 class AdminUsersView(BaseAppView, DataGridAppView):
61 class AdminUsersView(BaseAppView, DataGridAppView):
54 ALLOW_SCOPED_TOKENS = False
55 """
56 This view has alternative version inside EE, if modified please take a look
57 in there as well.
58 """
59
62
60 def load_default_context(self):
63 def load_default_context(self):
61 c = self._get_local_tmpl_context()
64 c = self._get_local_tmpl_context()
62 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
63 self._register_global_c(c)
65 self._register_global_c(c)
64 return c
66 return c
65
67
66 def _redirect_for_default_user(self, username):
67 _ = self.request.translate
68 if username == User.DEFAULT_USER:
69 h.flash(_("You can't edit this user"), category='warning')
70 # TODO(marcink): redirect to 'users' admin panel once this
71 # is a pyramid view
72 raise HTTPFound('/')
73
74 @LoginRequired()
68 @LoginRequired()
75 @HasPermissionAllDecorator('hg.admin')
69 @HasPermissionAllDecorator('hg.admin')
76 @view_config(
70 @view_config(
@@ -163,6 +157,529 b' class AdminUsersView(BaseAppView, DataGr'
163
157
164 return data
158 return data
165
159
160 def _set_personal_repo_group_template_vars(self, c_obj):
161 DummyUser = AttributeDict({
162 'username': '${username}',
163 'user_id': '${user_id}',
164 })
165 c_obj.default_create_repo_group = RepoGroupModel() \
166 .get_default_create_personal_repo_group()
167 c_obj.personal_repo_group_name = RepoGroupModel() \
168 .get_personal_group_name(DummyUser)
169
170 @LoginRequired()
171 @HasPermissionAllDecorator('hg.admin')
172 @view_config(
173 route_name='users_new', request_method='GET',
174 renderer='rhodecode:templates/admin/users/user_add.mako')
175 def users_new(self):
176 _ = self.request.translate
177 c = self.load_default_context()
178 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
179 self._set_personal_repo_group_template_vars(c)
180 return self._get_template_context(c)
181
182 @LoginRequired()
183 @HasPermissionAllDecorator('hg.admin')
184 @CSRFRequired()
185 @view_config(
186 route_name='users_create', request_method='POST',
187 renderer='rhodecode:templates/admin/users/user_add.mako')
188 def users_create(self):
189 _ = self.request.translate
190 c = self.load_default_context()
191 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
192 user_model = UserModel()
193 user_form = UserForm()()
194 try:
195 form_result = user_form.to_python(dict(self.request.POST))
196 user = user_model.create(form_result)
197 Session().flush()
198 creation_data = user.get_api_data()
199 username = form_result['username']
200
201 audit_logger.store_web(
202 'user.create', action_data={'data': creation_data},
203 user=c.rhodecode_user)
204
205 user_link = h.link_to(
206 h.escape(username),
207 h.route_path('user_edit', user_id=user.user_id))
208 h.flash(h.literal(_('Created user %(user_link)s')
209 % {'user_link': user_link}), category='success')
210 Session().commit()
211 except formencode.Invalid as errors:
212 self._set_personal_repo_group_template_vars(c)
213 data = render(
214 'rhodecode:templates/admin/users/user_add.mako',
215 self._get_template_context(c), self.request)
216 html = formencode.htmlfill.render(
217 data,
218 defaults=errors.value,
219 errors=errors.error_dict or {},
220 prefix_error=False,
221 encoding="UTF-8",
222 force_defaults=False
223 )
224 return Response(html)
225 except UserCreationError as e:
226 h.flash(e, 'error')
227 except Exception:
228 log.exception("Exception creation of user")
229 h.flash(_('Error occurred during creation of user %s')
230 % self.request.POST.get('username'), category='error')
231 raise HTTPFound(h.route_path('users'))
232
233
234 class UsersView(UserAppView):
235 ALLOW_SCOPED_TOKENS = False
236 """
237 This view has alternative version inside EE, if modified please take a look
238 in there as well.
239 """
240
241 def load_default_context(self):
242 c = self._get_local_tmpl_context()
243 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
244 c.allowed_languages = [
245 ('en', 'English (en)'),
246 ('de', 'German (de)'),
247 ('fr', 'French (fr)'),
248 ('it', 'Italian (it)'),
249 ('ja', 'Japanese (ja)'),
250 ('pl', 'Polish (pl)'),
251 ('pt', 'Portuguese (pt)'),
252 ('ru', 'Russian (ru)'),
253 ('zh', 'Chinese (zh)'),
254 ]
255 req = self.request
256
257 c.available_permissions = req.registry.settings['available_permissions']
258 PermissionModel().set_global_permission_choices(
259 c, gettext_translator=req.translate)
260
261 self._register_global_c(c)
262 return c
263
264 @LoginRequired()
265 @HasPermissionAllDecorator('hg.admin')
266 @CSRFRequired()
267 @view_config(
268 route_name='user_update', request_method='POST',
269 renderer='rhodecode:templates/admin/users/user_edit.mako')
270 def user_update(self):
271 _ = self.request.translate
272 c = self.load_default_context()
273
274 user_id = self.db_user_id
275 c.user = self.db_user
276
277 c.active = 'profile'
278 c.extern_type = c.user.extern_type
279 c.extern_name = c.user.extern_name
280 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
281 available_languages = [x[0] for x in c.allowed_languages]
282 _form = UserForm(edit=True, available_languages=available_languages,
283 old_data={'user_id': user_id,
284 'email': c.user.email})()
285 form_result = {}
286 old_values = c.user.get_api_data()
287 try:
288 form_result = _form.to_python(dict(self.request.POST))
289 skip_attrs = ['extern_type', 'extern_name']
290 # TODO: plugin should define if username can be updated
291 if c.extern_type != "rhodecode":
292 # forbid updating username for external accounts
293 skip_attrs.append('username')
294
295 UserModel().update_user(
296 user_id, skip_attrs=skip_attrs, **form_result)
297
298 audit_logger.store_web(
299 'user.edit', action_data={'old_data': old_values},
300 user=c.rhodecode_user)
301
302 Session().commit()
303 h.flash(_('User updated successfully'), category='success')
304 except formencode.Invalid as errors:
305 data = render(
306 'rhodecode:templates/admin/users/user_edit.mako',
307 self._get_template_context(c), self.request)
308 html = formencode.htmlfill.render(
309 data,
310 defaults=errors.value,
311 errors=errors.error_dict or {},
312 prefix_error=False,
313 encoding="UTF-8",
314 force_defaults=False
315 )
316 return Response(html)
317 except UserCreationError as e:
318 h.flash(e, 'error')
319 except Exception:
320 log.exception("Exception updating user")
321 h.flash(_('Error occurred during update of user %s')
322 % form_result.get('username'), category='error')
323 raise HTTPFound(h.route_path('user_edit', user_id=user_id))
324
325 @LoginRequired()
326 @HasPermissionAllDecorator('hg.admin')
327 @CSRFRequired()
328 @view_config(
329 route_name='user_delete', request_method='POST',
330 renderer='rhodecode:templates/admin/users/user_edit.mako')
331 def user_delete(self):
332 _ = self.request.translate
333 c = self.load_default_context()
334 c.user = self.db_user
335
336 _repos = c.user.repositories
337 _repo_groups = c.user.repository_groups
338 _user_groups = c.user.user_groups
339
340 handle_repos = None
341 handle_repo_groups = None
342 handle_user_groups = None
343 # dummy call for flash of handle
344 set_handle_flash_repos = lambda: None
345 set_handle_flash_repo_groups = lambda: None
346 set_handle_flash_user_groups = lambda: None
347
348 if _repos and self.request.POST.get('user_repos'):
349 do = self.request.POST['user_repos']
350 if do == 'detach':
351 handle_repos = 'detach'
352 set_handle_flash_repos = lambda: h.flash(
353 _('Detached %s repositories') % len(_repos),
354 category='success')
355 elif do == 'delete':
356 handle_repos = 'delete'
357 set_handle_flash_repos = lambda: h.flash(
358 _('Deleted %s repositories') % len(_repos),
359 category='success')
360
361 if _repo_groups and self.request.POST.get('user_repo_groups'):
362 do = self.request.POST['user_repo_groups']
363 if do == 'detach':
364 handle_repo_groups = 'detach'
365 set_handle_flash_repo_groups = lambda: h.flash(
366 _('Detached %s repository groups') % len(_repo_groups),
367 category='success')
368 elif do == 'delete':
369 handle_repo_groups = 'delete'
370 set_handle_flash_repo_groups = lambda: h.flash(
371 _('Deleted %s repository groups') % len(_repo_groups),
372 category='success')
373
374 if _user_groups and self.request.POST.get('user_user_groups'):
375 do = self.request.POST['user_user_groups']
376 if do == 'detach':
377 handle_user_groups = 'detach'
378 set_handle_flash_user_groups = lambda: h.flash(
379 _('Detached %s user groups') % len(_user_groups),
380 category='success')
381 elif do == 'delete':
382 handle_user_groups = 'delete'
383 set_handle_flash_user_groups = lambda: h.flash(
384 _('Deleted %s user groups') % len(_user_groups),
385 category='success')
386
387 old_values = c.user.get_api_data()
388 try:
389 UserModel().delete(c.user, handle_repos=handle_repos,
390 handle_repo_groups=handle_repo_groups,
391 handle_user_groups=handle_user_groups)
392
393 audit_logger.store_web(
394 'user.delete', action_data={'old_data': old_values},
395 user=c.rhodecode_user)
396
397 Session().commit()
398 set_handle_flash_repos()
399 set_handle_flash_repo_groups()
400 set_handle_flash_user_groups()
401 h.flash(_('Successfully deleted user'), category='success')
402 except (UserOwnsReposException, UserOwnsRepoGroupsException,
403 UserOwnsUserGroupsException, DefaultUserException) as e:
404 h.flash(e, category='warning')
405 except Exception:
406 log.exception("Exception during deletion of user")
407 h.flash(_('An error occurred during deletion of user'),
408 category='error')
409 raise HTTPFound(h.route_path('users'))
410
411 @LoginRequired()
412 @HasPermissionAllDecorator('hg.admin')
413 @view_config(
414 route_name='user_edit', request_method='GET',
415 renderer='rhodecode:templates/admin/users/user_edit.mako')
416 def user_edit(self):
417 _ = self.request.translate
418 c = self.load_default_context()
419 c.user = self.db_user
420
421 c.active = 'profile'
422 c.extern_type = c.user.extern_type
423 c.extern_name = c.user.extern_name
424 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
425
426 defaults = c.user.get_dict()
427 defaults.update({'language': c.user.user_data.get('language')})
428
429 data = render(
430 'rhodecode:templates/admin/users/user_edit.mako',
431 self._get_template_context(c), self.request)
432 html = formencode.htmlfill.render(
433 data,
434 defaults=defaults,
435 encoding="UTF-8",
436 force_defaults=False
437 )
438 return Response(html)
439
440 @LoginRequired()
441 @HasPermissionAllDecorator('hg.admin')
442 @view_config(
443 route_name='user_edit_advanced', request_method='GET',
444 renderer='rhodecode:templates/admin/users/user_edit.mako')
445 def user_edit_advanced(self):
446 _ = self.request.translate
447 c = self.load_default_context()
448
449 user_id = self.db_user_id
450 c.user = self.db_user
451
452 c.active = 'advanced'
453 c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id)
454 c.personal_repo_group_name = RepoGroupModel()\
455 .get_personal_group_name(c.user)
456
457 c.user_to_review_rules = sorted(
458 (x.user for x in c.user.user_review_rules),
459 key=lambda u: u.username.lower())
460
461 c.first_admin = User.get_first_super_admin()
462 defaults = c.user.get_dict()
463
464 # Interim workaround if the user participated on any pull requests as a
465 # reviewer.
466 has_review = len(c.user.reviewer_pull_requests)
467 c.can_delete_user = not has_review
468 c.can_delete_user_message = ''
469 inactive_link = h.link_to(
470 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active'))
471 if has_review == 1:
472 c.can_delete_user_message = h.literal(_(
473 'The user participates as reviewer in {} pull request and '
474 'cannot be deleted. \nYou can set the user to '
475 '"{}" instead of deleting it.').format(
476 has_review, inactive_link))
477 elif has_review:
478 c.can_delete_user_message = h.literal(_(
479 'The user participates as reviewer in {} pull requests and '
480 'cannot be deleted. \nYou can set the user to '
481 '"{}" instead of deleting it.').format(
482 has_review, inactive_link))
483
484 data = render(
485 'rhodecode:templates/admin/users/user_edit.mako',
486 self._get_template_context(c), self.request)
487 html = formencode.htmlfill.render(
488 data,
489 defaults=defaults,
490 encoding="UTF-8",
491 force_defaults=False
492 )
493 return Response(html)
494
495 @LoginRequired()
496 @HasPermissionAllDecorator('hg.admin')
497 @view_config(
498 route_name='user_edit_global_perms', request_method='GET',
499 renderer='rhodecode:templates/admin/users/user_edit.mako')
500 def user_edit_global_perms(self):
501 _ = self.request.translate
502 c = self.load_default_context()
503 c.user = self.db_user
504
505 c.active = 'global_perms'
506
507 c.default_user = User.get_default_user()
508 defaults = c.user.get_dict()
509 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
510 defaults.update(c.default_user.get_default_perms())
511 defaults.update(c.user.get_default_perms())
512
513 data = render(
514 'rhodecode:templates/admin/users/user_edit.mako',
515 self._get_template_context(c), self.request)
516 html = formencode.htmlfill.render(
517 data,
518 defaults=defaults,
519 encoding="UTF-8",
520 force_defaults=False
521 )
522 return Response(html)
523
524 @LoginRequired()
525 @HasPermissionAllDecorator('hg.admin')
526 @CSRFRequired()
527 @view_config(
528 route_name='user_edit_global_perms_update', request_method='POST',
529 renderer='rhodecode:templates/admin/users/user_edit.mako')
530 def user_edit_global_perms_update(self):
531 _ = self.request.translate
532 c = self.load_default_context()
533
534 user_id = self.db_user_id
535 c.user = self.db_user
536
537 c.active = 'global_perms'
538 try:
539 # first stage that verifies the checkbox
540 _form = UserIndividualPermissionsForm()
541 form_result = _form.to_python(dict(self.request.POST))
542 inherit_perms = form_result['inherit_default_permissions']
543 c.user.inherit_default_permissions = inherit_perms
544 Session().add(c.user)
545
546 if not inherit_perms:
547 # only update the individual ones if we un check the flag
548 _form = UserPermissionsForm(
549 [x[0] for x in c.repo_create_choices],
550 [x[0] for x in c.repo_create_on_write_choices],
551 [x[0] for x in c.repo_group_create_choices],
552 [x[0] for x in c.user_group_create_choices],
553 [x[0] for x in c.fork_choices],
554 [x[0] for x in c.inherit_default_permission_choices])()
555
556 form_result = _form.to_python(dict(self.request.POST))
557 form_result.update({'perm_user_id': c.user.user_id})
558
559 PermissionModel().update_user_permissions(form_result)
560
561 # TODO(marcink): implement global permissions
562 # audit_log.store_web('user.edit.permissions')
563
564 Session().commit()
565 h.flash(_('User global permissions updated successfully'),
566 category='success')
567
568 except formencode.Invalid as errors:
569 data = render(
570 'rhodecode:templates/admin/users/user_edit.mako',
571 self._get_template_context(c), self.request)
572 html = formencode.htmlfill.render(
573 data,
574 defaults=errors.value,
575 errors=errors.error_dict or {},
576 prefix_error=False,
577 encoding="UTF-8",
578 force_defaults=False
579 )
580 return Response(html)
581 except Exception:
582 log.exception("Exception during permissions saving")
583 h.flash(_('An error occurred during permissions saving'),
584 category='error')
585 raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id))
586
587 @LoginRequired()
588 @HasPermissionAllDecorator('hg.admin')
589 @CSRFRequired()
590 @view_config(
591 route_name='user_force_password_reset', request_method='POST',
592 renderer='rhodecode:templates/admin/users/user_edit.mako')
593 def user_force_password_reset(self):
594 """
595 toggle reset password flag for this user
596 """
597 _ = self.request.translate
598 c = self.load_default_context()
599
600 user_id = self.db_user_id
601 c.user = self.db_user
602
603 try:
604 old_value = c.user.user_data.get('force_password_change')
605 c.user.update_userdata(force_password_change=not old_value)
606
607 if old_value:
608 msg = _('Force password change disabled for user')
609 audit_logger.store_web(
610 'user.edit.password_reset.disabled',
611 user=c.rhodecode_user)
612 else:
613 msg = _('Force password change enabled for user')
614 audit_logger.store_web(
615 'user.edit.password_reset.enabled',
616 user=c.rhodecode_user)
617
618 Session().commit()
619 h.flash(msg, category='success')
620 except Exception:
621 log.exception("Exception during password reset for user")
622 h.flash(_('An error occurred during password reset for user'),
623 category='error')
624
625 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
626
627 @LoginRequired()
628 @HasPermissionAllDecorator('hg.admin')
629 @CSRFRequired()
630 @view_config(
631 route_name='user_create_personal_repo_group', request_method='POST',
632 renderer='rhodecode:templates/admin/users/user_edit.mako')
633 def user_create_personal_repo_group(self):
634 """
635 Create personal repository group for this user
636 """
637 from rhodecode.model.repo_group import RepoGroupModel
638
639 _ = self.request.translate
640 c = self.load_default_context()
641
642 user_id = self.db_user_id
643 c.user = self.db_user
644
645 personal_repo_group = RepoGroup.get_user_personal_repo_group(
646 c.user.user_id)
647 if personal_repo_group:
648 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
649
650 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
651 c.user)
652 named_personal_group = RepoGroup.get_by_group_name(
653 personal_repo_group_name)
654 try:
655
656 if named_personal_group and named_personal_group.user_id == c.user.user_id:
657 # migrate the same named group, and mark it as personal
658 named_personal_group.personal = True
659 Session().add(named_personal_group)
660 Session().commit()
661 msg = _('Linked repository group `%s` as personal' % (
662 personal_repo_group_name,))
663 h.flash(msg, category='success')
664 elif not named_personal_group:
665 RepoGroupModel().create_personal_repo_group(c.user)
666
667 msg = _('Created repository group `%s`' % (
668 personal_repo_group_name,))
669 h.flash(msg, category='success')
670 else:
671 msg = _('Repository group `%s` is already taken' % (
672 personal_repo_group_name,))
673 h.flash(msg, category='warning')
674 except Exception:
675 log.exception("Exception during repository group creation")
676 msg = _(
677 'An error occurred during repository group creation for user')
678 h.flash(msg, category='error')
679 Session().rollback()
680
681 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
682
166 @LoginRequired()
683 @LoginRequired()
167 @HasPermissionAllDecorator('hg.admin')
684 @HasPermissionAllDecorator('hg.admin')
168 @view_config(
685 @view_config(
@@ -171,10 +688,7 b' class AdminUsersView(BaseAppView, DataGr'
171 def auth_tokens(self):
688 def auth_tokens(self):
172 _ = self.request.translate
689 _ = self.request.translate
173 c = self.load_default_context()
690 c = self.load_default_context()
174
691 c.user = self.db_user
175 user_id = self.request.matchdict.get('user_id')
176 c.user = User.get_or_404(user_id)
177 self._redirect_for_default_user(c.user.username)
178
692
179 c.active = 'auth_tokens'
693 c.active = 'auth_tokens'
180
694
@@ -200,10 +714,8 b' class AdminUsersView(BaseAppView, DataGr'
200 _ = self.request.translate
714 _ = self.request.translate
201 c = self.load_default_context()
715 c = self.load_default_context()
202
716
203 user_id = self.request.matchdict.get('user_id')
717 user_id = self.db_user_id
204 c.user = User.get_or_404(user_id)
718 c.user = self.db_user
205
206 self._redirect_for_default_user(c.user.username)
207
719
208 user_data = c.user.get_api_data()
720 user_data = c.user.get_api_data()
209 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
721 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
@@ -233,9 +745,9 b' class AdminUsersView(BaseAppView, DataGr'
233 _ = self.request.translate
745 _ = self.request.translate
234 c = self.load_default_context()
746 c = self.load_default_context()
235
747
236 user_id = self.request.matchdict.get('user_id')
748 user_id = self.db_user_id
237 c.user = User.get_or_404(user_id)
749 c.user = self.db_user
238 self._redirect_for_default_user(c.user.username)
750
239 user_data = c.user.get_api_data()
751 user_data = c.user.get_api_data()
240
752
241 del_auth_token = self.request.POST.get('del_auth_token')
753 del_auth_token = self.request.POST.get('del_auth_token')
@@ -262,10 +774,7 b' class AdminUsersView(BaseAppView, DataGr'
262 def ssh_keys(self):
774 def ssh_keys(self):
263 _ = self.request.translate
775 _ = self.request.translate
264 c = self.load_default_context()
776 c = self.load_default_context()
265
777 c.user = self.db_user
266 user_id = self.request.matchdict.get('user_id')
267 c.user = User.get_or_404(user_id)
268 self._redirect_for_default_user(c.user.username)
269
778
270 c.active = 'ssh_keys'
779 c.active = 'ssh_keys'
271 c.default_key = self.request.GET.get('default_key')
780 c.default_key = self.request.GET.get('default_key')
@@ -281,9 +790,7 b' class AdminUsersView(BaseAppView, DataGr'
281 _ = self.request.translate
790 _ = self.request.translate
282 c = self.load_default_context()
791 c = self.load_default_context()
283
792
284 user_id = self.request.matchdict.get('user_id')
793 c.user = self.db_user
285 c.user = User.get_or_404(user_id)
286 self._redirect_for_default_user(c.user.username)
287
794
288 c.active = 'ssh_keys_generate'
795 c.active = 'ssh_keys_generate'
289 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
796 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
@@ -300,10 +807,8 b' class AdminUsersView(BaseAppView, DataGr'
300 _ = self.request.translate
807 _ = self.request.translate
301 c = self.load_default_context()
808 c = self.load_default_context()
302
809
303 user_id = self.request.matchdict.get('user_id')
810 user_id = self.db_user_id
304 c.user = User.get_or_404(user_id)
811 c.user = self.db_user
305
306 self._redirect_for_default_user(c.user.username)
307
812
308 user_data = c.user.get_api_data()
813 user_data = c.user.get_api_data()
309 key_data = self.request.POST.get('key_data')
814 key_data = self.request.POST.get('key_data')
@@ -353,9 +858,9 b' class AdminUsersView(BaseAppView, DataGr'
353 _ = self.request.translate
858 _ = self.request.translate
354 c = self.load_default_context()
859 c = self.load_default_context()
355
860
356 user_id = self.request.matchdict.get('user_id')
861 user_id = self.db_user_id
357 c.user = User.get_or_404(user_id)
862 c.user = self.db_user
358 self._redirect_for_default_user(c.user.username)
863
359 user_data = c.user.get_api_data()
864 user_data = c.user.get_api_data()
360
865
361 del_ssh_key = self.request.POST.get('del_ssh_key')
866 del_ssh_key = self.request.POST.get('del_ssh_key')
@@ -384,10 +889,7 b' class AdminUsersView(BaseAppView, DataGr'
384 def emails(self):
889 def emails(self):
385 _ = self.request.translate
890 _ = self.request.translate
386 c = self.load_default_context()
891 c = self.load_default_context()
387
892 c.user = self.db_user
388 user_id = self.request.matchdict.get('user_id')
389 c.user = User.get_or_404(user_id)
390 self._redirect_for_default_user(c.user.username)
391
893
392 c.active = 'emails'
894 c.active = 'emails'
393 c.user_email_map = UserEmailMap.query() \
895 c.user_email_map = UserEmailMap.query() \
@@ -404,22 +906,26 b' class AdminUsersView(BaseAppView, DataGr'
404 _ = self.request.translate
906 _ = self.request.translate
405 c = self.load_default_context()
907 c = self.load_default_context()
406
908
407 user_id = self.request.matchdict.get('user_id')
909 user_id = self.db_user_id
408 c.user = User.get_or_404(user_id)
910 c.user = self.db_user
409 self._redirect_for_default_user(c.user.username)
410
911
411 email = self.request.POST.get('new_email')
912 email = self.request.POST.get('new_email')
412 user_data = c.user.get_api_data()
913 user_data = c.user.get_api_data()
413 try:
914 try:
414 UserModel().add_extra_email(c.user.user_id, email)
915 UserModel().add_extra_email(c.user.user_id, email)
415 audit_logger.store_web(
916 audit_logger.store_web(
416 'user.edit.email.add', action_data={'email': email, 'user': user_data},
917 'user.edit.email.add',
918 action_data={'email': email, 'user': user_data},
417 user=self._rhodecode_user)
919 user=self._rhodecode_user)
418 Session().commit()
920 Session().commit()
419 h.flash(_("Added new email address `%s` for user account") % email,
921 h.flash(_("Added new email address `%s` for user account") % email,
420 category='success')
922 category='success')
421 except formencode.Invalid as error:
923 except formencode.Invalid as error:
422 h.flash(h.escape(error.error_dict['email']), category='error')
924 h.flash(h.escape(error.error_dict['email']), category='error')
925 except IntegrityError:
926 log.warning("Email %s already exists", email)
927 h.flash(_('Email `{}` is already registered for another user.').format(email),
928 category='error')
423 except Exception:
929 except Exception:
424 log.exception("Exception during email saving")
930 log.exception("Exception during email saving")
425 h.flash(_('An error occurred during email saving'),
931 h.flash(_('An error occurred during email saving'),
@@ -435,9 +941,8 b' class AdminUsersView(BaseAppView, DataGr'
435 _ = self.request.translate
941 _ = self.request.translate
436 c = self.load_default_context()
942 c = self.load_default_context()
437
943
438 user_id = self.request.matchdict.get('user_id')
944 user_id = self.db_user_id
439 c.user = User.get_or_404(user_id)
945 c.user = self.db_user
440 self._redirect_for_default_user(c.user.username)
441
946
442 email_id = self.request.POST.get('del_email_id')
947 email_id = self.request.POST.get('del_email_id')
443 user_model = UserModel()
948 user_model = UserModel()
@@ -446,7 +951,8 b' class AdminUsersView(BaseAppView, DataGr'
446 user_data = c.user.get_api_data()
951 user_data = c.user.get_api_data()
447 user_model.delete_extra_email(c.user.user_id, email_id)
952 user_model.delete_extra_email(c.user.user_id, email_id)
448 audit_logger.store_web(
953 audit_logger.store_web(
449 'user.edit.email.delete', action_data={'email': email, 'user': user_data},
954 'user.edit.email.delete',
955 action_data={'email': email, 'user': user_data},
450 user=self._rhodecode_user)
956 user=self._rhodecode_user)
451 Session().commit()
957 Session().commit()
452 h.flash(_("Removed email address from user account"),
958 h.flash(_("Removed email address from user account"),
@@ -461,10 +967,7 b' class AdminUsersView(BaseAppView, DataGr'
461 def ips(self):
967 def ips(self):
462 _ = self.request.translate
968 _ = self.request.translate
463 c = self.load_default_context()
969 c = self.load_default_context()
464
970 c.user = self.db_user
465 user_id = self.request.matchdict.get('user_id')
466 c.user = User.get_or_404(user_id)
467 self._redirect_for_default_user(c.user.username)
468
971
469 c.active = 'ips'
972 c.active = 'ips'
470 c.user_ip_map = UserIpMap.query() \
973 c.user_ip_map = UserIpMap.query() \
@@ -481,14 +984,14 b' class AdminUsersView(BaseAppView, DataGr'
481 @CSRFRequired()
984 @CSRFRequired()
482 @view_config(
985 @view_config(
483 route_name='edit_user_ips_add', request_method='POST')
986 route_name='edit_user_ips_add', request_method='POST')
987 # NOTE(marcink): this view is allowed for default users, as we can
988 # edit their IP white list
484 def ips_add(self):
989 def ips_add(self):
485 _ = self.request.translate
990 _ = self.request.translate
486 c = self.load_default_context()
991 c = self.load_default_context()
487
992
488 user_id = self.request.matchdict.get('user_id')
993 user_id = self.db_user_id
489 c.user = User.get_or_404(user_id)
994 c.user = self.db_user
490 # NOTE(marcink): this view is allowed for default users, as we can
491 # edit their IP white list
492
995
493 user_model = UserModel()
996 user_model = UserModel()
494 desc = self.request.POST.get('description')
997 desc = self.request.POST.get('description')
@@ -506,7 +1009,8 b' class AdminUsersView(BaseAppView, DataGr'
506 try:
1009 try:
507 user_model.add_extra_ip(c.user.user_id, ip, desc)
1010 user_model.add_extra_ip(c.user.user_id, ip, desc)
508 audit_logger.store_web(
1011 audit_logger.store_web(
509 'user.edit.ip.add', action_data={'ip': ip, 'user': user_data},
1012 'user.edit.ip.add',
1013 action_data={'ip': ip, 'user': user_data},
510 user=self._rhodecode_user)
1014 user=self._rhodecode_user)
511 Session().commit()
1015 Session().commit()
512 added.append(ip)
1016 added.append(ip)
@@ -531,14 +1035,14 b' class AdminUsersView(BaseAppView, DataGr'
531 @CSRFRequired()
1035 @CSRFRequired()
532 @view_config(
1036 @view_config(
533 route_name='edit_user_ips_delete', request_method='POST')
1037 route_name='edit_user_ips_delete', request_method='POST')
1038 # NOTE(marcink): this view is allowed for default users, as we can
1039 # edit their IP white list
534 def ips_delete(self):
1040 def ips_delete(self):
535 _ = self.request.translate
1041 _ = self.request.translate
536 c = self.load_default_context()
1042 c = self.load_default_context()
537
1043
538 user_id = self.request.matchdict.get('user_id')
1044 user_id = self.db_user_id
539 c.user = User.get_or_404(user_id)
1045 c.user = self.db_user
540 # NOTE(marcink): this view is allowed for default users, as we can
541 # edit their IP white list
542
1046
543 ip_id = self.request.POST.get('del_ip_id')
1047 ip_id = self.request.POST.get('del_ip_id')
544 user_model = UserModel()
1048 user_model = UserModel()
@@ -563,11 +1067,9 b' class AdminUsersView(BaseAppView, DataGr'
563 renderer='rhodecode:templates/admin/users/user_edit.mako')
1067 renderer='rhodecode:templates/admin/users/user_edit.mako')
564 def groups_management(self):
1068 def groups_management(self):
565 c = self.load_default_context()
1069 c = self.load_default_context()
1070 c.user = self.db_user
1071 c.data = c.user.group_member
566
1072
567 user_id = self.request.matchdict.get('user_id')
568 c.user = User.get_or_404(user_id)
569 c.data = c.user.group_member
570 self._redirect_for_default_user(c.user.username)
571 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
1073 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
572 for group in c.user.group_member]
1074 for group in c.user.group_member]
573 c.groups = json.dumps(groups)
1075 c.groups = json.dumps(groups)
@@ -584,9 +1086,8 b' class AdminUsersView(BaseAppView, DataGr'
584 _ = self.request.translate
1086 _ = self.request.translate
585 c = self.load_default_context()
1087 c = self.load_default_context()
586
1088
587 user_id = self.request.matchdict.get('user_id')
1089 user_id = self.db_user_id
588 c.user = User.get_or_404(user_id)
1090 c.user = self.db_user
589 self._redirect_for_default_user(c.user.username)
590
1091
591 user_groups = set(self.request.POST.getall('users_group_id'))
1092 user_groups = set(self.request.POST.getall('users_group_id'))
592 user_groups_objects = []
1093 user_groups_objects = []
@@ -595,7 +1096,25 b' class AdminUsersView(BaseAppView, DataGr'
595 user_groups_objects.append(
1096 user_groups_objects.append(
596 UserGroupModel().get_group(safe_int(ugid)))
1097 UserGroupModel().get_group(safe_int(ugid)))
597 user_group_model = UserGroupModel()
1098 user_group_model = UserGroupModel()
598 user_group_model.change_groups(c.user, user_groups_objects)
1099 added_to_groups, removed_from_groups = \
1100 user_group_model.change_groups(c.user, user_groups_objects)
1101
1102 user_data = c.user.get_api_data()
1103 for user_group_id in added_to_groups:
1104 user_group = UserGroup.get(user_group_id)
1105 old_values = user_group.get_api_data()
1106 audit_logger.store_web(
1107 'user_group.edit.member.add',
1108 action_data={'user': user_data, 'old_data': old_values},
1109 user=self._rhodecode_user)
1110
1111 for user_group_id in removed_from_groups:
1112 user_group = UserGroup.get(user_group_id)
1113 old_values = user_group.get_api_data()
1114 audit_logger.store_web(
1115 'user_group.edit.member.delete',
1116 action_data={'user': user_data, 'old_data': old_values},
1117 user=self._rhodecode_user)
599
1118
600 Session().commit()
1119 Session().commit()
601 c.active = 'user_groups_management'
1120 c.active = 'user_groups_management'
@@ -612,10 +1131,8 b' class AdminUsersView(BaseAppView, DataGr'
612 def user_audit_logs(self):
1131 def user_audit_logs(self):
613 _ = self.request.translate
1132 _ = self.request.translate
614 c = self.load_default_context()
1133 c = self.load_default_context()
1134 c.user = self.db_user
615
1135
616 user_id = self.request.matchdict.get('user_id')
617 c.user = User.get_or_404(user_id)
618 self._redirect_for_default_user(c.user.username)
619 c.active = 'audit'
1136 c.active = 'audit'
620
1137
621 p = safe_int(self.request.GET.get('page', 1), 1)
1138 p = safe_int(self.request.GET.get('page', 1), 1)
@@ -641,10 +1158,7 b' class AdminUsersView(BaseAppView, DataGr'
641 def user_perms_summary(self):
1158 def user_perms_summary(self):
642 _ = self.request.translate
1159 _ = self.request.translate
643 c = self.load_default_context()
1160 c = self.load_default_context()
644
1161 c.user = self.db_user
645 user_id = self.request.matchdict.get('user_id')
646 c.user = User.get_or_404(user_id)
647 self._redirect_for_default_user(c.user.username)
648
1162
649 c.active = 'perms_summary'
1163 c.active = 'perms_summary'
650 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1164 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
@@ -658,11 +1172,6 b' class AdminUsersView(BaseAppView, DataGr'
658 renderer='json_ext')
1172 renderer='json_ext')
659 def user_perms_summary_json(self):
1173 def user_perms_summary_json(self):
660 self.load_default_context()
1174 self.load_default_context()
661
1175 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
662 user_id = self.request.matchdict.get('user_id')
663 user = User.get_or_404(user_id)
664 self._redirect_for_default_user(user.username)
665
666 perm_user = user.AuthUser(ip_addr=self.request.remote_addr)
667
1176
668 return perm_user.permissions
1177 return perm_user.permissions
@@ -115,7 +115,6 b' def load_environment(global_conf, app_co'
115 'secret': config.get('channelstream.secret')
115 'secret': config.get('channelstream.secret')
116 }
116 }
117
117
118 set_available_permissions(config)
119 db_cfg = make_db_config(clear_session=True)
118 db_cfg = make_db_config(clear_session=True)
120
119
121 repos_path = list(db_cfg.items('paths'))[0][1]
120 repos_path = list(db_cfg.items('paths'))[0][1]
@@ -178,5 +177,6 b' def load_pyramid_environment(global_conf'
178 log_level=settings['vcs.server.log_level'])
177 log_level=settings['vcs.server.log_level'])
179
178
180 utils.configure_vcs(settings)
179 utils.configure_vcs(settings)
180
181 if vcs_server_enabled:
181 if vcs_server_enabled:
182 connect_vcs(vcs_server_uri, utils.get_vcs_server_protocol(settings))
182 connect_vcs(vcs_server_uri, utils.get_vcs_server_protocol(settings))
@@ -41,6 +41,7 b' import rhodecode'
41
41
42 from rhodecode.model import meta
42 from rhodecode.model import meta
43 from rhodecode.config import patches
43 from rhodecode.config import patches
44 from rhodecode.config import utils as config_utils
44 from rhodecode.config.routing import STATIC_FILE_PREFIX
45 from rhodecode.config.routing import STATIC_FILE_PREFIX
45 from rhodecode.config.environment import (
46 from rhodecode.config.environment import (
46 load_environment, load_pyramid_environment)
47 load_environment, load_pyramid_environment)
@@ -56,7 +57,7 b' from rhodecode.lib.plugins.utils import '
56 from rhodecode.lib.utils2 import aslist as rhodecode_aslist, AttributeDict
57 from rhodecode.lib.utils2 import aslist as rhodecode_aslist, AttributeDict
57 from rhodecode.subscribers import (
58 from rhodecode.subscribers import (
58 scan_repositories_if_enabled, write_js_routes_if_enabled,
59 scan_repositories_if_enabled, write_js_routes_if_enabled,
59 write_metadata_if_needed)
60 write_metadata_if_needed, inject_app_settings)
60
61
61
62
62 log = logging.getLogger(__name__)
63 log = logging.getLogger(__name__)
@@ -146,11 +147,12 b' def make_pyramid_app(global_config, **se'
146 settings_pylons = settings.copy()
147 settings_pylons = settings.copy()
147
148
148 sanitize_settings_and_apply_defaults(settings)
149 sanitize_settings_and_apply_defaults(settings)
150
149 config = Configurator(settings=settings)
151 config = Configurator(settings=settings)
152 load_pyramid_environment(global_config, settings)
153
150 add_pylons_compat_data(config.registry, global_config, settings_pylons)
154 add_pylons_compat_data(config.registry, global_config, settings_pylons)
151
155
152 load_pyramid_environment(global_config, settings)
153
154 includeme_first(config)
156 includeme_first(config)
155 includeme(config)
157 includeme(config)
156
158
@@ -315,6 +317,7 b' def includeme(config):'
315 settings['default_locale_name'] = settings.get('lang', 'en')
317 settings['default_locale_name'] = settings.get('lang', 'en')
316
318
317 # Add subscribers.
319 # Add subscribers.
320 config.add_subscriber(inject_app_settings, ApplicationCreated)
318 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
321 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
319 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
322 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
320 config.add_subscriber(write_js_routes_if_enabled, ApplicationCreated)
323 config.add_subscriber(write_js_routes_if_enabled, ApplicationCreated)
@@ -472,6 +475,9 b' def sanitize_settings_and_apply_defaults'
472 _sanitize_appenlight_settings(settings)
475 _sanitize_appenlight_settings(settings)
473 _sanitize_vcs_settings(settings)
476 _sanitize_vcs_settings(settings)
474
477
478 # configure instance id
479 config_utils.set_instance_id(settings)
480
475 return settings
481 return settings
476
482
477
483
@@ -219,37 +219,6 b' def make_map(config):'
219 'function': check_group},
219 'function': check_group},
220 requirements=URL_NAME_REQUIREMENTS)
220 requirements=URL_NAME_REQUIREMENTS)
221
221
222 # ADMIN USER ROUTES
223 with rmap.submapper(path_prefix=ADMIN_PREFIX,
224 controller='admin/users') as m:
225 m.connect('users', '/users',
226 action='create', conditions={'method': ['POST']})
227 m.connect('new_user', '/users/new',
228 action='new', conditions={'method': ['GET']})
229 m.connect('update_user', '/users/{user_id}',
230 action='update', conditions={'method': ['PUT']})
231 m.connect('delete_user', '/users/{user_id}',
232 action='delete', conditions={'method': ['DELETE']})
233 m.connect('edit_user', '/users/{user_id}/edit',
234 action='edit', conditions={'method': ['GET']}, jsroute=True)
235 m.connect('user', '/users/{user_id}',
236 action='show', conditions={'method': ['GET']})
237 m.connect('force_password_reset_user', '/users/{user_id}/password_reset',
238 action='reset_password', conditions={'method': ['POST']})
239 m.connect('create_personal_repo_group', '/users/{user_id}/create_repo_group',
240 action='create_personal_repo_group', conditions={'method': ['POST']})
241
242 # EXTRAS USER ROUTES
243 m.connect('edit_user_advanced', '/users/{user_id}/edit/advanced',
244 action='edit_advanced', conditions={'method': ['GET']})
245 m.connect('edit_user_advanced', '/users/{user_id}/edit/advanced',
246 action='update_advanced', conditions={'method': ['PUT']})
247
248 m.connect('edit_user_global_perms', '/users/{user_id}/edit/global_permissions',
249 action='edit_global_perms', conditions={'method': ['GET']})
250 m.connect('edit_user_global_perms', '/users/{user_id}/edit/global_permissions',
251 action='update_global_perms', conditions={'method': ['PUT']})
252
253 # ADMIN SETTINGS ROUTES
222 # ADMIN SETTINGS ROUTES
254 with rmap.submapper(path_prefix=ADMIN_PREFIX,
223 with rmap.submapper(path_prefix=ADMIN_PREFIX,
255 controller='admin/settings') as m:
224 controller='admin/settings') as m:
@@ -339,5 +308,4 b' def make_map(config):'
339 m.connect('my_account_password', '/my_account/password',
308 m.connect('my_account_password', '/my_account/password',
340 action='my_account_password', conditions={'method': ['GET']})
309 action='my_account_password', conditions={'method': ['GET']})
341
310
342
343 return rmap
311 return rmap
@@ -1012,13 +1012,16 b' class AuthUser(object):'
1012 log.debug('No data in %s that could been used to log in', self)
1012 log.debug('No data in %s that could been used to log in', self)
1013
1013
1014 if not is_user_loaded:
1014 if not is_user_loaded:
1015 log.debug('Failed to load user. Fallback to default user')
1015 log.debug(
1016 'Failed to load user. Fallback to default user %s', anon_user)
1016 # if we cannot authenticate user try anonymous
1017 # if we cannot authenticate user try anonymous
1017 if anon_user.active:
1018 if anon_user.active:
1019 log.debug('default user is active, using it as a session user')
1018 user_model.fill_data(self, user_id=anon_user.user_id)
1020 user_model.fill_data(self, user_id=anon_user.user_id)
1019 # then we set this user is logged in
1021 # then we set this user is logged in
1020 self.is_authenticated = True
1022 self.is_authenticated = True
1021 else:
1023 else:
1024 log.debug('default user is NOT active')
1022 # in case of disabled anonymous user we reset some of the
1025 # in case of disabled anonymous user we reset some of the
1023 # parameters so such user is "corrupted", skipping the fill_data
1026 # parameters so such user is "corrupted", skipping the fill_data
1024 for attr in ['user_id', 'username', 'admin', 'active']:
1027 for attr in ['user_id', 'username', 'admin', 'active']:
@@ -1277,25 +1280,26 b' class AuthUser(object):'
1277 return _set or set(['0.0.0.0/0', '::/0'])
1280 return _set or set(['0.0.0.0/0', '::/0'])
1278
1281
1279
1282
1280 def set_available_permissions(config):
1283 def set_available_permissions(settings):
1281 """
1284 """
1282 This function will propagate pylons globals with all available defined
1285 This function will propagate pyramid settings with all available defined
1283 permission given in db. We don't want to check each time from db for new
1286 permission given in db. We don't want to check each time from db for new
1284 permissions since adding a new permission also requires application restart
1287 permissions since adding a new permission also requires application restart
1285 ie. to decorate new views with the newly created permission
1288 ie. to decorate new views with the newly created permission
1286
1289
1287 :param config: current pylons config instance
1290 :param settings: current pyramid registry.settings
1288
1291
1289 """
1292 """
1290 log.info('getting information about all available permissions')
1293 log.debug('auth: getting information about all available permissions')
1291 try:
1294 try:
1292 sa = meta.Session
1295 sa = meta.Session
1293 all_perms = sa.query(Permission).all()
1296 all_perms = sa.query(Permission).all()
1294 config['available_permissions'] = [x.permission_name for x in all_perms]
1297 settings.setdefault('available_permissions',
1298 [x.permission_name for x in all_perms])
1299 log.debug('auth: set available permissions')
1295 except Exception:
1300 except Exception:
1296 log.error(traceback.format_exc())
1301 log.exception('Failed to fetch permissions from the database.')
1297 finally:
1302 raise
1298 meta.Session.remove()
1299
1303
1300
1304
1301 def get_csrf_token(session, force_new=False, save_if_missing=True):
1305 def get_csrf_token(session, force_new=False, save_if_missing=True):
@@ -681,6 +681,17 b' class User(Base, BaseModel):'
681 return 'NO_FEED_TOKEN_AVAILABLE'
681 return 'NO_FEED_TOKEN_AVAILABLE'
682
682
683 @classmethod
683 @classmethod
684 def get(cls, user_id, cache=False):
685 if not user_id:
686 return
687
688 user = cls.query()
689 if cache:
690 user = user.options(
691 FromCache("sql_cache_short", "get_users_%s" % user_id))
692 return user.get(user_id)
693
694 @classmethod
684 def extra_valid_auth_tokens(cls, user, role=None):
695 def extra_valid_auth_tokens(cls, user, role=None):
685 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
696 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
686 .filter(or_(UserApiKeys.expires == -1,
697 .filter(or_(UserApiKeys.expires == -1,
@@ -1341,6 +1352,9 b' class UserGroup(Base, BaseModel):'
1341
1352
1342 @classmethod
1353 @classmethod
1343 def get(cls, user_group_id, cache=False):
1354 def get(cls, user_group_id, cache=False):
1355 if not user_group_id:
1356 return
1357
1344 user_group = cls.query()
1358 user_group = cls.query()
1345 if cache:
1359 if cache:
1346 user_group = user_group.options(
1360 user_group = user_group.options(
@@ -554,16 +554,22 b' class UserGroupModel(BaseModel):'
554 groups_to_remove = current_groups - groups
554 groups_to_remove = current_groups - groups
555 groups_to_add = groups - current_groups
555 groups_to_add = groups - current_groups
556
556
557 removed_from_groups = []
558 added_to_groups = []
557 for gr in groups_to_remove:
559 for gr in groups_to_remove:
558 log.debug('Removing user %s from user group %s',
560 log.debug('Removing user %s from user group %s',
559 user.username, gr.users_group_name)
561 user.username, gr.users_group_name)
562 removed_from_groups.append(gr.users_group_id)
560 self.remove_user_from_group(gr.users_group_name, user.username)
563 self.remove_user_from_group(gr.users_group_name, user.username)
561 for gr in groups_to_add:
564 for gr in groups_to_add:
562 log.debug('Adding user %s to user group %s',
565 log.debug('Adding user %s to user group %s',
563 user.username, gr.users_group_name)
566 user.username, gr.users_group_name)
567 added_to_groups.append(gr.users_group_id)
564 UserGroupModel().add_user_to_group(
568 UserGroupModel().add_user_to_group(
565 gr.users_group_name, user.username)
569 gr.users_group_name, user.username)
566
570
571 return added_to_groups, removed_from_groups
572
567 def _serialize_user_group(self, user_group):
573 def _serialize_user_group(self, user_group):
568 import rhodecode.lib.helpers as h
574 import rhodecode.lib.helpers as h
569 return {
575 return {
@@ -12,7 +12,6 b''
12 ******************************************************************************/
12 ******************************************************************************/
13 function registerRCRoutes() {
13 function registerRCRoutes() {
14 // routes registration
14 // routes registration
15 pyroutes.register('edit_user', '/_admin/users/%(user_id)s/edit', ['user_id']);
16 pyroutes.register('favicon', '/favicon.ico', []);
15 pyroutes.register('favicon', '/favicon.ico', []);
17 pyroutes.register('robots', '/robots.txt', []);
16 pyroutes.register('robots', '/robots.txt', []);
18 pyroutes.register('auth_home', '/_admin/auth*traverse', []);
17 pyroutes.register('auth_home', '/_admin/auth*traverse', []);
@@ -66,6 +65,16 b' function registerRCRoutes() {'
66 pyroutes.register('admin_permissions_ssh_keys_update', '/_admin/permissions/ssh_keys/update', []);
65 pyroutes.register('admin_permissions_ssh_keys_update', '/_admin/permissions/ssh_keys/update', []);
67 pyroutes.register('users', '/_admin/users', []);
66 pyroutes.register('users', '/_admin/users', []);
68 pyroutes.register('users_data', '/_admin/users_data', []);
67 pyroutes.register('users_data', '/_admin/users_data', []);
68 pyroutes.register('users_create', '/_admin/users/create', []);
69 pyroutes.register('users_new', '/_admin/users/new', []);
70 pyroutes.register('user_edit', '/_admin/users/%(user_id)s/edit', ['user_id']);
71 pyroutes.register('user_edit_advanced', '/_admin/users/%(user_id)s/edit/advanced', ['user_id']);
72 pyroutes.register('user_edit_global_perms', '/_admin/users/%(user_id)s/edit/global_permissions', ['user_id']);
73 pyroutes.register('user_edit_global_perms_update', '/_admin/users/%(user_id)s/edit/global_permissions/update', ['user_id']);
74 pyroutes.register('user_update', '/_admin/users/%(user_id)s/update', ['user_id']);
75 pyroutes.register('user_delete', '/_admin/users/%(user_id)s/delete', ['user_id']);
76 pyroutes.register('user_force_password_reset', '/_admin/users/%(user_id)s/password_reset', ['user_id']);
77 pyroutes.register('user_create_personal_repo_group', '/_admin/users/%(user_id)s/create_repo_group', ['user_id']);
69 pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
78 pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
70 pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
79 pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
71 pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']);
80 pyroutes.register('edit_user_auth_tokens_delete', '/_admin/users/%(user_id)s/edit/auth_tokens/delete', ['user_id']);
@@ -35,6 +35,7 b' from threading import Thread'
35
35
36 from rhodecode.translation import _ as tsf
36 from rhodecode.translation import _ as tsf
37 from rhodecode.config.jsroutes import generate_jsroutes_content
37 from rhodecode.config.jsroutes import generate_jsroutes_content
38 from rhodecode.lib import auth
38
39
39 import rhodecode
40 import rhodecode
40
41
@@ -140,6 +141,12 b' def add_pylons_context(event):'
140 pylons.tmpl_context._push_object(context)
141 pylons.tmpl_context._push_object(context)
141
142
142
143
144 def inject_app_settings(event):
145 settings = event.app.registry.settings
146 # inject info about available permissions
147 auth.set_available_permissions(settings)
148
149
143 def scan_repositories_if_enabled(event):
150 def scan_repositories_if_enabled(event):
144 """
151 """
145 This is subscribed to the `pyramid.events.ApplicationCreated` event. It
152 This is subscribed to the `pyramid.events.ApplicationCreated` event. It
@@ -102,7 +102,6 b' var select2Options = {'
102 };
102 };
103 $("#role").select2(select2Options);
103 $("#role").select2(select2Options);
104
104
105
106 var preloadData = {
105 var preloadData = {
107 results: [
106 results: [
108 % for entry in c.lifetime_values:
107 % for entry in c.lifetime_values:
@@ -77,7 +77,7 b''
77 <td id="member_user_${user.user_id}" class="td-author">
77 <td id="member_user_${user.user_id}" class="td-author">
78 <div class="group_member">
78 <div class="group_member">
79 ${base.gravatar(user.email, 16)}
79 ${base.gravatar(user.email, 16)}
80 <span class="username user">${h.link_to(h.person(user), h.url( 'edit_user',user_id=user.user_id))}</span>
80 <span class="username user">${h.link_to(h.person(user), h.route_path('user_edit',user_id=user.user_id))}</span>
81 <input type="hidden" name="__start__" value="member:mapping">
81 <input type="hidden" name="__start__" value="member:mapping">
82 <input type="hidden" name="member_user_id" value="${user.user_id}">
82 <input type="hidden" name="member_user_id" value="${user.user_id}">
83 <input type="hidden" name="type" value="existing" id="member_${user.user_id}">
83 <input type="hidden" name="type" value="existing" id="member_${user.user_id}">
@@ -134,7 +134,7 b''
134 function addMember(user, fromUserGroup) {
134 function addMember(user, fromUserGroup) {
135 var gravatar = user.icon_link;
135 var gravatar = user.icon_link;
136 var username = user.value_display;
136 var username = user.value_display;
137 var userLink = pyroutes.url('edit_user', {"user_id": user.id});
137 var userLink = pyroutes.url('user_edit', {"user_id": user.id});
138 var uid = user.id;
138 var uid = user.id;
139
139
140 if (fromUserGroup) {
140 if (fromUserGroup) {
@@ -26,7 +26,7 b''
26 ${self.breadcrumbs()}
26 ${self.breadcrumbs()}
27 </div>
27 </div>
28 <!-- end box / title -->
28 <!-- end box / title -->
29 ${h.secure_form(h.url('users'))}
29 ${h.secure_form(h.route_path('users_create'), request=request)}
30 <div class="form">
30 <div class="form">
31 <!-- fields -->
31 <!-- fields -->
32 <div class="fields">
32 <div class="fields">
@@ -35,11 +35,11 b''
35 <div class="sidebar-col-wrapper">
35 <div class="sidebar-col-wrapper">
36 <div class="sidebar">
36 <div class="sidebar">
37 <ul class="nav nav-pills nav-stacked">
37 <ul class="nav nav-pills nav-stacked">
38 <li class="${'active' if c.active=='profile' else ''}"><a href="${h.url('edit_user', user_id=c.user.user_id)}">${_('User Profile')}</a></li>
38 <li class="${'active' if c.active=='profile' else ''}"><a href="${h.route_path('user_edit', user_id=c.user.user_id)}">${_('User Profile')}</a></li>
39 <li class="${'active' if c.active=='auth_tokens' else ''}"><a href="${h.route_path('edit_user_auth_tokens', user_id=c.user.user_id)}">${_('Auth tokens')}</a></li>
39 <li class="${'active' if c.active=='auth_tokens' else ''}"><a href="${h.route_path('edit_user_auth_tokens', user_id=c.user.user_id)}">${_('Auth tokens')}</a></li>
40 <li class="${'active' if c.active in ['ssh_keys','ssh_keys_generate'] else ''}"><a href="${h.route_path('edit_user_ssh_keys', user_id=c.user.user_id)}">${_('SSH Keys')}</a></li>
40 <li class="${'active' if c.active in ['ssh_keys','ssh_keys_generate'] else ''}"><a href="${h.route_path('edit_user_ssh_keys', user_id=c.user.user_id)}">${_('SSH Keys')}</a></li>
41 <li class="${'active' if c.active=='advanced' else ''}"><a href="${h.url('edit_user_advanced', user_id=c.user.user_id)}">${_('Advanced')}</a></li>
41 <li class="${'active' if c.active=='advanced' else ''}"><a href="${h.route_path('user_edit_advanced', user_id=c.user.user_id)}">${_('Advanced')}</a></li>
42 <li class="${'active' if c.active=='global_perms' else ''}"><a href="${h.url('edit_user_global_perms', user_id=c.user.user_id)}">${_('Global permissions')}</a></li>
42 <li class="${'active' if c.active=='global_perms' else ''}"><a href="${h.route_path('user_edit_global_perms', user_id=c.user.user_id)}">${_('Global permissions')}</a></li>
43 <li class="${'active' if c.active=='perms_summary' else ''}"><a href="${h.route_path('edit_user_perms_summary', user_id=c.user.user_id)}">${_('Permissions summary')}</a></li>
43 <li class="${'active' if c.active=='perms_summary' else ''}"><a href="${h.route_path('edit_user_perms_summary', user_id=c.user.user_id)}">${_('Permissions summary')}</a></li>
44 <li class="${'active' if c.active=='emails' else ''}"><a href="${h.route_path('edit_user_emails', user_id=c.user.user_id)}">${_('Emails')}</a></li>
44 <li class="${'active' if c.active=='emails' else ''}"><a href="${h.route_path('edit_user_emails', user_id=c.user.user_id)}">${_('Emails')}</a></li>
45 <li class="${'active' if c.active=='ips' else ''}"><a href="${h.route_path('edit_user_ips', user_id=c.user.user_id)}">${_('Ip Whitelist')}</a></li>
45 <li class="${'active' if c.active=='ips' else ''}"><a href="${h.route_path('edit_user_ips', user_id=c.user.user_id)}">${_('Ip Whitelist')}</a></li>
@@ -34,7 +34,7 b''
34 <h3 class="panel-title">${_('Force Password Reset')}</h3>
34 <h3 class="panel-title">${_('Force Password Reset')}</h3>
35 </div>
35 </div>
36 <div class="panel-body">
36 <div class="panel-body">
37 ${h.secure_form(h.url('force_password_reset_user', user_id=c.user.user_id), method='post')}
37 ${h.secure_form(h.route_path('user_force_password_reset', user_id=c.user.user_id), request=request)}
38 <div class="field">
38 <div class="field">
39 <button class="btn btn-default" type="submit">
39 <button class="btn btn-default" type="submit">
40 <i class="icon-lock"></i>
40 <i class="icon-lock"></i>
@@ -59,7 +59,7 b''
59 <h3 class="panel-title">${_('Personal Repository Group')}</h3>
59 <h3 class="panel-title">${_('Personal Repository Group')}</h3>
60 </div>
60 </div>
61 <div class="panel-body">
61 <div class="panel-body">
62 ${h.secure_form(h.url('create_personal_repo_group', user_id=c.user.user_id), method='post')}
62 ${h.secure_form(h.route_path('user_create_personal_repo_group', user_id=c.user.user_id), request=request)}
63
63
64 %if c.personal_repo_group:
64 %if c.personal_repo_group:
65 <div class="panel-body-title-text">${_('Users personal repository group')} : ${h.link_to(c.personal_repo_group.group_name, h.route_path('repo_group_home', repo_group_name=c.personal_repo_group.group_name))}</div>
65 <div class="panel-body-title-text">${_('Users personal repository group')} : ${h.link_to(c.personal_repo_group.group_name, h.route_path('repo_group_home', repo_group_name=c.personal_repo_group.group_name))}</div>
@@ -84,7 +84,7 b''
84 <h3 class="panel-title">${_('Delete User')}</h3>
84 <h3 class="panel-title">${_('Delete User')}</h3>
85 </div>
85 </div>
86 <div class="panel-body">
86 <div class="panel-body">
87 ${h.secure_form(h.url('delete_user', user_id=c.user.user_id), method='delete')}
87 ${h.secure_form(h.route_path('user_delete', user_id=c.user.user_id), request=request)}
88
88
89 <table class="display">
89 <table class="display">
90 <tr>
90 <tr>
@@ -92,6 +92,7 b''
92 <script>
92 <script>
93
93
94 $(document).ready(function(){
94 $(document).ready(function(){
95
95 var select2Options = {
96 var select2Options = {
96 'containerCssClass': "drop-menu",
97 'containerCssClass': "drop-menu",
97 'dropdownCssClass': "drop-menu-dropdown",
98 'dropdownCssClass': "drop-menu-dropdown",
@@ -167,8 +168,8 b' var repoFilter = function(data) {'
167 error: function(data, textStatus, errorThrown) {
168 error: function(data, textStatus, errorThrown) {
168 alert("Error while fetching entries.\nError code {0} ({1}).".format(data.status, data.statusText));
169 alert("Error while fetching entries.\nError code {0} ({1}).".format(data.status, data.statusText));
169 }
170 }
170 })
171 })
171 }
172 }
172 })
173 })
173 });
174 });
174
175
@@ -1,2 +1,2 b''
1 <%namespace name="dpb" file="/base/default_perms_box.mako"/>
1 <%namespace name="dpb" file="/base/default_perms_box.mako"/>
2 ${dpb.default_perms_box(h.url('edit_user_global_perms', user_id=c.user.user_id))}
2 ${dpb.default_perms_box(form_url=h.route_path('user_edit_global_perms_update', user_id=c.user.user_id))}
@@ -61,19 +61,19 b' var api;'
61 render: function (data,type,full,meta)
61 render: function (data,type,full,meta)
62 {return '<input type="hidden" name="users_group_id" value="'+data+'">'}},
62 {return '<input type="hidden" name="users_group_id" value="'+data+'">'}},
63 { data: {"_": "active",
63 { data: {"_": "active",
64 "sort": "active"}, title: "${_('Active')}", className: "td-active", className: "td-number"},
64 "sort": "active"}, title: "${_('Active')}", className: "td-active"},
65 { data: {"_": "owner_data"}, title: "${_('Owner')}", className: "td-user",
65 { data: {"_": "owner_data"}, title: "${_('Owner')}", className: "td-user",
66 render: function (data,type,full,meta)
66 render: function (data,type,full,meta)
67 {return '<div class="rc-user tooltip">'+
67 {return '<div class="rc-user tooltip">'+
68 '<img class="gravatar" src="'+ data.owner_icon +'" height="16" width="16">'+
68 '<img class="gravatar" src="'+ data.owner_icon +'" height="16" width="16">'+
69 data.owner +'</div>'
69 data.owner +'</div>'
70 }
70 }
71 },
71 },
72 { data: null,
72 { data: null,
73 title: "${_('Action')}",
73 title: "${_('Action')}",
74 className: "td-action",
74 className: "td-action",
75 defaultContent: '<a href="" class="btn btn-link btn-danger">Delete</a>'
75 defaultContent: '-'
76 },
76 }
77 ],
77 ],
78 language: {
78 language: {
79 paginate: DEFAULT_GRID_PAGINATION,
79 paginate: DEFAULT_GRID_PAGINATION,
@@ -6,7 +6,7 b''
6 </div>
6 </div>
7 <div class="panel-body">
7 <div class="panel-body">
8 <div class="user-profile-content">
8 <div class="user-profile-content">
9 ${h.secure_form(h.url('update_user', user_id=c.user.user_id),method='put', class_='form')}
9 ${h.secure_form(h.route_path('user_update', user_id=c.user.user_id), class_='form', request=request)}
10 <% readonly = None %>
10 <% readonly = None %>
11 <% disabled = "" %>
11 <% disabled = "" %>
12 %if c.extern_type != 'rhodecode':
12 %if c.extern_type != 'rhodecode':
@@ -25,7 +25,7 b''
25 ${self.breadcrumbs()}
25 ${self.breadcrumbs()}
26 <ul class="links">
26 <ul class="links">
27 <li>
27 <li>
28 <a href="${h.url('new_user')}" class="btn btn-small btn-success">${_(u'Add User')}</a>
28 <a href="${h.route_path('users_new')}" class="btn btn-small btn-success">${_(u'Add User')}</a>
29 </li>
29 </li>
30 </ul>
30 </ul>
31 </div>
31 </div>
@@ -124,22 +124,22 b''
124 edit_url=None, edit_global_url=h.route_path('admin_permissions_object'))}
124 edit_url=None, edit_global_url=h.route_path('admin_permissions_object'))}
125
125
126 ${glob(_('Super admin'), get_section_perms('hg.admin', permissions[section]),
126 ${glob(_('Super admin'), get_section_perms('hg.admin', permissions[section]),
127 edit_url=h.url('edit_user', user_id=c.user.user_id, anchor='admin'), edit_global_url=None)}
127 edit_url=h.route_path('user_edit', user_id=c.user.user_id, _anchor='admin'), edit_global_url=None)}
128
128
129 ${glob(_('Inherit permissions'), get_section_perms('hg.inherit_default_perms.', permissions[section]),
129 ${glob(_('Inherit permissions'), get_section_perms('hg.inherit_default_perms.', permissions[section]),
130 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=None)}
130 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=None)}
131
131
132 ${glob(_('Create repositories'), get_section_perms('hg.create.', permissions[section]),
132 ${glob(_('Create repositories'), get_section_perms('hg.create.', permissions[section]),
133 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
133 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
134
134
135 ${glob(_('Fork repositories'), get_section_perms('hg.fork.', permissions[section]),
135 ${glob(_('Fork repositories'), get_section_perms('hg.fork.', permissions[section]),
136 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
136 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
137
137
138 ${glob(_('Create repository groups'), get_section_perms('hg.repogroup.create.', permissions[section]),
138 ${glob(_('Create repository groups'), get_section_perms('hg.repogroup.create.', permissions[section]),
139 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
139 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
140
140
141 ${glob(_('Create user groups'), get_section_perms('hg.usergroup.create.', permissions[section]),
141 ${glob(_('Create user groups'), get_section_perms('hg.usergroup.create.', permissions[section]),
142 edit_url=h.url('edit_user_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
142 edit_url=h.route_path('user_edit_global_perms', user_id=c.user.user_id), edit_global_url=h.route_path('admin_permissions_object'))}
143
143
144 </tbody>
144 </tbody>
145 %else:
145 %else:
@@ -250,11 +250,11 b''
250
250
251 <%def name="user_actions(user_id, username)">
251 <%def name="user_actions(user_id, username)">
252 <div class="grid_edit">
252 <div class="grid_edit">
253 <a href="${h.url('edit_user',user_id=user_id)}" title="${_('Edit')}">
253 <a href="${h.route_path('user_edit',user_id=user_id)}" title="${_('Edit')}">
254 <i class="icon-pencil"></i>Edit</a>
254 <i class="icon-pencil"></i>${_('Edit')}</a>
255 </div>
255 </div>
256 <div class="grid_delete">
256 <div class="grid_delete">
257 ${h.secure_form(h.url('delete_user', user_id=user_id),method='delete')}
257 ${h.secure_form(h.route_path('user_delete', user_id=user_id), request=request)}
258 ${h.submit('remove_',_('Delete'),id="remove_user_%s" % user_id, class_="btn btn-link btn-danger",
258 ${h.submit('remove_',_('Delete'),id="remove_user_%s" % user_id, class_="btn btn-link btn-danger",
259 onclick="return confirm('"+_('Confirm to delete this user: %s') % username+"');")}
259 onclick="return confirm('"+_('Confirm to delete this user: %s') % username+"');")}
260 ${h.end_form()}
260 ${h.end_form()}
@@ -275,7 +275,7 b''
275
275
276
276
277 <%def name="user_name(user_id, username)">
277 <%def name="user_name(user_id, username)">
278 ${h.link_to(h.person(username, 'username_or_name_or_email'), h.url('edit_user', user_id=user_id))}
278 ${h.link_to(h.person(username, 'username_or_name_or_email'), h.route_path('user_edit', user_id=user_id))}
279 </%def>
279 </%def>
280
280
281 <%def name="user_profile(username)">
281 <%def name="user_profile(username)">
@@ -4,7 +4,7 b''
4 <div class="panel-heading">
4 <div class="panel-heading">
5 <h3 class="panel-title">${_('Profile')}</h3>
5 <h3 class="panel-title">${_('Profile')}</h3>
6 %if h.HasPermissionAny('hg.admin')():
6 %if h.HasPermissionAny('hg.admin')():
7 ${h.link_to(_('Edit'), h.url('edit_user', user_id=c.user.user_id), class_='panel-edit')}
7 ${h.link_to(_('Edit'), h.route_path('user_edit', user_id=c.user.user_id), class_='panel-edit')}
8 %endif
8 %endif
9 </div>
9 </div>
10
10
@@ -1,496 +0,0 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
21 """
22 Users crud controller for pylons
23 """
24
25 import logging
26 import formencode
27
28 from formencode import htmlfill
29 from pylons import request, tmpl_context as c, url, config
30 from pylons.controllers.util import redirect
31 from pylons.i18n.translation import _
32
33 from rhodecode.authentication.plugins import auth_rhodecode
34
35 from rhodecode.lib import helpers as h
36 from rhodecode.lib import auth
37 from rhodecode.lib import audit_logger
38 from rhodecode.lib.auth import (
39 LoginRequired, HasPermissionAllDecorator, AuthUser)
40 from rhodecode.lib.base import BaseController, render
41 from rhodecode.lib.exceptions import (
42 DefaultUserException, UserOwnsReposException, UserOwnsRepoGroupsException,
43 UserOwnsUserGroupsException, UserCreationError)
44 from rhodecode.lib.utils2 import safe_int, AttributeDict
45
46 from rhodecode.model.db import (
47 PullRequestReviewers, User, UserEmailMap, UserIpMap, RepoGroup)
48 from rhodecode.model.forms import (
49 UserForm, UserPermissionsForm, UserIndividualPermissionsForm)
50 from rhodecode.model.repo_group import RepoGroupModel
51 from rhodecode.model.user import UserModel
52 from rhodecode.model.meta import Session
53 from rhodecode.model.permission import PermissionModel
54
55 log = logging.getLogger(__name__)
56
57
58 class UsersController(BaseController):
59 """REST Controller styled on the Atom Publishing Protocol"""
60
61 @LoginRequired()
62 def __before__(self):
63 super(UsersController, self).__before__()
64 c.available_permissions = config['available_permissions']
65 c.allowed_languages = [
66 ('en', 'English (en)'),
67 ('de', 'German (de)'),
68 ('fr', 'French (fr)'),
69 ('it', 'Italian (it)'),
70 ('ja', 'Japanese (ja)'),
71 ('pl', 'Polish (pl)'),
72 ('pt', 'Portuguese (pt)'),
73 ('ru', 'Russian (ru)'),
74 ('zh', 'Chinese (zh)'),
75 ]
76 PermissionModel().set_global_permission_choices(c, gettext_translator=_)
77
78 def _get_personal_repo_group_template_vars(self):
79 DummyUser = AttributeDict({
80 'username': '${username}',
81 'user_id': '${user_id}',
82 })
83 c.default_create_repo_group = RepoGroupModel() \
84 .get_default_create_personal_repo_group()
85 c.personal_repo_group_name = RepoGroupModel() \
86 .get_personal_group_name(DummyUser)
87
88 @HasPermissionAllDecorator('hg.admin')
89 @auth.CSRFRequired()
90 def create(self):
91 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
92 user_model = UserModel()
93 user_form = UserForm()()
94 try:
95 form_result = user_form.to_python(dict(request.POST))
96 user = user_model.create(form_result)
97 Session().flush()
98 creation_data = user.get_api_data()
99 username = form_result['username']
100
101 audit_logger.store_web(
102 'user.create', action_data={'data': creation_data},
103 user=c.rhodecode_user)
104
105 user_link = h.link_to(h.escape(username),
106 url('edit_user',
107 user_id=user.user_id))
108 h.flash(h.literal(_('Created user %(user_link)s')
109 % {'user_link': user_link}), category='success')
110 Session().commit()
111 except formencode.Invalid as errors:
112 self._get_personal_repo_group_template_vars()
113 return htmlfill.render(
114 render('admin/users/user_add.mako'),
115 defaults=errors.value,
116 errors=errors.error_dict or {},
117 prefix_error=False,
118 encoding="UTF-8",
119 force_defaults=False)
120 except UserCreationError as e:
121 h.flash(e, 'error')
122 except Exception:
123 log.exception("Exception creation of user")
124 h.flash(_('Error occurred during creation of user %s')
125 % request.POST.get('username'), category='error')
126 return redirect(h.route_path('users'))
127
128 @HasPermissionAllDecorator('hg.admin')
129 def new(self):
130 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
131 self._get_personal_repo_group_template_vars()
132 return render('admin/users/user_add.mako')
133
134 @HasPermissionAllDecorator('hg.admin')
135 @auth.CSRFRequired()
136 def update(self, user_id):
137
138 user_id = safe_int(user_id)
139 c.user = User.get_or_404(user_id)
140 c.active = 'profile'
141 c.extern_type = c.user.extern_type
142 c.extern_name = c.user.extern_name
143 c.perm_user = AuthUser(user_id=user_id, ip_addr=self.ip_addr)
144 available_languages = [x[0] for x in c.allowed_languages]
145 _form = UserForm(edit=True, available_languages=available_languages,
146 old_data={'user_id': user_id,
147 'email': c.user.email})()
148 form_result = {}
149 old_values = c.user.get_api_data()
150 try:
151 form_result = _form.to_python(dict(request.POST))
152 skip_attrs = ['extern_type', 'extern_name']
153 # TODO: plugin should define if username can be updated
154 if c.extern_type != "rhodecode":
155 # forbid updating username for external accounts
156 skip_attrs.append('username')
157
158 UserModel().update_user(
159 user_id, skip_attrs=skip_attrs, **form_result)
160
161 audit_logger.store_web(
162 'user.edit', action_data={'old_data': old_values},
163 user=c.rhodecode_user)
164
165 Session().commit()
166 h.flash(_('User updated successfully'), category='success')
167 except formencode.Invalid as errors:
168 defaults = errors.value
169 e = errors.error_dict or {}
170
171 return htmlfill.render(
172 render('admin/users/user_edit.mako'),
173 defaults=defaults,
174 errors=e,
175 prefix_error=False,
176 encoding="UTF-8",
177 force_defaults=False)
178 except UserCreationError as e:
179 h.flash(e, 'error')
180 except Exception:
181 log.exception("Exception updating user")
182 h.flash(_('Error occurred during update of user %s')
183 % form_result.get('username'), category='error')
184 return redirect(url('edit_user', user_id=user_id))
185
186 @HasPermissionAllDecorator('hg.admin')
187 @auth.CSRFRequired()
188 def delete(self, user_id):
189 user_id = safe_int(user_id)
190 c.user = User.get_or_404(user_id)
191
192 _repos = c.user.repositories
193 _repo_groups = c.user.repository_groups
194 _user_groups = c.user.user_groups
195
196 handle_repos = None
197 handle_repo_groups = None
198 handle_user_groups = None
199 # dummy call for flash of handle
200 set_handle_flash_repos = lambda: None
201 set_handle_flash_repo_groups = lambda: None
202 set_handle_flash_user_groups = lambda: None
203
204 if _repos and request.POST.get('user_repos'):
205 do = request.POST['user_repos']
206 if do == 'detach':
207 handle_repos = 'detach'
208 set_handle_flash_repos = lambda: h.flash(
209 _('Detached %s repositories') % len(_repos),
210 category='success')
211 elif do == 'delete':
212 handle_repos = 'delete'
213 set_handle_flash_repos = lambda: h.flash(
214 _('Deleted %s repositories') % len(_repos),
215 category='success')
216
217 if _repo_groups and request.POST.get('user_repo_groups'):
218 do = request.POST['user_repo_groups']
219 if do == 'detach':
220 handle_repo_groups = 'detach'
221 set_handle_flash_repo_groups = lambda: h.flash(
222 _('Detached %s repository groups') % len(_repo_groups),
223 category='success')
224 elif do == 'delete':
225 handle_repo_groups = 'delete'
226 set_handle_flash_repo_groups = lambda: h.flash(
227 _('Deleted %s repository groups') % len(_repo_groups),
228 category='success')
229
230 if _user_groups and request.POST.get('user_user_groups'):
231 do = request.POST['user_user_groups']
232 if do == 'detach':
233 handle_user_groups = 'detach'
234 set_handle_flash_user_groups = lambda: h.flash(
235 _('Detached %s user groups') % len(_user_groups),
236 category='success')
237 elif do == 'delete':
238 handle_user_groups = 'delete'
239 set_handle_flash_user_groups = lambda: h.flash(
240 _('Deleted %s user groups') % len(_user_groups),
241 category='success')
242
243 old_values = c.user.get_api_data()
244 try:
245 UserModel().delete(c.user, handle_repos=handle_repos,
246 handle_repo_groups=handle_repo_groups,
247 handle_user_groups=handle_user_groups)
248
249 audit_logger.store_web(
250 'user.delete', action_data={'old_data': old_values},
251 user=c.rhodecode_user)
252
253 Session().commit()
254 set_handle_flash_repos()
255 set_handle_flash_repo_groups()
256 set_handle_flash_user_groups()
257 h.flash(_('Successfully deleted user'), category='success')
258 except (UserOwnsReposException, UserOwnsRepoGroupsException,
259 UserOwnsUserGroupsException, DefaultUserException) as e:
260 h.flash(e, category='warning')
261 except Exception:
262 log.exception("Exception during deletion of user")
263 h.flash(_('An error occurred during deletion of user'),
264 category='error')
265 return redirect(h.route_path('users'))
266
267 @HasPermissionAllDecorator('hg.admin')
268 @auth.CSRFRequired()
269 def reset_password(self, user_id):
270 """
271 toggle reset password flag for this user
272 """
273 user_id = safe_int(user_id)
274 c.user = User.get_or_404(user_id)
275 try:
276 old_value = c.user.user_data.get('force_password_change')
277 c.user.update_userdata(force_password_change=not old_value)
278
279 if old_value:
280 msg = _('Force password change disabled for user')
281 audit_logger.store_web(
282 'user.edit.password_reset.disabled',
283 user=c.rhodecode_user)
284 else:
285 msg = _('Force password change enabled for user')
286 audit_logger.store_web(
287 'user.edit.password_reset.enabled',
288 user=c.rhodecode_user)
289
290 Session().commit()
291 h.flash(msg, category='success')
292 except Exception:
293 log.exception("Exception during password reset for user")
294 h.flash(_('An error occurred during password reset for user'),
295 category='error')
296
297 return redirect(url('edit_user_advanced', user_id=user_id))
298
299 @HasPermissionAllDecorator('hg.admin')
300 @auth.CSRFRequired()
301 def create_personal_repo_group(self, user_id):
302 """
303 Create personal repository group for this user
304 """
305 from rhodecode.model.repo_group import RepoGroupModel
306
307 user_id = safe_int(user_id)
308 c.user = User.get_or_404(user_id)
309 personal_repo_group = RepoGroup.get_user_personal_repo_group(
310 c.user.user_id)
311 if personal_repo_group:
312 return redirect(url('edit_user_advanced', user_id=user_id))
313
314 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
315 c.user)
316 named_personal_group = RepoGroup.get_by_group_name(
317 personal_repo_group_name)
318 try:
319
320 if named_personal_group and named_personal_group.user_id == c.user.user_id:
321 # migrate the same named group, and mark it as personal
322 named_personal_group.personal = True
323 Session().add(named_personal_group)
324 Session().commit()
325 msg = _('Linked repository group `%s` as personal' % (
326 personal_repo_group_name,))
327 h.flash(msg, category='success')
328 elif not named_personal_group:
329 RepoGroupModel().create_personal_repo_group(c.user)
330
331 msg = _('Created repository group `%s`' % (
332 personal_repo_group_name,))
333 h.flash(msg, category='success')
334 else:
335 msg = _('Repository group `%s` is already taken' % (
336 personal_repo_group_name,))
337 h.flash(msg, category='warning')
338 except Exception:
339 log.exception("Exception during repository group creation")
340 msg = _(
341 'An error occurred during repository group creation for user')
342 h.flash(msg, category='error')
343 Session().rollback()
344
345 return redirect(url('edit_user_advanced', user_id=user_id))
346
347 @HasPermissionAllDecorator('hg.admin')
348 def show(self, user_id):
349 """GET /users/user_id: Show a specific item"""
350 # url('user', user_id=ID)
351 User.get_or_404(-1)
352
353 @HasPermissionAllDecorator('hg.admin')
354 def edit(self, user_id):
355 """GET /users/user_id/edit: Form to edit an existing item"""
356 # url('edit_user', user_id=ID)
357 user_id = safe_int(user_id)
358 c.user = User.get_or_404(user_id)
359 if c.user.username == User.DEFAULT_USER:
360 h.flash(_("You can't edit this user"), category='warning')
361 return redirect(h.route_path('users'))
362
363 c.active = 'profile'
364 c.extern_type = c.user.extern_type
365 c.extern_name = c.user.extern_name
366 c.perm_user = AuthUser(user_id=user_id, ip_addr=self.ip_addr)
367
368 defaults = c.user.get_dict()
369 defaults.update({'language': c.user.user_data.get('language')})
370 return htmlfill.render(
371 render('admin/users/user_edit.mako'),
372 defaults=defaults,
373 encoding="UTF-8",
374 force_defaults=False)
375
376 @HasPermissionAllDecorator('hg.admin')
377 def edit_advanced(self, user_id):
378 user_id = safe_int(user_id)
379 user = c.user = User.get_or_404(user_id)
380 if user.username == User.DEFAULT_USER:
381 h.flash(_("You can't edit this user"), category='warning')
382 return redirect(h.route_path('users'))
383
384 c.active = 'advanced'
385 c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id)
386 c.personal_repo_group_name = RepoGroupModel()\
387 .get_personal_group_name(user)
388
389 c.user_to_review_rules = sorted(
390 (x.user for x in c.user.user_review_rules),
391 key=lambda u: u.username.lower())
392
393 c.first_admin = User.get_first_super_admin()
394 defaults = user.get_dict()
395
396 # Interim workaround if the user participated on any pull requests as a
397 # reviewer.
398 has_review = len(user.reviewer_pull_requests)
399 c.can_delete_user = not has_review
400 c.can_delete_user_message = ''
401 inactive_link = h.link_to(
402 'inactive', h.url('edit_user', user_id=user_id, anchor='active'))
403 if has_review == 1:
404 c.can_delete_user_message = h.literal(_(
405 'The user participates as reviewer in {} pull request and '
406 'cannot be deleted. \nYou can set the user to '
407 '"{}" instead of deleting it.').format(
408 has_review, inactive_link))
409 elif has_review:
410 c.can_delete_user_message = h.literal(_(
411 'The user participates as reviewer in {} pull requests and '
412 'cannot be deleted. \nYou can set the user to '
413 '"{}" instead of deleting it.').format(
414 has_review, inactive_link))
415
416 return htmlfill.render(
417 render('admin/users/user_edit.mako'),
418 defaults=defaults,
419 encoding="UTF-8",
420 force_defaults=False)
421
422 @HasPermissionAllDecorator('hg.admin')
423 def edit_global_perms(self, user_id):
424 user_id = safe_int(user_id)
425 c.user = User.get_or_404(user_id)
426 if c.user.username == User.DEFAULT_USER:
427 h.flash(_("You can't edit this user"), category='warning')
428 return redirect(h.route_path('users'))
429
430 c.active = 'global_perms'
431
432 c.default_user = User.get_default_user()
433 defaults = c.user.get_dict()
434 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
435 defaults.update(c.default_user.get_default_perms())
436 defaults.update(c.user.get_default_perms())
437
438 return htmlfill.render(
439 render('admin/users/user_edit.mako'),
440 defaults=defaults,
441 encoding="UTF-8",
442 force_defaults=False)
443
444 @HasPermissionAllDecorator('hg.admin')
445 @auth.CSRFRequired()
446 def update_global_perms(self, user_id):
447 user_id = safe_int(user_id)
448 user = User.get_or_404(user_id)
449 c.active = 'global_perms'
450 try:
451 # first stage that verifies the checkbox
452 _form = UserIndividualPermissionsForm()
453 form_result = _form.to_python(dict(request.POST))
454 inherit_perms = form_result['inherit_default_permissions']
455 user.inherit_default_permissions = inherit_perms
456 Session().add(user)
457
458 if not inherit_perms:
459 # only update the individual ones if we un check the flag
460 _form = UserPermissionsForm(
461 [x[0] for x in c.repo_create_choices],
462 [x[0] for x in c.repo_create_on_write_choices],
463 [x[0] for x in c.repo_group_create_choices],
464 [x[0] for x in c.user_group_create_choices],
465 [x[0] for x in c.fork_choices],
466 [x[0] for x in c.inherit_default_permission_choices])()
467
468 form_result = _form.to_python(dict(request.POST))
469 form_result.update({'perm_user_id': user.user_id})
470
471 PermissionModel().update_user_permissions(form_result)
472
473 # TODO(marcink): implement global permissions
474 # audit_log.store_web('user.edit.permissions')
475
476 Session().commit()
477 h.flash(_('User global permissions updated successfully'),
478 category='success')
479
480 except formencode.Invalid as errors:
481 defaults = errors.value
482 c.user = user
483 return htmlfill.render(
484 render('admin/users/user_edit.mako'),
485 defaults=defaults,
486 errors=errors.error_dict or {},
487 prefix_error=False,
488 encoding="UTF-8",
489 force_defaults=False)
490 except Exception:
491 log.exception("Exception during permissions saving")
492 h.flash(_('An error occurred during permissions saving'),
493 category='error')
494 return redirect(url('edit_user_global_perms', user_id=user_id))
495
496
This diff has been collapsed as it changes many lines, (512 lines changed) Show them Hide them
@@ -1,512 +0,0 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
21 import pytest
22 from sqlalchemy.orm.exc import NoResultFound
23
24 from rhodecode.lib.auth import check_password
25 from rhodecode.lib import helpers as h
26 from rhodecode.model import validators
27 from rhodecode.model.db import User, UserIpMap, UserApiKeys
28 from rhodecode.model.meta import Session
29 from rhodecode.model.user import UserModel
30 from rhodecode.tests import (
31 TestController, url, link_to, TEST_USER_ADMIN_LOGIN,
32 TEST_USER_REGULAR_LOGIN, assert_session_flash)
33 from rhodecode.tests.fixture import Fixture
34 from rhodecode.tests.utils import AssertResponse
35
36 fixture = Fixture()
37
38
39 def route_path(name, params=None, **kwargs):
40 import urllib
41 from rhodecode.apps._base import ADMIN_PREFIX
42
43 base_url = {
44 'users_data':
45 ADMIN_PREFIX + '/users_data',
46 }[name].format(**kwargs)
47
48 if params:
49 base_url = '{}?{}'.format(base_url, urllib.urlencode(params))
50 return base_url
51
52
53 class TestAdminUsersController(TestController):
54 test_user_1 = 'testme'
55 destroy_users = set()
56
57 @classmethod
58 def teardown_method(cls, method):
59 fixture.destroy_users(cls.destroy_users)
60
61 def test_create(self, xhr_header):
62 self.log_user()
63 username = 'newtestuser'
64 password = 'test12'
65 password_confirmation = password
66 name = 'name'
67 lastname = 'lastname'
68 email = 'mail@mail.com'
69
70 self.app.get(url('new_user'))
71
72 response = self.app.post(url('users'), params={
73 'username': username,
74 'password': password,
75 'password_confirmation': password_confirmation,
76 'firstname': name,
77 'active': True,
78 'lastname': lastname,
79 'extern_name': 'rhodecode',
80 'extern_type': 'rhodecode',
81 'email': email,
82 'csrf_token': self.csrf_token,
83 })
84 user_link = link_to(
85 username,
86 url('edit_user', user_id=User.get_by_username(username).user_id))
87 assert_session_flash(response, 'Created user %s' % (user_link,))
88 self.destroy_users.add(username)
89
90 new_user = User.query().filter(User.username == username).one()
91
92 assert new_user.username == username
93 assert check_password(password, new_user.password)
94 assert new_user.name == name
95 assert new_user.lastname == lastname
96 assert new_user.email == email
97
98 response = self.app.get(route_path('users_data'),
99 extra_environ=xhr_header)
100 response.mustcontain(username)
101
102 def test_create_err(self):
103 self.log_user()
104 username = 'new_user'
105 password = ''
106 name = 'name'
107 lastname = 'lastname'
108 email = 'errmail.com'
109
110 self.app.get(url('new_user'))
111
112 response = self.app.post(url('users'), params={
113 'username': username,
114 'password': password,
115 'name': name,
116 'active': False,
117 'lastname': lastname,
118 'email': email,
119 'csrf_token': self.csrf_token,
120 })
121
122 msg = validators.ValidUsername(
123 False, {})._messages['system_invalid_username']
124 msg = h.html_escape(msg % {'username': 'new_user'})
125 response.mustcontain('<span class="error-message">%s</span>' % msg)
126 response.mustcontain(
127 '<span class="error-message">Please enter a value</span>')
128 response.mustcontain(
129 '<span class="error-message">An email address must contain a'
130 ' single @</span>')
131
132 def get_user():
133 Session().query(User).filter(User.username == username).one()
134
135 with pytest.raises(NoResultFound):
136 get_user()
137
138 def test_new(self):
139 self.log_user()
140 self.app.get(url('new_user'))
141
142 @pytest.mark.parametrize("name, attrs", [
143 ('firstname', {'firstname': 'new_username'}),
144 ('lastname', {'lastname': 'new_username'}),
145 ('admin', {'admin': True}),
146 ('admin', {'admin': False}),
147 ('extern_type', {'extern_type': 'ldap'}),
148 ('extern_type', {'extern_type': None}),
149 ('extern_name', {'extern_name': 'test'}),
150 ('extern_name', {'extern_name': None}),
151 ('active', {'active': False}),
152 ('active', {'active': True}),
153 ('email', {'email': 'some@email.com'}),
154 ('language', {'language': 'de'}),
155 ('language', {'language': 'en'}),
156 # ('new_password', {'new_password': 'foobar123',
157 # 'password_confirmation': 'foobar123'})
158 ])
159 def test_update(self, name, attrs):
160 self.log_user()
161 usr = fixture.create_user(self.test_user_1, password='qweqwe',
162 email='testme@rhodecode.org',
163 extern_type='rhodecode',
164 extern_name=self.test_user_1,
165 skip_if_exists=True)
166 Session().commit()
167 self.destroy_users.add(self.test_user_1)
168 params = usr.get_api_data()
169 cur_lang = params['language'] or 'en'
170 params.update({
171 'password_confirmation': '',
172 'new_password': '',
173 'language': cur_lang,
174 '_method': 'put',
175 'csrf_token': self.csrf_token,
176 })
177 params.update({'new_password': ''})
178 params.update(attrs)
179 if name == 'email':
180 params['emails'] = [attrs['email']]
181 elif name == 'extern_type':
182 # cannot update this via form, expected value is original one
183 params['extern_type'] = "rhodecode"
184 elif name == 'extern_name':
185 # cannot update this via form, expected value is original one
186 params['extern_name'] = self.test_user_1
187 # special case since this user is not
188 # logged in yet his data is not filled
189 # so we use creation data
190
191 response = self.app.post(url('user', user_id=usr.user_id), params)
192 assert response.status_int == 302
193 assert_session_flash(response, 'User updated successfully')
194
195 updated_user = User.get_by_username(self.test_user_1)
196 updated_params = updated_user.get_api_data()
197 updated_params.update({'password_confirmation': ''})
198 updated_params.update({'new_password': ''})
199
200 del params['_method']
201 del params['csrf_token']
202 assert params == updated_params
203
204 def test_update_and_migrate_password(
205 self, autologin_user, real_crypto_backend):
206 from rhodecode.lib import auth
207
208 # create new user, with sha256 password
209 temp_user = 'test_admin_sha256'
210 user = fixture.create_user(temp_user)
211 user.password = auth._RhodeCodeCryptoSha256().hash_create(
212 b'test123')
213 Session().add(user)
214 Session().commit()
215 self.destroy_users.add('test_admin_sha256')
216
217 params = user.get_api_data()
218
219 params.update({
220 'password_confirmation': 'qweqwe123',
221 'new_password': 'qweqwe123',
222 'language': 'en',
223 '_method': 'put',
224 'csrf_token': autologin_user.csrf_token,
225 })
226
227 response = self.app.post(url('user', user_id=user.user_id), params)
228 assert response.status_int == 302
229 assert_session_flash(response, 'User updated successfully')
230
231 # new password should be bcrypted, after log-in and transfer
232 user = User.get_by_username(temp_user)
233 assert user.password.startswith('$')
234
235 updated_user = User.get_by_username(temp_user)
236 updated_params = updated_user.get_api_data()
237 updated_params.update({'password_confirmation': 'qweqwe123'})
238 updated_params.update({'new_password': 'qweqwe123'})
239
240 del params['_method']
241 del params['csrf_token']
242 assert params == updated_params
243
244 def test_delete(self):
245 self.log_user()
246 username = 'newtestuserdeleteme'
247
248 fixture.create_user(name=username)
249
250 new_user = Session().query(User)\
251 .filter(User.username == username).one()
252 response = self.app.post(url('user', user_id=new_user.user_id),
253 params={'_method': 'delete',
254 'csrf_token': self.csrf_token})
255
256 assert_session_flash(response, 'Successfully deleted user')
257
258 def test_delete_owner_of_repository(self):
259 self.log_user()
260 username = 'newtestuserdeleteme_repo_owner'
261 obj_name = 'test_repo'
262 usr = fixture.create_user(name=username)
263 self.destroy_users.add(username)
264 fixture.create_repo(obj_name, cur_user=usr.username)
265
266 new_user = Session().query(User)\
267 .filter(User.username == username).one()
268 response = self.app.post(url('user', user_id=new_user.user_id),
269 params={'_method': 'delete',
270 'csrf_token': self.csrf_token})
271
272 msg = 'user "%s" still owns 1 repositories and cannot be removed. ' \
273 'Switch owners or remove those repositories:%s' % (username,
274 obj_name)
275 assert_session_flash(response, msg)
276 fixture.destroy_repo(obj_name)
277
278 def test_delete_owner_of_repository_detaching(self):
279 self.log_user()
280 username = 'newtestuserdeleteme_repo_owner_detach'
281 obj_name = 'test_repo'
282 usr = fixture.create_user(name=username)
283 self.destroy_users.add(username)
284 fixture.create_repo(obj_name, cur_user=usr.username)
285
286 new_user = Session().query(User)\
287 .filter(User.username == username).one()
288 response = self.app.post(url('user', user_id=new_user.user_id),
289 params={'_method': 'delete',
290 'user_repos': 'detach',
291 'csrf_token': self.csrf_token})
292
293 msg = 'Detached 1 repositories'
294 assert_session_flash(response, msg)
295 fixture.destroy_repo(obj_name)
296
297 def test_delete_owner_of_repository_deleting(self):
298 self.log_user()
299 username = 'newtestuserdeleteme_repo_owner_delete'
300 obj_name = 'test_repo'
301 usr = fixture.create_user(name=username)
302 self.destroy_users.add(username)
303 fixture.create_repo(obj_name, cur_user=usr.username)
304
305 new_user = Session().query(User)\
306 .filter(User.username == username).one()
307 response = self.app.post(url('user', user_id=new_user.user_id),
308 params={'_method': 'delete',
309 'user_repos': 'delete',
310 'csrf_token': self.csrf_token})
311
312 msg = 'Deleted 1 repositories'
313 assert_session_flash(response, msg)
314
315 def test_delete_owner_of_repository_group(self):
316 self.log_user()
317 username = 'newtestuserdeleteme_repo_group_owner'
318 obj_name = 'test_group'
319 usr = fixture.create_user(name=username)
320 self.destroy_users.add(username)
321 fixture.create_repo_group(obj_name, cur_user=usr.username)
322
323 new_user = Session().query(User)\
324 .filter(User.username == username).one()
325 response = self.app.post(url('user', user_id=new_user.user_id),
326 params={'_method': 'delete',
327 'csrf_token': self.csrf_token})
328
329 msg = 'user "%s" still owns 1 repository groups and cannot be removed. ' \
330 'Switch owners or remove those repository groups:%s' % (username,
331 obj_name)
332 assert_session_flash(response, msg)
333 fixture.destroy_repo_group(obj_name)
334
335 def test_delete_owner_of_repository_group_detaching(self):
336 self.log_user()
337 username = 'newtestuserdeleteme_repo_group_owner_detach'
338 obj_name = 'test_group'
339 usr = fixture.create_user(name=username)
340 self.destroy_users.add(username)
341 fixture.create_repo_group(obj_name, cur_user=usr.username)
342
343 new_user = Session().query(User)\
344 .filter(User.username == username).one()
345 response = self.app.post(url('user', user_id=new_user.user_id),
346 params={'_method': 'delete',
347 'user_repo_groups': 'delete',
348 'csrf_token': self.csrf_token})
349
350 msg = 'Deleted 1 repository groups'
351 assert_session_flash(response, msg)
352
353 def test_delete_owner_of_repository_group_deleting(self):
354 self.log_user()
355 username = 'newtestuserdeleteme_repo_group_owner_delete'
356 obj_name = 'test_group'
357 usr = fixture.create_user(name=username)
358 self.destroy_users.add(username)
359 fixture.create_repo_group(obj_name, cur_user=usr.username)
360
361 new_user = Session().query(User)\
362 .filter(User.username == username).one()
363 response = self.app.post(url('user', user_id=new_user.user_id),
364 params={'_method': 'delete',
365 'user_repo_groups': 'detach',
366 'csrf_token': self.csrf_token})
367
368 msg = 'Detached 1 repository groups'
369 assert_session_flash(response, msg)
370 fixture.destroy_repo_group(obj_name)
371
372 def test_delete_owner_of_user_group(self):
373 self.log_user()
374 username = 'newtestuserdeleteme_user_group_owner'
375 obj_name = 'test_user_group'
376 usr = fixture.create_user(name=username)
377 self.destroy_users.add(username)
378 fixture.create_user_group(obj_name, cur_user=usr.username)
379
380 new_user = Session().query(User)\
381 .filter(User.username == username).one()
382 response = self.app.post(url('user', user_id=new_user.user_id),
383 params={'_method': 'delete',
384 'csrf_token': self.csrf_token})
385
386 msg = 'user "%s" still owns 1 user groups and cannot be removed. ' \
387 'Switch owners or remove those user groups:%s' % (username,
388 obj_name)
389 assert_session_flash(response, msg)
390 fixture.destroy_user_group(obj_name)
391
392 def test_delete_owner_of_user_group_detaching(self):
393 self.log_user()
394 username = 'newtestuserdeleteme_user_group_owner_detaching'
395 obj_name = 'test_user_group'
396 usr = fixture.create_user(name=username)
397 self.destroy_users.add(username)
398 fixture.create_user_group(obj_name, cur_user=usr.username)
399
400 new_user = Session().query(User)\
401 .filter(User.username == username).one()
402 try:
403 response = self.app.post(url('user', user_id=new_user.user_id),
404 params={'_method': 'delete',
405 'user_user_groups': 'detach',
406 'csrf_token': self.csrf_token})
407
408 msg = 'Detached 1 user groups'
409 assert_session_flash(response, msg)
410 finally:
411 fixture.destroy_user_group(obj_name)
412
413 def test_delete_owner_of_user_group_deleting(self):
414 self.log_user()
415 username = 'newtestuserdeleteme_user_group_owner_deleting'
416 obj_name = 'test_user_group'
417 usr = fixture.create_user(name=username)
418 self.destroy_users.add(username)
419 fixture.create_user_group(obj_name, cur_user=usr.username)
420
421 new_user = Session().query(User)\
422 .filter(User.username == username).one()
423 response = self.app.post(url('user', user_id=new_user.user_id),
424 params={'_method': 'delete',
425 'user_user_groups': 'delete',
426 'csrf_token': self.csrf_token})
427
428 msg = 'Deleted 1 user groups'
429 assert_session_flash(response, msg)
430
431 def test_edit(self):
432 self.log_user()
433 user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
434 self.app.get(url('edit_user', user_id=user.user_id))
435
436 @pytest.mark.parametrize(
437 'repo_create, repo_create_write, user_group_create, repo_group_create,'
438 'fork_create, inherit_default_permissions, expect_error,'
439 'expect_form_error', [
440 ('hg.create.none', 'hg.create.write_on_repogroup.false',
441 'hg.usergroup.create.false', 'hg.repogroup.create.false',
442 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
443 ('hg.create.repository', 'hg.create.write_on_repogroup.false',
444 'hg.usergroup.create.false', 'hg.repogroup.create.false',
445 'hg.fork.none', 'hg.inherit_default_perms.false', False, False),
446 ('hg.create.repository', 'hg.create.write_on_repogroup.true',
447 'hg.usergroup.create.true', 'hg.repogroup.create.true',
448 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
449 False),
450 ('hg.create.XXX', 'hg.create.write_on_repogroup.true',
451 'hg.usergroup.create.true', 'hg.repogroup.create.true',
452 'hg.fork.repository', 'hg.inherit_default_perms.false', False,
453 True),
454 ('', '', '', '', '', '', True, False),
455 ])
456 def test_global_perms_on_user(
457 self, repo_create, repo_create_write, user_group_create,
458 repo_group_create, fork_create, expect_error, expect_form_error,
459 inherit_default_permissions):
460 self.log_user()
461 user = fixture.create_user('dummy')
462 uid = user.user_id
463
464 # ENABLE REPO CREATE ON A GROUP
465 perm_params = {
466 'inherit_default_permissions': False,
467 'default_repo_create': repo_create,
468 'default_repo_create_on_write': repo_create_write,
469 'default_user_group_create': user_group_create,
470 'default_repo_group_create': repo_group_create,
471 'default_fork_create': fork_create,
472 'default_inherit_default_permissions': inherit_default_permissions,
473 '_method': 'put',
474 'csrf_token': self.csrf_token,
475 }
476 response = self.app.post(
477 url('edit_user_global_perms', user_id=uid),
478 params=perm_params)
479
480 if expect_form_error:
481 assert response.status_int == 200
482 response.mustcontain('Value must be one of')
483 else:
484 if expect_error:
485 msg = 'An error occurred during permissions saving'
486 else:
487 msg = 'User global permissions updated successfully'
488 ug = User.get(uid)
489 del perm_params['_method']
490 del perm_params['inherit_default_permissions']
491 del perm_params['csrf_token']
492 assert perm_params == ug.get_default_perms()
493 assert_session_flash(response, msg)
494 fixture.destroy_user(uid)
495
496 def test_global_permissions_initial_values(self, user_util):
497 self.log_user()
498 user = user_util.create_user()
499 uid = user.user_id
500 response = self.app.get(url('edit_user_global_perms', user_id=uid))
501 default_user = User.get_default_user()
502 default_permissions = default_user.get_default_perms()
503 assert_response = AssertResponse(response)
504 expected_permissions = (
505 'default_repo_create', 'default_repo_create_on_write',
506 'default_fork_create', 'default_repo_group_create',
507 'default_user_group_create', 'default_inherit_default_permissions')
508 for permission in expected_permissions:
509 css_selector = '[name={}][checked=checked]'.format(permission)
510 element = assert_response.get_element(css_selector)
511 assert element.value == default_permissions[permission]
512
General Comments 0
You need to be logged in to leave comments. Login now