##// 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 30 from rhodecode.model import repo
31 31 from rhodecode.model import repo_group
32 32 from rhodecode.model import user_group
33 from rhodecode.model import user
33 34 from rhodecode.model.db import User
34 35 from rhodecode.model.scm import ScmModel
35 36
@@ -267,6 +268,20 b' class UserGroupAppView(BaseAppView):'
267 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 285 class DataGridAppView(object):
271 286 """
272 287 Common class to have re-usable grid rendering components
@@ -483,17 +498,63 b' class UserGroupRoutePredicate(object):'
483 498
484 499 user_group_id = info['match']['user_group_id']
485 500 user_group_model = user_group.UserGroup()
486 by_name_match = user_group_model.get(
501 by_id_match = user_group_model.get(
487 502 user_group_id, cache=True)
488 503
489 if by_name_match:
504 if by_id_match:
490 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 507 return True
493 508
494 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 558 def includeme(config):
498 559 config.add_route_predicate(
499 560 'repo_route', RepoRoutePredicate)
@@ -503,3 +564,7 b' def includeme(config):'
503 564 'repo_group_route', RepoGroupRoutePredicate)
504 565 config.add_route_predicate(
505 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 137 name='users_data',
138 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 182 # user auth tokens
141 183 config.add_route(
142 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 187 config.add_route(
145 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 191 config.add_route(
148 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 196 # user ssh keys
152 197 config.add_route(
153 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 201 config.add_route(
156 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 205 config.add_route(
159 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 209 config.add_route(
162 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 214 # user emails
166 215 config.add_route(
167 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 219 config.add_route(
170 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 223 config.add_route(
173 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 228 # user IPs
177 229 config.add_route(
178 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 233 config.add_route(
181 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 237 config.add_route(
184 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 242 # user perms
188 243 config.add_route(
189 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 247 config.add_route(
192 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 252 # user user groups management
196 253 config.add_route(
197 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 258 config.add_route(
201 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 263 # user audit logs
205 264 config.add_route(
206 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 268 # user-groups admin
210 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 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 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 28 from rhodecode.model.meta import Session
25 29 from rhodecode.model.user import UserModel
26 30
@@ -40,6 +44,27 b' def route_path(name, params=None, **kwar'
40 44 ADMIN_PREFIX + '/users',
41 45 'users_data':
42 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 68 'edit_user_auth_tokens':
44 69 ADMIN_PREFIX + '/users/{user_id}/edit/auth_tokens',
45 70 'edit_user_auth_tokens_add':
@@ -60,6 +85,15 b' def route_path(name, params=None, **kwar'
60 85 ADMIN_PREFIX + '/users/{user_id}/edit/ips/new',
61 86 'edit_user_ips_delete':
62 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 97 }[name].format(**kwargs)
64 98
65 99 if params:
@@ -220,7 +254,8 b' class TestAdminUsersView(TestController)'
220 254 def test_emails(self):
221 255 self.log_user()
222 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 259 response.mustcontain('No additional emails specified')
225 260
226 261 def test_emails_add(self, user_util):
@@ -233,7 +268,8 b' class TestAdminUsersView(TestController)'
233 268 params={'new_email': 'example@rhodecode.com',
234 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 273 response.mustcontain('example@rhodecode.com')
238 274
239 275 def test_emails_add_existing_email(self, user_util, user_regular):
@@ -250,7 +286,8 b' class TestAdminUsersView(TestController)'
250 286 assert_session_flash(
251 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 291 response.mustcontain(no=[existing_email])
255 292
256 293 def test_emails_delete(self, user_util):
@@ -263,7 +300,8 b' class TestAdminUsersView(TestController)'
263 300 params={'new_email': 'example@rhodecode.com',
264 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 305 response.mustcontain('example@rhodecode.com')
268 306
269 307 user_email = UserEmailMap.query()\
@@ -277,5 +315,469 b' class TestAdminUsersView(TestController)'
277 315 params={'del_email_id': del_email_id,
278 316 'csrf_token': self.csrf_token})
279 317
280 response = self.app.get(route_path('edit_user_emails', user_id=user_id))
281 response.mustcontain(no=['example@rhodecode.com']) No newline at end of file
318 response = self.app.get(
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, (689 lines changed) Show them Hide them
@@ -18,7 +18,6 b''
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 import time
22 21 import logging
23 22 import datetime
24 23 import formencode
@@ -26,51 +25,46 b' import formencode.htmlfill'
26 25
27 26 from pyramid.httpexceptions import HTTPFound
28 27 from pyramid.view import view_config
29 from sqlalchemy.sql.functions import coalesce
30 from sqlalchemy.exc import IntegrityError
28 from pyramid.renderers import render
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 32 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
33 from rhodecode.authentication.plugins import auth_rhodecode
34 34 from rhodecode.events import trigger
35 35
36 36 from rhodecode.lib import audit_logger
37 from rhodecode.lib.exceptions import (
38 UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException,
39 UserOwnsUserGroupsException, DefaultUserException)
37 40 from rhodecode.lib.ext_json import json
38 41 from rhodecode.lib.auth import (
39 42 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
40 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 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 50 from rhodecode.model.ssh_key import SshKeyModel
44 51 from rhodecode.model.user import UserModel
45 52 from rhodecode.model.user_group import UserGroupModel
46 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 56 from rhodecode.model.meta import Session
49 57
50 58 log = logging.getLogger(__name__)
51 59
52 60
53 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 63 def load_default_context(self):
61 64 c = self._get_local_tmpl_context()
62 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
63 65 self._register_global_c(c)
64 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 68 @LoginRequired()
75 69 @HasPermissionAllDecorator('hg.admin')
76 70 @view_config(
@@ -163,6 +157,529 b' class AdminUsersView(BaseAppView, DataGr'
163 157
164 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 683 @LoginRequired()
167 684 @HasPermissionAllDecorator('hg.admin')
168 685 @view_config(
@@ -171,10 +688,7 b' class AdminUsersView(BaseAppView, DataGr'
171 688 def auth_tokens(self):
172 689 _ = self.request.translate
173 690 c = self.load_default_context()
174
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)
691 c.user = self.db_user
178 692
179 693 c.active = 'auth_tokens'
180 694
@@ -200,10 +714,8 b' class AdminUsersView(BaseAppView, DataGr'
200 714 _ = self.request.translate
201 715 c = self.load_default_context()
202 716
203 user_id = self.request.matchdict.get('user_id')
204 c.user = User.get_or_404(user_id)
205
206 self._redirect_for_default_user(c.user.username)
717 user_id = self.db_user_id
718 c.user = self.db_user
207 719
208 720 user_data = c.user.get_api_data()
209 721 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
@@ -233,9 +745,9 b' class AdminUsersView(BaseAppView, DataGr'
233 745 _ = self.request.translate
234 746 c = self.load_default_context()
235 747
236 user_id = self.request.matchdict.get('user_id')
237 c.user = User.get_or_404(user_id)
238 self._redirect_for_default_user(c.user.username)
748 user_id = self.db_user_id
749 c.user = self.db_user
750
239 751 user_data = c.user.get_api_data()
240 752
241 753 del_auth_token = self.request.POST.get('del_auth_token')
@@ -262,10 +774,7 b' class AdminUsersView(BaseAppView, DataGr'
262 774 def ssh_keys(self):
263 775 _ = self.request.translate
264 776 c = self.load_default_context()
265
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)
777 c.user = self.db_user
269 778
270 779 c.active = 'ssh_keys'
271 780 c.default_key = self.request.GET.get('default_key')
@@ -281,9 +790,7 b' class AdminUsersView(BaseAppView, DataGr'
281 790 _ = self.request.translate
282 791 c = self.load_default_context()
283 792
284 user_id = self.request.matchdict.get('user_id')
285 c.user = User.get_or_404(user_id)
286 self._redirect_for_default_user(c.user.username)
793 c.user = self.db_user
287 794
288 795 c.active = 'ssh_keys_generate'
289 796 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
@@ -300,10 +807,8 b' class AdminUsersView(BaseAppView, DataGr'
300 807 _ = self.request.translate
301 808 c = self.load_default_context()
302 809
303 user_id = self.request.matchdict.get('user_id')
304 c.user = User.get_or_404(user_id)
305
306 self._redirect_for_default_user(c.user.username)
810 user_id = self.db_user_id
811 c.user = self.db_user
307 812
308 813 user_data = c.user.get_api_data()
309 814 key_data = self.request.POST.get('key_data')
@@ -353,9 +858,9 b' class AdminUsersView(BaseAppView, DataGr'
353 858 _ = self.request.translate
354 859 c = self.load_default_context()
355 860
356 user_id = self.request.matchdict.get('user_id')
357 c.user = User.get_or_404(user_id)
358 self._redirect_for_default_user(c.user.username)
861 user_id = self.db_user_id
862 c.user = self.db_user
863
359 864 user_data = c.user.get_api_data()
360 865
361 866 del_ssh_key = self.request.POST.get('del_ssh_key')
@@ -384,10 +889,7 b' class AdminUsersView(BaseAppView, DataGr'
384 889 def emails(self):
385 890 _ = self.request.translate
386 891 c = self.load_default_context()
387
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)
892 c.user = self.db_user
391 893
392 894 c.active = 'emails'
393 895 c.user_email_map = UserEmailMap.query() \
@@ -404,22 +906,26 b' class AdminUsersView(BaseAppView, DataGr'
404 906 _ = self.request.translate
405 907 c = self.load_default_context()
406 908
407 user_id = self.request.matchdict.get('user_id')
408 c.user = User.get_or_404(user_id)
409 self._redirect_for_default_user(c.user.username)
909 user_id = self.db_user_id
910 c.user = self.db_user
410 911
411 912 email = self.request.POST.get('new_email')
412 913 user_data = c.user.get_api_data()
413 914 try:
414 915 UserModel().add_extra_email(c.user.user_id, email)
415 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 919 user=self._rhodecode_user)
418 920 Session().commit()
419 921 h.flash(_("Added new email address `%s` for user account") % email,
420 922 category='success')
421 923 except formencode.Invalid as error:
422 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 929 except Exception:
424 930 log.exception("Exception during email saving")
425 931 h.flash(_('An error occurred during email saving'),
@@ -435,9 +941,8 b' class AdminUsersView(BaseAppView, DataGr'
435 941 _ = self.request.translate
436 942 c = self.load_default_context()
437 943
438 user_id = self.request.matchdict.get('user_id')
439 c.user = User.get_or_404(user_id)
440 self._redirect_for_default_user(c.user.username)
944 user_id = self.db_user_id
945 c.user = self.db_user
441 946
442 947 email_id = self.request.POST.get('del_email_id')
443 948 user_model = UserModel()
@@ -446,7 +951,8 b' class AdminUsersView(BaseAppView, DataGr'
446 951 user_data = c.user.get_api_data()
447 952 user_model.delete_extra_email(c.user.user_id, email_id)
448 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 956 user=self._rhodecode_user)
451 957 Session().commit()
452 958 h.flash(_("Removed email address from user account"),
@@ -461,10 +967,7 b' class AdminUsersView(BaseAppView, DataGr'
461 967 def ips(self):
462 968 _ = self.request.translate
463 969 c = self.load_default_context()
464
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)
970 c.user = self.db_user
468 971
469 972 c.active = 'ips'
470 973 c.user_ip_map = UserIpMap.query() \
@@ -481,14 +984,14 b' class AdminUsersView(BaseAppView, DataGr'
481 984 @CSRFRequired()
482 985 @view_config(
483 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 989 def ips_add(self):
485 990 _ = self.request.translate
486 991 c = self.load_default_context()
487 992
488 user_id = self.request.matchdict.get('user_id')
489 c.user = User.get_or_404(user_id)
490 # NOTE(marcink): this view is allowed for default users, as we can
491 # edit their IP white list
993 user_id = self.db_user_id
994 c.user = self.db_user
492 995
493 996 user_model = UserModel()
494 997 desc = self.request.POST.get('description')
@@ -506,7 +1009,8 b' class AdminUsersView(BaseAppView, DataGr'
506 1009 try:
507 1010 user_model.add_extra_ip(c.user.user_id, ip, desc)
508 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 1014 user=self._rhodecode_user)
511 1015 Session().commit()
512 1016 added.append(ip)
@@ -531,14 +1035,14 b' class AdminUsersView(BaseAppView, DataGr'
531 1035 @CSRFRequired()
532 1036 @view_config(
533 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 1040 def ips_delete(self):
535 1041 _ = self.request.translate
536 1042 c = self.load_default_context()
537 1043
538 user_id = self.request.matchdict.get('user_id')
539 c.user = User.get_or_404(user_id)
540 # NOTE(marcink): this view is allowed for default users, as we can
541 # edit their IP white list
1044 user_id = self.db_user_id
1045 c.user = self.db_user
542 1046
543 1047 ip_id = self.request.POST.get('del_ip_id')
544 1048 user_model = UserModel()
@@ -563,11 +1067,9 b' class AdminUsersView(BaseAppView, DataGr'
563 1067 renderer='rhodecode:templates/admin/users/user_edit.mako')
564 1068 def groups_management(self):
565 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 1073 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
572 1074 for group in c.user.group_member]
573 1075 c.groups = json.dumps(groups)
@@ -584,9 +1086,8 b' class AdminUsersView(BaseAppView, DataGr'
584 1086 _ = self.request.translate
585 1087 c = self.load_default_context()
586 1088
587 user_id = self.request.matchdict.get('user_id')
588 c.user = User.get_or_404(user_id)
589 self._redirect_for_default_user(c.user.username)
1089 user_id = self.db_user_id
1090 c.user = self.db_user
590 1091
591 1092 user_groups = set(self.request.POST.getall('users_group_id'))
592 1093 user_groups_objects = []
@@ -595,8 +1096,26 b' class AdminUsersView(BaseAppView, DataGr'
595 1096 user_groups_objects.append(
596 1097 UserGroupModel().get_group(safe_int(ugid)))
597 1098 user_group_model = UserGroupModel()
1099 added_to_groups, removed_from_groups = \
598 1100 user_group_model.change_groups(c.user, user_groups_objects)
599 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)
1118
600 1119 Session().commit()
601 1120 c.active = 'user_groups_management'
602 1121 h.flash(_("Groups successfully changed"), category='success')
@@ -612,10 +1131,8 b' class AdminUsersView(BaseAppView, DataGr'
612 1131 def user_audit_logs(self):
613 1132 _ = self.request.translate
614 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 1136 c.active = 'audit'
620 1137
621 1138 p = safe_int(self.request.GET.get('page', 1), 1)
@@ -641,10 +1158,7 b' class AdminUsersView(BaseAppView, DataGr'
641 1158 def user_perms_summary(self):
642 1159 _ = self.request.translate
643 1160 c = self.load_default_context()
644
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)
1161 c.user = self.db_user
648 1162
649 1163 c.active = 'perms_summary'
650 1164 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
@@ -658,11 +1172,6 b' class AdminUsersView(BaseAppView, DataGr'
658 1172 renderer='json_ext')
659 1173 def user_perms_summary_json(self):
660 1174 self.load_default_context()
661
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)
1175 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
667 1176
668 1177 return perm_user.permissions
@@ -115,7 +115,6 b' def load_environment(global_conf, app_co'
115 115 'secret': config.get('channelstream.secret')
116 116 }
117 117
118 set_available_permissions(config)
119 118 db_cfg = make_db_config(clear_session=True)
120 119
121 120 repos_path = list(db_cfg.items('paths'))[0][1]
@@ -178,5 +177,6 b' def load_pyramid_environment(global_conf'
178 177 log_level=settings['vcs.server.log_level'])
179 178
180 179 utils.configure_vcs(settings)
180
181 181 if vcs_server_enabled:
182 182 connect_vcs(vcs_server_uri, utils.get_vcs_server_protocol(settings))
@@ -41,6 +41,7 b' import rhodecode'
41 41
42 42 from rhodecode.model import meta
43 43 from rhodecode.config import patches
44 from rhodecode.config import utils as config_utils
44 45 from rhodecode.config.routing import STATIC_FILE_PREFIX
45 46 from rhodecode.config.environment import (
46 47 load_environment, load_pyramid_environment)
@@ -56,7 +57,7 b' from rhodecode.lib.plugins.utils import '
56 57 from rhodecode.lib.utils2 import aslist as rhodecode_aslist, AttributeDict
57 58 from rhodecode.subscribers import (
58 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 63 log = logging.getLogger(__name__)
@@ -146,11 +147,12 b' def make_pyramid_app(global_config, **se'
146 147 settings_pylons = settings.copy()
147 148
148 149 sanitize_settings_and_apply_defaults(settings)
150
149 151 config = Configurator(settings=settings)
152 load_pyramid_environment(global_config, settings)
153
150 154 add_pylons_compat_data(config.registry, global_config, settings_pylons)
151 155
152 load_pyramid_environment(global_config, settings)
153
154 156 includeme_first(config)
155 157 includeme(config)
156 158
@@ -315,6 +317,7 b' def includeme(config):'
315 317 settings['default_locale_name'] = settings.get('lang', 'en')
316 318
317 319 # Add subscribers.
320 config.add_subscriber(inject_app_settings, ApplicationCreated)
318 321 config.add_subscriber(scan_repositories_if_enabled, ApplicationCreated)
319 322 config.add_subscriber(write_metadata_if_needed, ApplicationCreated)
320 323 config.add_subscriber(write_js_routes_if_enabled, ApplicationCreated)
@@ -472,6 +475,9 b' def sanitize_settings_and_apply_defaults'
472 475 _sanitize_appenlight_settings(settings)
473 476 _sanitize_vcs_settings(settings)
474 477
478 # configure instance id
479 config_utils.set_instance_id(settings)
480
475 481 return settings
476 482
477 483
@@ -219,37 +219,6 b' def make_map(config):'
219 219 'function': check_group},
220 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 222 # ADMIN SETTINGS ROUTES
254 223 with rmap.submapper(path_prefix=ADMIN_PREFIX,
255 224 controller='admin/settings') as m:
@@ -339,5 +308,4 b' def make_map(config):'
339 308 m.connect('my_account_password', '/my_account/password',
340 309 action='my_account_password', conditions={'method': ['GET']})
341 310
342
343 311 return rmap
@@ -1012,13 +1012,16 b' class AuthUser(object):'
1012 1012 log.debug('No data in %s that could been used to log in', self)
1013 1013
1014 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 1017 # if we cannot authenticate user try anonymous
1017 1018 if anon_user.active:
1019 log.debug('default user is active, using it as a session user')
1018 1020 user_model.fill_data(self, user_id=anon_user.user_id)
1019 1021 # then we set this user is logged in
1020 1022 self.is_authenticated = True
1021 1023 else:
1024 log.debug('default user is NOT active')
1022 1025 # in case of disabled anonymous user we reset some of the
1023 1026 # parameters so such user is "corrupted", skipping the fill_data
1024 1027 for attr in ['user_id', 'username', 'admin', 'active']:
@@ -1277,25 +1280,26 b' class AuthUser(object):'
1277 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 1286 permission given in db. We don't want to check each time from db for new
1284 1287 permissions since adding a new permission also requires application restart
1285 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 1294 try:
1292 1295 sa = meta.Session
1293 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 1300 except Exception:
1296 log.error(traceback.format_exc())
1297 finally:
1298 meta.Session.remove()
1301 log.exception('Failed to fetch permissions from the database.')
1302 raise
1299 1303
1300 1304
1301 1305 def get_csrf_token(session, force_new=False, save_if_missing=True):
@@ -681,6 +681,17 b' class User(Base, BaseModel):'
681 681 return 'NO_FEED_TOKEN_AVAILABLE'
682 682
683 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 695 def extra_valid_auth_tokens(cls, user, role=None):
685 696 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
686 697 .filter(or_(UserApiKeys.expires == -1,
@@ -1341,6 +1352,9 b' class UserGroup(Base, BaseModel):'
1341 1352
1342 1353 @classmethod
1343 1354 def get(cls, user_group_id, cache=False):
1355 if not user_group_id:
1356 return
1357
1344 1358 user_group = cls.query()
1345 1359 if cache:
1346 1360 user_group = user_group.options(
@@ -554,16 +554,22 b' class UserGroupModel(BaseModel):'
554 554 groups_to_remove = current_groups - groups
555 555 groups_to_add = groups - current_groups
556 556
557 removed_from_groups = []
558 added_to_groups = []
557 559 for gr in groups_to_remove:
558 560 log.debug('Removing user %s from user group %s',
559 561 user.username, gr.users_group_name)
562 removed_from_groups.append(gr.users_group_id)
560 563 self.remove_user_from_group(gr.users_group_name, user.username)
561 564 for gr in groups_to_add:
562 565 log.debug('Adding user %s to user group %s',
563 566 user.username, gr.users_group_name)
567 added_to_groups.append(gr.users_group_id)
564 568 UserGroupModel().add_user_to_group(
565 569 gr.users_group_name, user.username)
566 570
571 return added_to_groups, removed_from_groups
572
567 573 def _serialize_user_group(self, user_group):
568 574 import rhodecode.lib.helpers as h
569 575 return {
@@ -12,7 +12,6 b''
12 12 ******************************************************************************/
13 13 function registerRCRoutes() {
14 14 // routes registration
15 pyroutes.register('edit_user', '/_admin/users/%(user_id)s/edit', ['user_id']);
16 15 pyroutes.register('favicon', '/favicon.ico', []);
17 16 pyroutes.register('robots', '/robots.txt', []);
18 17 pyroutes.register('auth_home', '/_admin/auth*traverse', []);
@@ -66,6 +65,16 b' function registerRCRoutes() {'
66 65 pyroutes.register('admin_permissions_ssh_keys_update', '/_admin/permissions/ssh_keys/update', []);
67 66 pyroutes.register('users', '/_admin/users', []);
68 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 78 pyroutes.register('edit_user_auth_tokens', '/_admin/users/%(user_id)s/edit/auth_tokens', ['user_id']);
70 79 pyroutes.register('edit_user_auth_tokens_add', '/_admin/users/%(user_id)s/edit/auth_tokens/new', ['user_id']);
71 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 36 from rhodecode.translation import _ as tsf
37 37 from rhodecode.config.jsroutes import generate_jsroutes_content
38 from rhodecode.lib import auth
38 39
39 40 import rhodecode
40 41
@@ -140,6 +141,12 b' def add_pylons_context(event):'
140 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 150 def scan_repositories_if_enabled(event):
144 151 """
145 152 This is subscribed to the `pyramid.events.ApplicationCreated` event. It
@@ -102,7 +102,6 b' var select2Options = {'
102 102 };
103 103 $("#role").select2(select2Options);
104 104
105
106 105 var preloadData = {
107 106 results: [
108 107 % for entry in c.lifetime_values:
@@ -77,7 +77,7 b''
77 77 <td id="member_user_${user.user_id}" class="td-author">
78 78 <div class="group_member">
79 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 81 <input type="hidden" name="__start__" value="member:mapping">
82 82 <input type="hidden" name="member_user_id" value="${user.user_id}">
83 83 <input type="hidden" name="type" value="existing" id="member_${user.user_id}">
@@ -134,7 +134,7 b''
134 134 function addMember(user, fromUserGroup) {
135 135 var gravatar = user.icon_link;
136 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 138 var uid = user.id;
139 139
140 140 if (fromUserGroup) {
@@ -26,7 +26,7 b''
26 26 ${self.breadcrumbs()}
27 27 </div>
28 28 <!-- end box / title -->
29 ${h.secure_form(h.url('users'))}
29 ${h.secure_form(h.route_path('users_create'), request=request)}
30 30 <div class="form">
31 31 <!-- fields -->
32 32 <div class="fields">
@@ -35,11 +35,11 b''
35 35 <div class="sidebar-col-wrapper">
36 36 <div class="sidebar">
37 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 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 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>
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>
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.route_path('user_edit_global_perms', user_id=c.user.user_id)}">${_('Global permissions')}</a></li>
43 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 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 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 34 <h3 class="panel-title">${_('Force Password Reset')}</h3>
35 35 </div>
36 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 38 <div class="field">
39 39 <button class="btn btn-default" type="submit">
40 40 <i class="icon-lock"></i>
@@ -59,7 +59,7 b''
59 59 <h3 class="panel-title">${_('Personal Repository Group')}</h3>
60 60 </div>
61 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 64 %if c.personal_repo_group:
65 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 84 <h3 class="panel-title">${_('Delete User')}</h3>
85 85 </div>
86 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 89 <table class="display">
90 90 <tr>
@@ -92,6 +92,7 b''
92 92 <script>
93 93
94 94 $(document).ready(function(){
95
95 96 var select2Options = {
96 97 'containerCssClass': "drop-menu",
97 98 'dropdownCssClass': "drop-menu-dropdown",
@@ -1,2 +1,2 b''
1 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,7 +61,7 b' var api;'
61 61 render: function (data,type,full,meta)
62 62 {return '<input type="hidden" name="users_group_id" value="'+data+'">'}},
63 63 { data: {"_": "active",
64 "sort": "active"}, title: "${_('Active')}", className: "td-active", className: "td-number"},
64 "sort": "active"}, title: "${_('Active')}", className: "td-active"},
65 65 { data: {"_": "owner_data"}, title: "${_('Owner')}", className: "td-user",
66 66 render: function (data,type,full,meta)
67 67 {return '<div class="rc-user tooltip">'+
@@ -72,8 +72,8 b' var api;'
72 72 { data: null,
73 73 title: "${_('Action')}",
74 74 className: "td-action",
75 defaultContent: '<a href="" class="btn btn-link btn-danger">Delete</a>'
76 },
75 defaultContent: '-'
76 }
77 77 ],
78 78 language: {
79 79 paginate: DEFAULT_GRID_PAGINATION,
@@ -6,7 +6,7 b''
6 6 </div>
7 7 <div class="panel-body">
8 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 10 <% readonly = None %>
11 11 <% disabled = "" %>
12 12 %if c.extern_type != 'rhodecode':
@@ -25,7 +25,7 b''
25 25 ${self.breadcrumbs()}
26 26 <ul class="links">
27 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 29 </li>
30 30 </ul>
31 31 </div>
@@ -124,22 +124,22 b''
124 124 edit_url=None, edit_global_url=h.route_path('admin_permissions_object'))}
125 125
126 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 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 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 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 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 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 144 </tbody>
145 145 %else:
@@ -250,11 +250,11 b''
250 250
251 251 <%def name="user_actions(user_id, username)">
252 252 <div class="grid_edit">
253 <a href="${h.url('edit_user',user_id=user_id)}" title="${_('Edit')}">
254 <i class="icon-pencil"></i>Edit</a>
253 <a href="${h.route_path('user_edit',user_id=user_id)}" title="${_('Edit')}">
254 <i class="icon-pencil"></i>${_('Edit')}</a>
255 255 </div>
256 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 258 ${h.submit('remove_',_('Delete'),id="remove_user_%s" % user_id, class_="btn btn-link btn-danger",
259 259 onclick="return confirm('"+_('Confirm to delete this user: %s') % username+"');")}
260 260 ${h.end_form()}
@@ -275,7 +275,7 b''
275 275
276 276
277 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 279 </%def>
280 280
281 281 <%def name="user_profile(username)">
@@ -4,7 +4,7 b''
4 4 <div class="panel-heading">
5 5 <h3 class="panel-title">${_('Profile')}</h3>
6 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 8 %endif
9 9 </div>
10 10
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
This diff has been collapsed as it changes many lines, (512 lines changed) Show them Hide them
General Comments 0
You need to be logged in to leave comments. Login now