##// END OF EJS Templates
Don't cast to string on warning about deleting an user who still owns repositories
marcink -
r2155:24d90665 beta
parent child Browse files
Show More
@@ -1,210 +1,211 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 rhodecode.controllers.admin.users
3 rhodecode.controllers.admin.users
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5
5
6 Users crud controller for pylons
6 Users crud controller for pylons
7
7
8 :created_on: Apr 4, 2010
8 :created_on: Apr 4, 2010
9 :author: marcink
9 :author: marcink
10 :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
10 :copyright: (C) 2010-2012 Marcin Kuzminski <marcin@python-works.com>
11 :license: GPLv3, see COPYING for more details.
11 :license: GPLv3, see COPYING for more details.
12 """
12 """
13 # This program is free software: you can redistribute it and/or modify
13 # This program is free software: you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation, either version 3 of the License, or
15 # the Free Software Foundation, either version 3 of the License, or
16 # (at your option) any later version.
16 # (at your option) any later version.
17 #
17 #
18 # This program is distributed in the hope that it will be useful,
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
21 # GNU General Public License for more details.
22 #
22 #
23 # You should have received a copy of the GNU General Public License
23 # You should have received a copy of the GNU General Public License
24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25
25
26 import logging
26 import logging
27 import traceback
27 import traceback
28 import formencode
28 import formencode
29
29
30 from formencode import htmlfill
30 from formencode import htmlfill
31 from pylons import request, session, tmpl_context as c, url, config
31 from pylons import request, session, tmpl_context as c, url, config
32 from pylons.controllers.util import redirect
32 from pylons.controllers.util import redirect
33 from pylons.i18n.translation import _
33 from pylons.i18n.translation import _
34
34
35 from rhodecode.lib.exceptions import DefaultUserException, \
35 from rhodecode.lib.exceptions import DefaultUserException, \
36 UserOwnsReposException
36 UserOwnsReposException
37 from rhodecode.lib import helpers as h
37 from rhodecode.lib import helpers as h
38 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
38 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
39 from rhodecode.lib.base import BaseController, render
39 from rhodecode.lib.base import BaseController, render
40
40
41 from rhodecode.model.db import User, Permission
41 from rhodecode.model.db import User, Permission
42 from rhodecode.model.forms import UserForm
42 from rhodecode.model.forms import UserForm
43 from rhodecode.model.user import UserModel
43 from rhodecode.model.user import UserModel
44 from rhodecode.model.meta import Session
44 from rhodecode.model.meta import Session
45
45
46 log = logging.getLogger(__name__)
46 log = logging.getLogger(__name__)
47
47
48
48
49 class UsersController(BaseController):
49 class UsersController(BaseController):
50 """REST Controller styled on the Atom Publishing Protocol"""
50 """REST Controller styled on the Atom Publishing Protocol"""
51 # To properly map this controller, ensure your config/routing.py
51 # To properly map this controller, ensure your config/routing.py
52 # file has a resource setup:
52 # file has a resource setup:
53 # map.resource('user', 'users')
53 # map.resource('user', 'users')
54
54
55 @LoginRequired()
55 @LoginRequired()
56 @HasPermissionAllDecorator('hg.admin')
56 @HasPermissionAllDecorator('hg.admin')
57 def __before__(self):
57 def __before__(self):
58 c.admin_user = session.get('admin_user')
58 c.admin_user = session.get('admin_user')
59 c.admin_username = session.get('admin_username')
59 c.admin_username = session.get('admin_username')
60 super(UsersController, self).__before__()
60 super(UsersController, self).__before__()
61 c.available_permissions = config['available_permissions']
61 c.available_permissions = config['available_permissions']
62
62
63 def index(self, format='html'):
63 def index(self, format='html'):
64 """GET /users: All items in the collection"""
64 """GET /users: All items in the collection"""
65 # url('users')
65 # url('users')
66
66
67 c.users_list = self.sa.query(User).all()
67 c.users_list = self.sa.query(User).all()
68 return render('admin/users/users.html')
68 return render('admin/users/users.html')
69
69
70 def create(self):
70 def create(self):
71 """POST /users: Create a new item"""
71 """POST /users: Create a new item"""
72 # url('users')
72 # url('users')
73
73
74 user_model = UserModel()
74 user_model = UserModel()
75 user_form = UserForm()()
75 user_form = UserForm()()
76 try:
76 try:
77 form_result = user_form.to_python(dict(request.POST))
77 form_result = user_form.to_python(dict(request.POST))
78 user_model.create(form_result)
78 user_model.create(form_result)
79 h.flash(_('created user %s') % form_result['username'],
79 h.flash(_('created user %s') % form_result['username'],
80 category='success')
80 category='success')
81 Session.commit()
81 Session.commit()
82 #action_logger(self.rhodecode_user, 'new_user', '', '', self.sa)
82 #action_logger(self.rhodecode_user, 'new_user', '', '', self.sa)
83 except formencode.Invalid, errors:
83 except formencode.Invalid, errors:
84 return htmlfill.render(
84 return htmlfill.render(
85 render('admin/users/user_add.html'),
85 render('admin/users/user_add.html'),
86 defaults=errors.value,
86 defaults=errors.value,
87 errors=errors.error_dict or {},
87 errors=errors.error_dict or {},
88 prefix_error=False,
88 prefix_error=False,
89 encoding="UTF-8")
89 encoding="UTF-8")
90 except Exception:
90 except Exception:
91 log.error(traceback.format_exc())
91 log.error(traceback.format_exc())
92 h.flash(_('error occurred during creation of user %s') \
92 h.flash(_('error occurred during creation of user %s') \
93 % request.POST.get('username'), category='error')
93 % request.POST.get('username'), category='error')
94 return redirect(url('users'))
94 return redirect(url('users'))
95
95
96 def new(self, format='html'):
96 def new(self, format='html'):
97 """GET /users/new: Form to create a new item"""
97 """GET /users/new: Form to create a new item"""
98 # url('new_user')
98 # url('new_user')
99 return render('admin/users/user_add.html')
99 return render('admin/users/user_add.html')
100
100
101 def update(self, id):
101 def update(self, id):
102 """PUT /users/id: Update an existing item"""
102 """PUT /users/id: Update an existing item"""
103 # Forms posted to this method should contain a hidden field:
103 # Forms posted to this method should contain a hidden field:
104 # <input type="hidden" name="_method" value="PUT" />
104 # <input type="hidden" name="_method" value="PUT" />
105 # Or using helpers:
105 # Or using helpers:
106 # h.form(url('update_user', id=ID),
106 # h.form(url('update_user', id=ID),
107 # method='put')
107 # method='put')
108 # url('user', id=ID)
108 # url('user', id=ID)
109 user_model = UserModel()
109 user_model = UserModel()
110 c.user = user_model.get(id)
110 c.user = user_model.get(id)
111
111
112 _form = UserForm(edit=True, old_data={'user_id': id,
112 _form = UserForm(edit=True, old_data={'user_id': id,
113 'email': c.user.email})()
113 'email': c.user.email})()
114 form_result = {}
114 form_result = {}
115 try:
115 try:
116 form_result = _form.to_python(dict(request.POST))
116 form_result = _form.to_python(dict(request.POST))
117 user_model.update(id, form_result)
117 user_model.update(id, form_result)
118 h.flash(_('User updated successfully'), category='success')
118 h.flash(_('User updated successfully'), category='success')
119 Session.commit()
119 Session.commit()
120 except formencode.Invalid, errors:
120 except formencode.Invalid, errors:
121 e = errors.error_dict or {}
121 e = errors.error_dict or {}
122 perm = Permission.get_by_key('hg.create.repository')
122 perm = Permission.get_by_key('hg.create.repository')
123 e.update({'create_repo_perm': user_model.has_perm(id, perm)})
123 e.update({'create_repo_perm': user_model.has_perm(id, perm)})
124 return htmlfill.render(
124 return htmlfill.render(
125 render('admin/users/user_edit.html'),
125 render('admin/users/user_edit.html'),
126 defaults=errors.value,
126 defaults=errors.value,
127 errors=e,
127 errors=e,
128 prefix_error=False,
128 prefix_error=False,
129 encoding="UTF-8")
129 encoding="UTF-8")
130 except Exception:
130 except Exception:
131 log.error(traceback.format_exc())
131 log.error(traceback.format_exc())
132 h.flash(_('error occurred during update of user %s') \
132 h.flash(_('error occurred during update of user %s') \
133 % form_result.get('username'), category='error')
133 % form_result.get('username'), category='error')
134
134
135 return redirect(url('users'))
135 return redirect(url('users'))
136
136
137 def delete(self, id):
137 def delete(self, id):
138 """DELETE /users/id: Delete an existing item"""
138 """DELETE /users/id: Delete an existing item"""
139 # Forms posted to this method should contain a hidden field:
139 # Forms posted to this method should contain a hidden field:
140 # <input type="hidden" name="_method" value="DELETE" />
140 # <input type="hidden" name="_method" value="DELETE" />
141 # Or using helpers:
141 # Or using helpers:
142 # h.form(url('delete_user', id=ID),
142 # h.form(url('delete_user', id=ID),
143 # method='delete')
143 # method='delete')
144 # url('user', id=ID)
144 # url('user', id=ID)
145 user_model = UserModel()
145 user_model = UserModel()
146 try:
146 try:
147 user_model.delete(id)
147 user_model.delete(id)
148 Session.commit()
148 h.flash(_('successfully deleted user'), category='success')
149 h.flash(_('successfully deleted user'), category='success')
149 Session.commit()
150 except (UserOwnsReposException, DefaultUserException), e:
150 except (UserOwnsReposException, DefaultUserException), e:
151 h.flash(str(e), category='warning')
151 h.flash(e, category='warning')
152 except Exception:
152 except Exception:
153 log.error(traceback.format_exc())
153 h.flash(_('An error occurred during deletion of user'),
154 h.flash(_('An error occurred during deletion of user'),
154 category='error')
155 category='error')
155 return redirect(url('users'))
156 return redirect(url('users'))
156
157
157 def show(self, id, format='html'):
158 def show(self, id, format='html'):
158 """GET /users/id: Show a specific item"""
159 """GET /users/id: Show a specific item"""
159 # url('user', id=ID)
160 # url('user', id=ID)
160
161
161 def edit(self, id, format='html'):
162 def edit(self, id, format='html'):
162 """GET /users/id/edit: Form to edit an existing item"""
163 """GET /users/id/edit: Form to edit an existing item"""
163 # url('edit_user', id=ID)
164 # url('edit_user', id=ID)
164 c.user = User.get(id)
165 c.user = User.get(id)
165 if not c.user:
166 if not c.user:
166 return redirect(url('users'))
167 return redirect(url('users'))
167 if c.user.username == 'default':
168 if c.user.username == 'default':
168 h.flash(_("You can't edit this user"), category='warning')
169 h.flash(_("You can't edit this user"), category='warning')
169 return redirect(url('users'))
170 return redirect(url('users'))
170 c.user.permissions = {}
171 c.user.permissions = {}
171 c.granted_permissions = UserModel().fill_perms(c.user)\
172 c.granted_permissions = UserModel().fill_perms(c.user)\
172 .permissions['global']
173 .permissions['global']
173
174
174 defaults = c.user.get_dict()
175 defaults = c.user.get_dict()
175 perm = Permission.get_by_key('hg.create.repository')
176 perm = Permission.get_by_key('hg.create.repository')
176 defaults.update({'create_repo_perm': UserModel().has_perm(id, perm)})
177 defaults.update({'create_repo_perm': UserModel().has_perm(id, perm)})
177
178
178 return htmlfill.render(
179 return htmlfill.render(
179 render('admin/users/user_edit.html'),
180 render('admin/users/user_edit.html'),
180 defaults=defaults,
181 defaults=defaults,
181 encoding="UTF-8",
182 encoding="UTF-8",
182 force_defaults=False
183 force_defaults=False
183 )
184 )
184
185
185 def update_perm(self, id):
186 def update_perm(self, id):
186 """PUT /users_perm/id: Update an existing item"""
187 """PUT /users_perm/id: Update an existing item"""
187 # url('user_perm', id=ID, method='put')
188 # url('user_perm', id=ID, method='put')
188
189
189 grant_perm = request.POST.get('create_repo_perm', False)
190 grant_perm = request.POST.get('create_repo_perm', False)
190 user_model = UserModel()
191 user_model = UserModel()
191
192
192 if grant_perm:
193 if grant_perm:
193 perm = Permission.get_by_key('hg.create.none')
194 perm = Permission.get_by_key('hg.create.none')
194 user_model.revoke_perm(id, perm)
195 user_model.revoke_perm(id, perm)
195
196
196 perm = Permission.get_by_key('hg.create.repository')
197 perm = Permission.get_by_key('hg.create.repository')
197 user_model.grant_perm(id, perm)
198 user_model.grant_perm(id, perm)
198 h.flash(_("Granted 'repository create' permission to user"),
199 h.flash(_("Granted 'repository create' permission to user"),
199 category='success')
200 category='success')
200 Session.commit()
201 Session.commit()
201 else:
202 else:
202 perm = Permission.get_by_key('hg.create.repository')
203 perm = Permission.get_by_key('hg.create.repository')
203 user_model.revoke_perm(id, perm)
204 user_model.revoke_perm(id, perm)
204
205
205 perm = Permission.get_by_key('hg.create.none')
206 perm = Permission.get_by_key('hg.create.none')
206 user_model.grant_perm(id, perm)
207 user_model.grant_perm(id, perm)
207 h.flash(_("Revoked 'repository create' permission to user"),
208 h.flash(_("Revoked 'repository create' permission to user"),
208 category='success')
209 category='success')
209 Session.commit()
210 Session.commit()
210 return redirect(url('edit_user', id=id))
211 return redirect(url('edit_user', id=id))
General Comments 0
You need to be logged in to leave comments. Login now