##// END OF EJS Templates
cleanup: removing unused grav_tmpl function
lisaq -
r497:096f9488 default
parent child Browse files
Show More
@@ -1,717 +1,714 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2016 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Users crud controller for pylons
23 23 """
24 24
25 25 import logging
26 26 import formencode
27 27
28 28 from formencode import htmlfill
29 29 from pylons import request, tmpl_context as c, url, config
30 30 from pylons.controllers.util import redirect
31 31 from pylons.i18n.translation import _
32 32
33 33 from rhodecode.authentication.plugins import auth_rhodecode
34 34 from rhodecode.lib.exceptions import (
35 35 DefaultUserException, UserOwnsReposException, UserOwnsRepoGroupsException,
36 36 UserOwnsUserGroupsException, UserCreationError)
37 37 from rhodecode.lib import helpers as h
38 38 from rhodecode.lib import auth
39 39 from rhodecode.lib.auth import (
40 40 LoginRequired, HasPermissionAllDecorator, AuthUser, generate_auth_token)
41 41 from rhodecode.lib.base import BaseController, render
42 42 from rhodecode.model.auth_token import AuthTokenModel
43 43
44 44 from rhodecode.model.db import (
45 45 PullRequestReviewers, User, UserEmailMap, UserIpMap, RepoGroup)
46 46 from rhodecode.model.forms import (
47 47 UserForm, UserPermissionsForm, UserIndividualPermissionsForm)
48 48 from rhodecode.model.user import UserModel
49 49 from rhodecode.model.meta import Session
50 50 from rhodecode.model.permission import PermissionModel
51 51 from rhodecode.lib.utils import action_logger
52 52 from rhodecode.lib.ext_json import json
53 53 from rhodecode.lib.utils2 import datetime_to_time, safe_int
54 54
55 55 log = logging.getLogger(__name__)
56 56
57 57
58 58 class UsersController(BaseController):
59 59 """REST Controller styled on the Atom Publishing Protocol"""
60 60
61 61 @LoginRequired()
62 62 def __before__(self):
63 63 super(UsersController, self).__before__()
64 64 c.available_permissions = config['available_permissions']
65 65 c.allowed_languages = [
66 66 ('en', 'English (en)'),
67 67 ('de', 'German (de)'),
68 68 ('fr', 'French (fr)'),
69 69 ('it', 'Italian (it)'),
70 70 ('ja', 'Japanese (ja)'),
71 71 ('pl', 'Polish (pl)'),
72 72 ('pt', 'Portuguese (pt)'),
73 73 ('ru', 'Russian (ru)'),
74 74 ('zh', 'Chinese (zh)'),
75 75 ]
76 76 PermissionModel().set_global_permission_choices(c, translator=_)
77 77
78 78 @HasPermissionAllDecorator('hg.admin')
79 79 def index(self):
80 80 """GET /users: All items in the collection"""
81 81 # url('users')
82 82
83 83 from rhodecode.lib.utils import PartialRenderer
84 84 _render = PartialRenderer('data_table/_dt_elements.html')
85 85
86 def grav_tmpl(user_email, size):
87 return _render("user_gravatar", user_email, size)
88
89 86 def username(user_id, username):
90 87 return _render("user_name", user_id, username)
91 88
92 89 def user_actions(user_id, username):
93 90 return _render("user_actions", user_id, username)
94 91
95 92 # json generate
96 93 c.users_list = User.query()\
97 94 .filter(User.username != User.DEFAULT_USER) \
98 95 .all()
99 96
100 97 users_data = []
101 98 for user in c.users_list:
102 99 users_data.append({
103 100 "username": h.gravatar_with_user(user.username),
104 101 "username_raw": user.username,
105 102 "email": user.email,
106 103 "first_name": h.escape(user.name),
107 104 "last_name": h.escape(user.lastname),
108 105 "last_login": h.format_date(user.last_login),
109 106 "last_login_raw": datetime_to_time(user.last_login),
110 107 "last_activity": h.format_date(
111 108 h.time_to_datetime(user.user_data.get('last_activity', 0))),
112 109 "last_activity_raw": user.user_data.get('last_activity', 0),
113 110 "active": h.bool2icon(user.active),
114 111 "active_raw": user.active,
115 112 "admin": h.bool2icon(user.admin),
116 113 "admin_raw": user.admin,
117 114 "extern_type": user.extern_type,
118 115 "extern_name": user.extern_name,
119 116 "action": user_actions(user.user_id, user.username),
120 117 })
121 118
122 119
123 120 c.data = json.dumps(users_data)
124 121 return render('admin/users/users.html')
125 122
126 123 @HasPermissionAllDecorator('hg.admin')
127 124 @auth.CSRFRequired()
128 125 def create(self):
129 126 """POST /users: Create a new item"""
130 127 # url('users')
131 128 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
132 129 user_model = UserModel()
133 130 user_form = UserForm()()
134 131 try:
135 132 form_result = user_form.to_python(dict(request.POST))
136 133 user = user_model.create(form_result)
137 134 Session().flush()
138 135 username = form_result['username']
139 136 action_logger(c.rhodecode_user, 'admin_created_user:%s' % username,
140 137 None, self.ip_addr, self.sa)
141 138
142 139 user_link = h.link_to(h.escape(username),
143 140 url('edit_user',
144 141 user_id=user.user_id))
145 142 h.flash(h.literal(_('Created user %(user_link)s')
146 143 % {'user_link': user_link}), category='success')
147 144 Session().commit()
148 145 except formencode.Invalid as errors:
149 146 return htmlfill.render(
150 147 render('admin/users/user_add.html'),
151 148 defaults=errors.value,
152 149 errors=errors.error_dict or {},
153 150 prefix_error=False,
154 151 encoding="UTF-8",
155 152 force_defaults=False)
156 153 except UserCreationError as e:
157 154 h.flash(e, 'error')
158 155 except Exception:
159 156 log.exception("Exception creation of user")
160 157 h.flash(_('Error occurred during creation of user %s')
161 158 % request.POST.get('username'), category='error')
162 159 return redirect(url('users'))
163 160
164 161 @HasPermissionAllDecorator('hg.admin')
165 162 def new(self):
166 163 """GET /users/new: Form to create a new item"""
167 164 # url('new_user')
168 165 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
169 166 return render('admin/users/user_add.html')
170 167
171 168 @HasPermissionAllDecorator('hg.admin')
172 169 @auth.CSRFRequired()
173 170 def update(self, user_id):
174 171 """PUT /users/user_id: Update an existing item"""
175 172 # Forms posted to this method should contain a hidden field:
176 173 # <input type="hidden" name="_method" value="PUT" />
177 174 # Or using helpers:
178 175 # h.form(url('update_user', user_id=ID),
179 176 # method='put')
180 177 # url('user', user_id=ID)
181 178 user_id = safe_int(user_id)
182 179 c.user = User.get_or_404(user_id)
183 180 c.active = 'profile'
184 181 c.extern_type = c.user.extern_type
185 182 c.extern_name = c.user.extern_name
186 183 c.perm_user = AuthUser(user_id=user_id, ip_addr=self.ip_addr)
187 184 available_languages = [x[0] for x in c.allowed_languages]
188 185 _form = UserForm(edit=True, available_languages=available_languages,
189 186 old_data={'user_id': user_id,
190 187 'email': c.user.email})()
191 188 form_result = {}
192 189 try:
193 190 form_result = _form.to_python(dict(request.POST))
194 191 skip_attrs = ['extern_type', 'extern_name']
195 192 # TODO: plugin should define if username can be updated
196 193 if c.extern_type != "rhodecode":
197 194 # forbid updating username for external accounts
198 195 skip_attrs.append('username')
199 196
200 197 UserModel().update_user(user_id, skip_attrs=skip_attrs, **form_result)
201 198 usr = form_result['username']
202 199 action_logger(c.rhodecode_user, 'admin_updated_user:%s' % usr,
203 200 None, self.ip_addr, self.sa)
204 201 h.flash(_('User updated successfully'), category='success')
205 202 Session().commit()
206 203 except formencode.Invalid as errors:
207 204 defaults = errors.value
208 205 e = errors.error_dict or {}
209 206
210 207 return htmlfill.render(
211 208 render('admin/users/user_edit.html'),
212 209 defaults=defaults,
213 210 errors=e,
214 211 prefix_error=False,
215 212 encoding="UTF-8",
216 213 force_defaults=False)
217 214 except UserCreationError as e:
218 215 h.flash(e, 'error')
219 216 except Exception:
220 217 log.exception("Exception updating user")
221 218 h.flash(_('Error occurred during update of user %s')
222 219 % form_result.get('username'), category='error')
223 220 return redirect(url('edit_user', user_id=user_id))
224 221
225 222 @HasPermissionAllDecorator('hg.admin')
226 223 @auth.CSRFRequired()
227 224 def delete(self, user_id):
228 225 """DELETE /users/user_id: Delete an existing item"""
229 226 # Forms posted to this method should contain a hidden field:
230 227 # <input type="hidden" name="_method" value="DELETE" />
231 228 # Or using helpers:
232 229 # h.form(url('delete_user', user_id=ID),
233 230 # method='delete')
234 231 # url('user', user_id=ID)
235 232 user_id = safe_int(user_id)
236 233 c.user = User.get_or_404(user_id)
237 234
238 235 _repos = c.user.repositories
239 236 _repo_groups = c.user.repository_groups
240 237 _user_groups = c.user.user_groups
241 238
242 239 handle_repos = None
243 240 handle_repo_groups = None
244 241 handle_user_groups = None
245 242 # dummy call for flash of handle
246 243 set_handle_flash_repos = lambda: None
247 244 set_handle_flash_repo_groups = lambda: None
248 245 set_handle_flash_user_groups = lambda: None
249 246
250 247 if _repos and request.POST.get('user_repos'):
251 248 do = request.POST['user_repos']
252 249 if do == 'detach':
253 250 handle_repos = 'detach'
254 251 set_handle_flash_repos = lambda: h.flash(
255 252 _('Detached %s repositories') % len(_repos),
256 253 category='success')
257 254 elif do == 'delete':
258 255 handle_repos = 'delete'
259 256 set_handle_flash_repos = lambda: h.flash(
260 257 _('Deleted %s repositories') % len(_repos),
261 258 category='success')
262 259
263 260 if _repo_groups and request.POST.get('user_repo_groups'):
264 261 do = request.POST['user_repo_groups']
265 262 if do == 'detach':
266 263 handle_repo_groups = 'detach'
267 264 set_handle_flash_repo_groups = lambda: h.flash(
268 265 _('Detached %s repository groups') % len(_repo_groups),
269 266 category='success')
270 267 elif do == 'delete':
271 268 handle_repo_groups = 'delete'
272 269 set_handle_flash_repo_groups = lambda: h.flash(
273 270 _('Deleted %s repository groups') % len(_repo_groups),
274 271 category='success')
275 272
276 273 if _user_groups and request.POST.get('user_user_groups'):
277 274 do = request.POST['user_user_groups']
278 275 if do == 'detach':
279 276 handle_user_groups = 'detach'
280 277 set_handle_flash_user_groups = lambda: h.flash(
281 278 _('Detached %s user groups') % len(_user_groups),
282 279 category='success')
283 280 elif do == 'delete':
284 281 handle_user_groups = 'delete'
285 282 set_handle_flash_user_groups = lambda: h.flash(
286 283 _('Deleted %s user groups') % len(_user_groups),
287 284 category='success')
288 285
289 286 try:
290 287 UserModel().delete(c.user, handle_repos=handle_repos,
291 288 handle_repo_groups=handle_repo_groups,
292 289 handle_user_groups=handle_user_groups)
293 290 Session().commit()
294 291 set_handle_flash_repos()
295 292 set_handle_flash_repo_groups()
296 293 set_handle_flash_user_groups()
297 294 h.flash(_('Successfully deleted user'), category='success')
298 295 except (UserOwnsReposException, UserOwnsRepoGroupsException,
299 296 UserOwnsUserGroupsException, DefaultUserException) as e:
300 297 h.flash(e, category='warning')
301 298 except Exception:
302 299 log.exception("Exception during deletion of user")
303 300 h.flash(_('An error occurred during deletion of user'),
304 301 category='error')
305 302 return redirect(url('users'))
306 303
307 304 @HasPermissionAllDecorator('hg.admin')
308 305 @auth.CSRFRequired()
309 306 def reset_password(self, user_id):
310 307 """
311 308 toggle reset password flag for this user
312 309
313 310 :param user_id:
314 311 """
315 312 user_id = safe_int(user_id)
316 313 c.user = User.get_or_404(user_id)
317 314 try:
318 315 old_value = c.user.user_data.get('force_password_change')
319 316 c.user.update_userdata(force_password_change=not old_value)
320 317 Session().commit()
321 318 if old_value:
322 319 msg = _('Force password change disabled for user')
323 320 else:
324 321 msg = _('Force password change enabled for user')
325 322 h.flash(msg, category='success')
326 323 except Exception:
327 324 log.exception("Exception during password reset for user")
328 325 h.flash(_('An error occurred during password reset for user'),
329 326 category='error')
330 327
331 328 return redirect(url('edit_user_advanced', user_id=user_id))
332 329
333 330 @HasPermissionAllDecorator('hg.admin')
334 331 @auth.CSRFRequired()
335 332 def create_personal_repo_group(self, user_id):
336 333 """
337 334 Create personal repository group for this user
338 335
339 336 :param user_id:
340 337 """
341 338 from rhodecode.model.repo_group import RepoGroupModel
342 339
343 340 user_id = safe_int(user_id)
344 341 c.user = User.get_or_404(user_id)
345 342
346 343 try:
347 344 desc = RepoGroupModel.PERSONAL_GROUP_DESC % {
348 345 'username': c.user.username}
349 346 if not RepoGroup.get_by_group_name(c.user.username):
350 347 RepoGroupModel().create(group_name=c.user.username,
351 348 group_description=desc,
352 349 owner=c.user.username)
353 350
354 351 msg = _('Created repository group `%s`' % (c.user.username,))
355 352 h.flash(msg, category='success')
356 353 except Exception:
357 354 log.exception("Exception during repository group creation")
358 355 msg = _(
359 356 'An error occurred during repository group creation for user')
360 357 h.flash(msg, category='error')
361 358
362 359 return redirect(url('edit_user_advanced', user_id=user_id))
363 360
364 361 @HasPermissionAllDecorator('hg.admin')
365 362 def show(self, user_id):
366 363 """GET /users/user_id: Show a specific item"""
367 364 # url('user', user_id=ID)
368 365 User.get_or_404(-1)
369 366
370 367 @HasPermissionAllDecorator('hg.admin')
371 368 def edit(self, user_id):
372 369 """GET /users/user_id/edit: Form to edit an existing item"""
373 370 # url('edit_user', user_id=ID)
374 371 user_id = safe_int(user_id)
375 372 c.user = User.get_or_404(user_id)
376 373 if c.user.username == User.DEFAULT_USER:
377 374 h.flash(_("You can't edit this user"), category='warning')
378 375 return redirect(url('users'))
379 376
380 377 c.active = 'profile'
381 378 c.extern_type = c.user.extern_type
382 379 c.extern_name = c.user.extern_name
383 380 c.perm_user = AuthUser(user_id=user_id, ip_addr=self.ip_addr)
384 381
385 382 defaults = c.user.get_dict()
386 383 defaults.update({'language': c.user.user_data.get('language')})
387 384 return htmlfill.render(
388 385 render('admin/users/user_edit.html'),
389 386 defaults=defaults,
390 387 encoding="UTF-8",
391 388 force_defaults=False)
392 389
393 390 @HasPermissionAllDecorator('hg.admin')
394 391 def edit_advanced(self, user_id):
395 392 user_id = safe_int(user_id)
396 393 user = c.user = User.get_or_404(user_id)
397 394 if user.username == User.DEFAULT_USER:
398 395 h.flash(_("You can't edit this user"), category='warning')
399 396 return redirect(url('users'))
400 397
401 398 c.active = 'advanced'
402 399 c.perm_user = AuthUser(user_id=user_id, ip_addr=self.ip_addr)
403 400 c.personal_repo_group = RepoGroup.get_by_group_name(user.username)
404 401 c.first_admin = User.get_first_super_admin()
405 402 defaults = user.get_dict()
406 403
407 404 # Interim workaround if the user participated on any pull requests as a
408 405 # reviewer.
409 406 has_review = bool(PullRequestReviewers.query().filter(
410 407 PullRequestReviewers.user_id == user_id).first())
411 408 c.can_delete_user = not has_review
412 409 c.can_delete_user_message = _(
413 410 'The user participates as reviewer in pull requests and '
414 411 'cannot be deleted. You can set the user to '
415 412 '"inactive" instead of deleting it.') if has_review else ''
416 413
417 414 return htmlfill.render(
418 415 render('admin/users/user_edit.html'),
419 416 defaults=defaults,
420 417 encoding="UTF-8",
421 418 force_defaults=False)
422 419
423 420 @HasPermissionAllDecorator('hg.admin')
424 421 def edit_auth_tokens(self, user_id):
425 422 user_id = safe_int(user_id)
426 423 c.user = User.get_or_404(user_id)
427 424 if c.user.username == User.DEFAULT_USER:
428 425 h.flash(_("You can't edit this user"), category='warning')
429 426 return redirect(url('users'))
430 427
431 428 c.active = 'auth_tokens'
432 429 show_expired = True
433 430 c.lifetime_values = [
434 431 (str(-1), _('forever')),
435 432 (str(5), _('5 minutes')),
436 433 (str(60), _('1 hour')),
437 434 (str(60 * 24), _('1 day')),
438 435 (str(60 * 24 * 30), _('1 month')),
439 436 ]
440 437 c.lifetime_options = [(c.lifetime_values, _("Lifetime"))]
441 438 c.role_values = [(x, AuthTokenModel.cls._get_role_name(x))
442 439 for x in AuthTokenModel.cls.ROLES]
443 440 c.role_options = [(c.role_values, _("Role"))]
444 441 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
445 442 c.user.user_id, show_expired=show_expired)
446 443 defaults = c.user.get_dict()
447 444 return htmlfill.render(
448 445 render('admin/users/user_edit.html'),
449 446 defaults=defaults,
450 447 encoding="UTF-8",
451 448 force_defaults=False)
452 449
453 450 @HasPermissionAllDecorator('hg.admin')
454 451 @auth.CSRFRequired()
455 452 def add_auth_token(self, user_id):
456 453 user_id = safe_int(user_id)
457 454 c.user = User.get_or_404(user_id)
458 455 if c.user.username == User.DEFAULT_USER:
459 456 h.flash(_("You can't edit this user"), category='warning')
460 457 return redirect(url('users'))
461 458
462 459 lifetime = safe_int(request.POST.get('lifetime'), -1)
463 460 description = request.POST.get('description')
464 461 role = request.POST.get('role')
465 462 AuthTokenModel().create(c.user.user_id, description, lifetime, role)
466 463 Session().commit()
467 464 h.flash(_("Auth token successfully created"), category='success')
468 465 return redirect(url('edit_user_auth_tokens', user_id=c.user.user_id))
469 466
470 467 @HasPermissionAllDecorator('hg.admin')
471 468 @auth.CSRFRequired()
472 469 def delete_auth_token(self, user_id):
473 470 user_id = safe_int(user_id)
474 471 c.user = User.get_or_404(user_id)
475 472 if c.user.username == User.DEFAULT_USER:
476 473 h.flash(_("You can't edit this user"), category='warning')
477 474 return redirect(url('users'))
478 475
479 476 auth_token = request.POST.get('del_auth_token')
480 477 if request.POST.get('del_auth_token_builtin'):
481 478 user = User.get(c.user.user_id)
482 479 if user:
483 480 user.api_key = generate_auth_token(user.username)
484 481 Session().add(user)
485 482 Session().commit()
486 483 h.flash(_("Auth token successfully reset"), category='success')
487 484 elif auth_token:
488 485 AuthTokenModel().delete(auth_token, c.user.user_id)
489 486 Session().commit()
490 487 h.flash(_("Auth token successfully deleted"), category='success')
491 488
492 489 return redirect(url('edit_user_auth_tokens', user_id=c.user.user_id))
493 490
494 491 @HasPermissionAllDecorator('hg.admin')
495 492 def edit_global_perms(self, user_id):
496 493 user_id = safe_int(user_id)
497 494 c.user = User.get_or_404(user_id)
498 495 if c.user.username == User.DEFAULT_USER:
499 496 h.flash(_("You can't edit this user"), category='warning')
500 497 return redirect(url('users'))
501 498
502 499 c.active = 'global_perms'
503 500
504 501 c.default_user = User.get_default_user()
505 502 defaults = c.user.get_dict()
506 503 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
507 504 defaults.update(c.default_user.get_default_perms())
508 505 defaults.update(c.user.get_default_perms())
509 506
510 507 return htmlfill.render(
511 508 render('admin/users/user_edit.html'),
512 509 defaults=defaults,
513 510 encoding="UTF-8",
514 511 force_defaults=False)
515 512
516 513 @HasPermissionAllDecorator('hg.admin')
517 514 @auth.CSRFRequired()
518 515 def update_global_perms(self, user_id):
519 516 """PUT /users_perm/user_id: Update an existing item"""
520 517 # url('user_perm', user_id=ID, method='put')
521 518 user_id = safe_int(user_id)
522 519 user = User.get_or_404(user_id)
523 520 c.active = 'global_perms'
524 521 try:
525 522 # first stage that verifies the checkbox
526 523 _form = UserIndividualPermissionsForm()
527 524 form_result = _form.to_python(dict(request.POST))
528 525 inherit_perms = form_result['inherit_default_permissions']
529 526 user.inherit_default_permissions = inherit_perms
530 527 Session().add(user)
531 528
532 529 if not inherit_perms:
533 530 # only update the individual ones if we un check the flag
534 531 _form = UserPermissionsForm(
535 532 [x[0] for x in c.repo_create_choices],
536 533 [x[0] for x in c.repo_create_on_write_choices],
537 534 [x[0] for x in c.repo_group_create_choices],
538 535 [x[0] for x in c.user_group_create_choices],
539 536 [x[0] for x in c.fork_choices],
540 537 [x[0] for x in c.inherit_default_permission_choices])()
541 538
542 539 form_result = _form.to_python(dict(request.POST))
543 540 form_result.update({'perm_user_id': user.user_id})
544 541
545 542 PermissionModel().update_user_permissions(form_result)
546 543
547 544 Session().commit()
548 545 h.flash(_('User global permissions updated successfully'),
549 546 category='success')
550 547
551 548 Session().commit()
552 549 except formencode.Invalid as errors:
553 550 defaults = errors.value
554 551 c.user = user
555 552 return htmlfill.render(
556 553 render('admin/users/user_edit.html'),
557 554 defaults=defaults,
558 555 errors=errors.error_dict or {},
559 556 prefix_error=False,
560 557 encoding="UTF-8",
561 558 force_defaults=False)
562 559 except Exception:
563 560 log.exception("Exception during permissions saving")
564 561 h.flash(_('An error occurred during permissions saving'),
565 562 category='error')
566 563 return redirect(url('edit_user_global_perms', user_id=user_id))
567 564
568 565 @HasPermissionAllDecorator('hg.admin')
569 566 def edit_perms_summary(self, user_id):
570 567 user_id = safe_int(user_id)
571 568 c.user = User.get_or_404(user_id)
572 569 if c.user.username == User.DEFAULT_USER:
573 570 h.flash(_("You can't edit this user"), category='warning')
574 571 return redirect(url('users'))
575 572
576 573 c.active = 'perms_summary'
577 574 c.perm_user = AuthUser(user_id=user_id, ip_addr=self.ip_addr)
578 575
579 576 return render('admin/users/user_edit.html')
580 577
581 578 @HasPermissionAllDecorator('hg.admin')
582 579 def edit_emails(self, user_id):
583 580 user_id = safe_int(user_id)
584 581 c.user = User.get_or_404(user_id)
585 582 if c.user.username == User.DEFAULT_USER:
586 583 h.flash(_("You can't edit this user"), category='warning')
587 584 return redirect(url('users'))
588 585
589 586 c.active = 'emails'
590 587 c.user_email_map = UserEmailMap.query() \
591 588 .filter(UserEmailMap.user == c.user).all()
592 589
593 590 defaults = c.user.get_dict()
594 591 return htmlfill.render(
595 592 render('admin/users/user_edit.html'),
596 593 defaults=defaults,
597 594 encoding="UTF-8",
598 595 force_defaults=False)
599 596
600 597 @HasPermissionAllDecorator('hg.admin')
601 598 @auth.CSRFRequired()
602 599 def add_email(self, user_id):
603 600 """POST /user_emails:Add an existing item"""
604 601 # url('user_emails', user_id=ID, method='put')
605 602 user_id = safe_int(user_id)
606 603 c.user = User.get_or_404(user_id)
607 604
608 605 email = request.POST.get('new_email')
609 606 user_model = UserModel()
610 607
611 608 try:
612 609 user_model.add_extra_email(user_id, email)
613 610 Session().commit()
614 611 h.flash(_("Added new email address `%s` for user account") % email,
615 612 category='success')
616 613 except formencode.Invalid as error:
617 614 msg = error.error_dict['email']
618 615 h.flash(msg, category='error')
619 616 except Exception:
620 617 log.exception("Exception during email saving")
621 618 h.flash(_('An error occurred during email saving'),
622 619 category='error')
623 620 return redirect(url('edit_user_emails', user_id=user_id))
624 621
625 622 @HasPermissionAllDecorator('hg.admin')
626 623 @auth.CSRFRequired()
627 624 def delete_email(self, user_id):
628 625 """DELETE /user_emails_delete/user_id: Delete an existing item"""
629 626 # url('user_emails_delete', user_id=ID, method='delete')
630 627 user_id = safe_int(user_id)
631 628 c.user = User.get_or_404(user_id)
632 629 email_id = request.POST.get('del_email_id')
633 630 user_model = UserModel()
634 631 user_model.delete_extra_email(user_id, email_id)
635 632 Session().commit()
636 633 h.flash(_("Removed email address from user account"), category='success')
637 634 return redirect(url('edit_user_emails', user_id=user_id))
638 635
639 636 @HasPermissionAllDecorator('hg.admin')
640 637 def edit_ips(self, user_id):
641 638 user_id = safe_int(user_id)
642 639 c.user = User.get_or_404(user_id)
643 640 if c.user.username == User.DEFAULT_USER:
644 641 h.flash(_("You can't edit this user"), category='warning')
645 642 return redirect(url('users'))
646 643
647 644 c.active = 'ips'
648 645 c.user_ip_map = UserIpMap.query() \
649 646 .filter(UserIpMap.user == c.user).all()
650 647
651 648 c.inherit_default_ips = c.user.inherit_default_permissions
652 649 c.default_user_ip_map = UserIpMap.query() \
653 650 .filter(UserIpMap.user == User.get_default_user()).all()
654 651
655 652 defaults = c.user.get_dict()
656 653 return htmlfill.render(
657 654 render('admin/users/user_edit.html'),
658 655 defaults=defaults,
659 656 encoding="UTF-8",
660 657 force_defaults=False)
661 658
662 659 @HasPermissionAllDecorator('hg.admin')
663 660 @auth.CSRFRequired()
664 661 def add_ip(self, user_id):
665 662 """POST /user_ips:Add an existing item"""
666 663 # url('user_ips', user_id=ID, method='put')
667 664
668 665 user_id = safe_int(user_id)
669 666 c.user = User.get_or_404(user_id)
670 667 user_model = UserModel()
671 668 try:
672 669 ip_list = user_model.parse_ip_range(request.POST.get('new_ip'))
673 670 except Exception as e:
674 671 ip_list = []
675 672 log.exception("Exception during ip saving")
676 673 h.flash(_('An error occurred during ip saving:%s' % (e,)),
677 674 category='error')
678 675
679 676 desc = request.POST.get('description')
680 677 added = []
681 678 for ip in ip_list:
682 679 try:
683 680 user_model.add_extra_ip(user_id, ip, desc)
684 681 Session().commit()
685 682 added.append(ip)
686 683 except formencode.Invalid as error:
687 684 msg = error.error_dict['ip']
688 685 h.flash(msg, category='error')
689 686 except Exception:
690 687 log.exception("Exception during ip saving")
691 688 h.flash(_('An error occurred during ip saving'),
692 689 category='error')
693 690 if added:
694 691 h.flash(
695 692 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
696 693 category='success')
697 694 if 'default_user' in request.POST:
698 695 return redirect(url('admin_permissions_ips'))
699 696 return redirect(url('edit_user_ips', user_id=user_id))
700 697
701 698 @HasPermissionAllDecorator('hg.admin')
702 699 @auth.CSRFRequired()
703 700 def delete_ip(self, user_id):
704 701 """DELETE /user_ips_delete/user_id: Delete an existing item"""
705 702 # url('user_ips_delete', user_id=ID, method='delete')
706 703 user_id = safe_int(user_id)
707 704 c.user = User.get_or_404(user_id)
708 705
709 706 ip_id = request.POST.get('del_ip_id')
710 707 user_model = UserModel()
711 708 user_model.delete_extra_ip(user_id, ip_id)
712 709 Session().commit()
713 710 h.flash(_("Removed ip address from user whitelist"), category='success')
714 711
715 712 if 'default_user' in request.POST:
716 713 return redirect(url('admin_permissions_ips'))
717 714 return redirect(url('edit_user_ips', user_id=user_id))
General Comments 0
You need to be logged in to leave comments. Login now