##// END OF EJS Templates
ssh-keys: further sanitize data of inputted SSH keys.
marcink -
r2751:ea9069b3 stable
parent child Browse files
Show More
@@ -1,1191 +1,1191 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2018 RhodeCode GmbH
3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22 import datetime
22 import datetime
23 import formencode
23 import formencode
24 import formencode.htmlfill
24 import formencode.htmlfill
25
25
26 from pyramid.httpexceptions import HTTPFound
26 from pyramid.httpexceptions import HTTPFound
27 from pyramid.view import view_config
27 from pyramid.view import view_config
28 from pyramid.renderers import render
28 from pyramid.renderers import render
29 from pyramid.response import Response
29 from pyramid.response import Response
30
30
31 from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView
31 from rhodecode.apps._base import BaseAppView, DataGridAppView, UserAppView
32 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
32 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
33 from rhodecode.authentication.plugins import auth_rhodecode
33 from rhodecode.authentication.plugins import auth_rhodecode
34 from rhodecode.events import trigger
34 from rhodecode.events import trigger
35
35
36 from rhodecode.lib import audit_logger
36 from rhodecode.lib import audit_logger
37 from rhodecode.lib.exceptions import (
37 from rhodecode.lib.exceptions import (
38 UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException,
38 UserCreationError, UserOwnsReposException, UserOwnsRepoGroupsException,
39 UserOwnsUserGroupsException, DefaultUserException)
39 UserOwnsUserGroupsException, DefaultUserException)
40 from rhodecode.lib.ext_json import json
40 from rhodecode.lib.ext_json import json
41 from rhodecode.lib.auth import (
41 from rhodecode.lib.auth import (
42 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
42 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
43 from rhodecode.lib import helpers as h
43 from rhodecode.lib import helpers as h
44 from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict
44 from rhodecode.lib.utils2 import safe_int, safe_unicode, AttributeDict
45 from rhodecode.model.auth_token import AuthTokenModel
45 from rhodecode.model.auth_token import AuthTokenModel
46 from rhodecode.model.forms import (
46 from rhodecode.model.forms import (
47 UserForm, UserIndividualPermissionsForm, UserPermissionsForm,
47 UserForm, UserIndividualPermissionsForm, UserPermissionsForm,
48 UserExtraEmailForm, UserExtraIpForm)
48 UserExtraEmailForm, UserExtraIpForm)
49 from rhodecode.model.permission import PermissionModel
49 from rhodecode.model.permission import PermissionModel
50 from rhodecode.model.repo_group import RepoGroupModel
50 from rhodecode.model.repo_group import RepoGroupModel
51 from rhodecode.model.ssh_key import SshKeyModel
51 from rhodecode.model.ssh_key import SshKeyModel
52 from rhodecode.model.user import UserModel
52 from rhodecode.model.user import UserModel
53 from rhodecode.model.user_group import UserGroupModel
53 from rhodecode.model.user_group import UserGroupModel
54 from rhodecode.model.db import (
54 from rhodecode.model.db import (
55 or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap,
55 or_, coalesce,IntegrityError, User, UserGroup, UserIpMap, UserEmailMap,
56 UserApiKeys, UserSshKeys, RepoGroup)
56 UserApiKeys, UserSshKeys, RepoGroup)
57 from rhodecode.model.meta import Session
57 from rhodecode.model.meta import Session
58
58
59 log = logging.getLogger(__name__)
59 log = logging.getLogger(__name__)
60
60
61
61
62 class AdminUsersView(BaseAppView, DataGridAppView):
62 class AdminUsersView(BaseAppView, DataGridAppView):
63
63
64 def load_default_context(self):
64 def load_default_context(self):
65 c = self._get_local_tmpl_context()
65 c = self._get_local_tmpl_context()
66 return c
66 return c
67
67
68 @LoginRequired()
68 @LoginRequired()
69 @HasPermissionAllDecorator('hg.admin')
69 @HasPermissionAllDecorator('hg.admin')
70 @view_config(
70 @view_config(
71 route_name='users', request_method='GET',
71 route_name='users', request_method='GET',
72 renderer='rhodecode:templates/admin/users/users.mako')
72 renderer='rhodecode:templates/admin/users/users.mako')
73 def users_list(self):
73 def users_list(self):
74 c = self.load_default_context()
74 c = self.load_default_context()
75 return self._get_template_context(c)
75 return self._get_template_context(c)
76
76
77 @LoginRequired()
77 @LoginRequired()
78 @HasPermissionAllDecorator('hg.admin')
78 @HasPermissionAllDecorator('hg.admin')
79 @view_config(
79 @view_config(
80 # renderer defined below
80 # renderer defined below
81 route_name='users_data', request_method='GET',
81 route_name='users_data', request_method='GET',
82 renderer='json_ext', xhr=True)
82 renderer='json_ext', xhr=True)
83 def users_list_data(self):
83 def users_list_data(self):
84 self.load_default_context()
84 self.load_default_context()
85 column_map = {
85 column_map = {
86 'first_name': 'name',
86 'first_name': 'name',
87 'last_name': 'lastname',
87 'last_name': 'lastname',
88 }
88 }
89 draw, start, limit = self._extract_chunk(self.request)
89 draw, start, limit = self._extract_chunk(self.request)
90 search_q, order_by, order_dir = self._extract_ordering(
90 search_q, order_by, order_dir = self._extract_ordering(
91 self.request, column_map=column_map)
91 self.request, column_map=column_map)
92
92
93 _render = self.request.get_partial_renderer(
93 _render = self.request.get_partial_renderer(
94 'rhodecode:templates/data_table/_dt_elements.mako')
94 'rhodecode:templates/data_table/_dt_elements.mako')
95
95
96 def user_actions(user_id, username):
96 def user_actions(user_id, username):
97 return _render("user_actions", user_id, username)
97 return _render("user_actions", user_id, username)
98
98
99 users_data_total_count = User.query()\
99 users_data_total_count = User.query()\
100 .filter(User.username != User.DEFAULT_USER) \
100 .filter(User.username != User.DEFAULT_USER) \
101 .count()
101 .count()
102
102
103 # json generate
103 # json generate
104 base_q = User.query().filter(User.username != User.DEFAULT_USER)
104 base_q = User.query().filter(User.username != User.DEFAULT_USER)
105
105
106 if search_q:
106 if search_q:
107 like_expression = u'%{}%'.format(safe_unicode(search_q))
107 like_expression = u'%{}%'.format(safe_unicode(search_q))
108 base_q = base_q.filter(or_(
108 base_q = base_q.filter(or_(
109 User.username.ilike(like_expression),
109 User.username.ilike(like_expression),
110 User._email.ilike(like_expression),
110 User._email.ilike(like_expression),
111 User.name.ilike(like_expression),
111 User.name.ilike(like_expression),
112 User.lastname.ilike(like_expression),
112 User.lastname.ilike(like_expression),
113 ))
113 ))
114
114
115 users_data_total_filtered_count = base_q.count()
115 users_data_total_filtered_count = base_q.count()
116
116
117 sort_col = getattr(User, order_by, None)
117 sort_col = getattr(User, order_by, None)
118 if sort_col:
118 if sort_col:
119 if order_dir == 'asc':
119 if order_dir == 'asc':
120 # handle null values properly to order by NULL last
120 # handle null values properly to order by NULL last
121 if order_by in ['last_activity']:
121 if order_by in ['last_activity']:
122 sort_col = coalesce(sort_col, datetime.date.max)
122 sort_col = coalesce(sort_col, datetime.date.max)
123 sort_col = sort_col.asc()
123 sort_col = sort_col.asc()
124 else:
124 else:
125 # handle null values properly to order by NULL last
125 # handle null values properly to order by NULL last
126 if order_by in ['last_activity']:
126 if order_by in ['last_activity']:
127 sort_col = coalesce(sort_col, datetime.date.min)
127 sort_col = coalesce(sort_col, datetime.date.min)
128 sort_col = sort_col.desc()
128 sort_col = sort_col.desc()
129
129
130 base_q = base_q.order_by(sort_col)
130 base_q = base_q.order_by(sort_col)
131 base_q = base_q.offset(start).limit(limit)
131 base_q = base_q.offset(start).limit(limit)
132
132
133 users_list = base_q.all()
133 users_list = base_q.all()
134
134
135 users_data = []
135 users_data = []
136 for user in users_list:
136 for user in users_list:
137 users_data.append({
137 users_data.append({
138 "username": h.gravatar_with_user(self.request, user.username),
138 "username": h.gravatar_with_user(self.request, user.username),
139 "email": user.email,
139 "email": user.email,
140 "first_name": user.first_name,
140 "first_name": user.first_name,
141 "last_name": user.last_name,
141 "last_name": user.last_name,
142 "last_login": h.format_date(user.last_login),
142 "last_login": h.format_date(user.last_login),
143 "last_activity": h.format_date(user.last_activity),
143 "last_activity": h.format_date(user.last_activity),
144 "active": h.bool2icon(user.active),
144 "active": h.bool2icon(user.active),
145 "active_raw": user.active,
145 "active_raw": user.active,
146 "admin": h.bool2icon(user.admin),
146 "admin": h.bool2icon(user.admin),
147 "extern_type": user.extern_type,
147 "extern_type": user.extern_type,
148 "extern_name": user.extern_name,
148 "extern_name": user.extern_name,
149 "action": user_actions(user.user_id, user.username),
149 "action": user_actions(user.user_id, user.username),
150 })
150 })
151
151
152 data = ({
152 data = ({
153 'draw': draw,
153 'draw': draw,
154 'data': users_data,
154 'data': users_data,
155 'recordsTotal': users_data_total_count,
155 'recordsTotal': users_data_total_count,
156 'recordsFiltered': users_data_total_filtered_count,
156 'recordsFiltered': users_data_total_filtered_count,
157 })
157 })
158
158
159 return data
159 return data
160
160
161 def _set_personal_repo_group_template_vars(self, c_obj):
161 def _set_personal_repo_group_template_vars(self, c_obj):
162 DummyUser = AttributeDict({
162 DummyUser = AttributeDict({
163 'username': '${username}',
163 'username': '${username}',
164 'user_id': '${user_id}',
164 'user_id': '${user_id}',
165 })
165 })
166 c_obj.default_create_repo_group = RepoGroupModel() \
166 c_obj.default_create_repo_group = RepoGroupModel() \
167 .get_default_create_personal_repo_group()
167 .get_default_create_personal_repo_group()
168 c_obj.personal_repo_group_name = RepoGroupModel() \
168 c_obj.personal_repo_group_name = RepoGroupModel() \
169 .get_personal_group_name(DummyUser)
169 .get_personal_group_name(DummyUser)
170
170
171 @LoginRequired()
171 @LoginRequired()
172 @HasPermissionAllDecorator('hg.admin')
172 @HasPermissionAllDecorator('hg.admin')
173 @view_config(
173 @view_config(
174 route_name='users_new', request_method='GET',
174 route_name='users_new', request_method='GET',
175 renderer='rhodecode:templates/admin/users/user_add.mako')
175 renderer='rhodecode:templates/admin/users/user_add.mako')
176 def users_new(self):
176 def users_new(self):
177 _ = self.request.translate
177 _ = self.request.translate
178 c = self.load_default_context()
178 c = self.load_default_context()
179 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
179 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
180 self._set_personal_repo_group_template_vars(c)
180 self._set_personal_repo_group_template_vars(c)
181 return self._get_template_context(c)
181 return self._get_template_context(c)
182
182
183 @LoginRequired()
183 @LoginRequired()
184 @HasPermissionAllDecorator('hg.admin')
184 @HasPermissionAllDecorator('hg.admin')
185 @CSRFRequired()
185 @CSRFRequired()
186 @view_config(
186 @view_config(
187 route_name='users_create', request_method='POST',
187 route_name='users_create', request_method='POST',
188 renderer='rhodecode:templates/admin/users/user_add.mako')
188 renderer='rhodecode:templates/admin/users/user_add.mako')
189 def users_create(self):
189 def users_create(self):
190 _ = self.request.translate
190 _ = self.request.translate
191 c = self.load_default_context()
191 c = self.load_default_context()
192 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
192 c.default_extern_type = auth_rhodecode.RhodeCodeAuthPlugin.name
193 user_model = UserModel()
193 user_model = UserModel()
194 user_form = UserForm(self.request.translate)()
194 user_form = UserForm(self.request.translate)()
195 try:
195 try:
196 form_result = user_form.to_python(dict(self.request.POST))
196 form_result = user_form.to_python(dict(self.request.POST))
197 user = user_model.create(form_result)
197 user = user_model.create(form_result)
198 Session().flush()
198 Session().flush()
199 creation_data = user.get_api_data()
199 creation_data = user.get_api_data()
200 username = form_result['username']
200 username = form_result['username']
201
201
202 audit_logger.store_web(
202 audit_logger.store_web(
203 'user.create', action_data={'data': creation_data},
203 'user.create', action_data={'data': creation_data},
204 user=c.rhodecode_user)
204 user=c.rhodecode_user)
205
205
206 user_link = h.link_to(
206 user_link = h.link_to(
207 h.escape(username),
207 h.escape(username),
208 h.route_path('user_edit', user_id=user.user_id))
208 h.route_path('user_edit', user_id=user.user_id))
209 h.flash(h.literal(_('Created user %(user_link)s')
209 h.flash(h.literal(_('Created user %(user_link)s')
210 % {'user_link': user_link}), category='success')
210 % {'user_link': user_link}), category='success')
211 Session().commit()
211 Session().commit()
212 except formencode.Invalid as errors:
212 except formencode.Invalid as errors:
213 self._set_personal_repo_group_template_vars(c)
213 self._set_personal_repo_group_template_vars(c)
214 data = render(
214 data = render(
215 'rhodecode:templates/admin/users/user_add.mako',
215 'rhodecode:templates/admin/users/user_add.mako',
216 self._get_template_context(c), self.request)
216 self._get_template_context(c), self.request)
217 html = formencode.htmlfill.render(
217 html = formencode.htmlfill.render(
218 data,
218 data,
219 defaults=errors.value,
219 defaults=errors.value,
220 errors=errors.error_dict or {},
220 errors=errors.error_dict or {},
221 prefix_error=False,
221 prefix_error=False,
222 encoding="UTF-8",
222 encoding="UTF-8",
223 force_defaults=False
223 force_defaults=False
224 )
224 )
225 return Response(html)
225 return Response(html)
226 except UserCreationError as e:
226 except UserCreationError as e:
227 h.flash(e, 'error')
227 h.flash(e, 'error')
228 except Exception:
228 except Exception:
229 log.exception("Exception creation of user")
229 log.exception("Exception creation of user")
230 h.flash(_('Error occurred during creation of user %s')
230 h.flash(_('Error occurred during creation of user %s')
231 % self.request.POST.get('username'), category='error')
231 % self.request.POST.get('username'), category='error')
232 raise HTTPFound(h.route_path('users'))
232 raise HTTPFound(h.route_path('users'))
233
233
234
234
235 class UsersView(UserAppView):
235 class UsersView(UserAppView):
236 ALLOW_SCOPED_TOKENS = False
236 ALLOW_SCOPED_TOKENS = False
237 """
237 """
238 This view has alternative version inside EE, if modified please take a look
238 This view has alternative version inside EE, if modified please take a look
239 in there as well.
239 in there as well.
240 """
240 """
241
241
242 def load_default_context(self):
242 def load_default_context(self):
243 c = self._get_local_tmpl_context()
243 c = self._get_local_tmpl_context()
244 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
244 c.allow_scoped_tokens = self.ALLOW_SCOPED_TOKENS
245 c.allowed_languages = [
245 c.allowed_languages = [
246 ('en', 'English (en)'),
246 ('en', 'English (en)'),
247 ('de', 'German (de)'),
247 ('de', 'German (de)'),
248 ('fr', 'French (fr)'),
248 ('fr', 'French (fr)'),
249 ('it', 'Italian (it)'),
249 ('it', 'Italian (it)'),
250 ('ja', 'Japanese (ja)'),
250 ('ja', 'Japanese (ja)'),
251 ('pl', 'Polish (pl)'),
251 ('pl', 'Polish (pl)'),
252 ('pt', 'Portuguese (pt)'),
252 ('pt', 'Portuguese (pt)'),
253 ('ru', 'Russian (ru)'),
253 ('ru', 'Russian (ru)'),
254 ('zh', 'Chinese (zh)'),
254 ('zh', 'Chinese (zh)'),
255 ]
255 ]
256 req = self.request
256 req = self.request
257
257
258 c.available_permissions = req.registry.settings['available_permissions']
258 c.available_permissions = req.registry.settings['available_permissions']
259 PermissionModel().set_global_permission_choices(
259 PermissionModel().set_global_permission_choices(
260 c, gettext_translator=req.translate)
260 c, gettext_translator=req.translate)
261
261
262 return c
262 return c
263
263
264 @LoginRequired()
264 @LoginRequired()
265 @HasPermissionAllDecorator('hg.admin')
265 @HasPermissionAllDecorator('hg.admin')
266 @CSRFRequired()
266 @CSRFRequired()
267 @view_config(
267 @view_config(
268 route_name='user_update', request_method='POST',
268 route_name='user_update', request_method='POST',
269 renderer='rhodecode:templates/admin/users/user_edit.mako')
269 renderer='rhodecode:templates/admin/users/user_edit.mako')
270 def user_update(self):
270 def user_update(self):
271 _ = self.request.translate
271 _ = self.request.translate
272 c = self.load_default_context()
272 c = self.load_default_context()
273
273
274 user_id = self.db_user_id
274 user_id = self.db_user_id
275 c.user = self.db_user
275 c.user = self.db_user
276
276
277 c.active = 'profile'
277 c.active = 'profile'
278 c.extern_type = c.user.extern_type
278 c.extern_type = c.user.extern_type
279 c.extern_name = c.user.extern_name
279 c.extern_name = c.user.extern_name
280 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
280 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
281 available_languages = [x[0] for x in c.allowed_languages]
281 available_languages = [x[0] for x in c.allowed_languages]
282 _form = UserForm(self.request.translate, edit=True,
282 _form = UserForm(self.request.translate, edit=True,
283 available_languages=available_languages,
283 available_languages=available_languages,
284 old_data={'user_id': user_id,
284 old_data={'user_id': user_id,
285 'email': c.user.email})()
285 'email': c.user.email})()
286 form_result = {}
286 form_result = {}
287 old_values = c.user.get_api_data()
287 old_values = c.user.get_api_data()
288 try:
288 try:
289 form_result = _form.to_python(dict(self.request.POST))
289 form_result = _form.to_python(dict(self.request.POST))
290 skip_attrs = ['extern_type', 'extern_name']
290 skip_attrs = ['extern_type', 'extern_name']
291 # TODO: plugin should define if username can be updated
291 # TODO: plugin should define if username can be updated
292 if c.extern_type != "rhodecode":
292 if c.extern_type != "rhodecode":
293 # forbid updating username for external accounts
293 # forbid updating username for external accounts
294 skip_attrs.append('username')
294 skip_attrs.append('username')
295
295
296 UserModel().update_user(
296 UserModel().update_user(
297 user_id, skip_attrs=skip_attrs, **form_result)
297 user_id, skip_attrs=skip_attrs, **form_result)
298
298
299 audit_logger.store_web(
299 audit_logger.store_web(
300 'user.edit', action_data={'old_data': old_values},
300 'user.edit', action_data={'old_data': old_values},
301 user=c.rhodecode_user)
301 user=c.rhodecode_user)
302
302
303 Session().commit()
303 Session().commit()
304 h.flash(_('User updated successfully'), category='success')
304 h.flash(_('User updated successfully'), category='success')
305 except formencode.Invalid as errors:
305 except formencode.Invalid as errors:
306 data = render(
306 data = render(
307 'rhodecode:templates/admin/users/user_edit.mako',
307 'rhodecode:templates/admin/users/user_edit.mako',
308 self._get_template_context(c), self.request)
308 self._get_template_context(c), self.request)
309 html = formencode.htmlfill.render(
309 html = formencode.htmlfill.render(
310 data,
310 data,
311 defaults=errors.value,
311 defaults=errors.value,
312 errors=errors.error_dict or {},
312 errors=errors.error_dict or {},
313 prefix_error=False,
313 prefix_error=False,
314 encoding="UTF-8",
314 encoding="UTF-8",
315 force_defaults=False
315 force_defaults=False
316 )
316 )
317 return Response(html)
317 return Response(html)
318 except UserCreationError as e:
318 except UserCreationError as e:
319 h.flash(e, 'error')
319 h.flash(e, 'error')
320 except Exception:
320 except Exception:
321 log.exception("Exception updating user")
321 log.exception("Exception updating user")
322 h.flash(_('Error occurred during update of user %s')
322 h.flash(_('Error occurred during update of user %s')
323 % form_result.get('username'), category='error')
323 % form_result.get('username'), category='error')
324 raise HTTPFound(h.route_path('user_edit', user_id=user_id))
324 raise HTTPFound(h.route_path('user_edit', user_id=user_id))
325
325
326 @LoginRequired()
326 @LoginRequired()
327 @HasPermissionAllDecorator('hg.admin')
327 @HasPermissionAllDecorator('hg.admin')
328 @CSRFRequired()
328 @CSRFRequired()
329 @view_config(
329 @view_config(
330 route_name='user_delete', request_method='POST',
330 route_name='user_delete', request_method='POST',
331 renderer='rhodecode:templates/admin/users/user_edit.mako')
331 renderer='rhodecode:templates/admin/users/user_edit.mako')
332 def user_delete(self):
332 def user_delete(self):
333 _ = self.request.translate
333 _ = self.request.translate
334 c = self.load_default_context()
334 c = self.load_default_context()
335 c.user = self.db_user
335 c.user = self.db_user
336
336
337 _repos = c.user.repositories
337 _repos = c.user.repositories
338 _repo_groups = c.user.repository_groups
338 _repo_groups = c.user.repository_groups
339 _user_groups = c.user.user_groups
339 _user_groups = c.user.user_groups
340
340
341 handle_repos = None
341 handle_repos = None
342 handle_repo_groups = None
342 handle_repo_groups = None
343 handle_user_groups = None
343 handle_user_groups = None
344 # dummy call for flash of handle
344 # dummy call for flash of handle
345 set_handle_flash_repos = lambda: None
345 set_handle_flash_repos = lambda: None
346 set_handle_flash_repo_groups = lambda: None
346 set_handle_flash_repo_groups = lambda: None
347 set_handle_flash_user_groups = lambda: None
347 set_handle_flash_user_groups = lambda: None
348
348
349 if _repos and self.request.POST.get('user_repos'):
349 if _repos and self.request.POST.get('user_repos'):
350 do = self.request.POST['user_repos']
350 do = self.request.POST['user_repos']
351 if do == 'detach':
351 if do == 'detach':
352 handle_repos = 'detach'
352 handle_repos = 'detach'
353 set_handle_flash_repos = lambda: h.flash(
353 set_handle_flash_repos = lambda: h.flash(
354 _('Detached %s repositories') % len(_repos),
354 _('Detached %s repositories') % len(_repos),
355 category='success')
355 category='success')
356 elif do == 'delete':
356 elif do == 'delete':
357 handle_repos = 'delete'
357 handle_repos = 'delete'
358 set_handle_flash_repos = lambda: h.flash(
358 set_handle_flash_repos = lambda: h.flash(
359 _('Deleted %s repositories') % len(_repos),
359 _('Deleted %s repositories') % len(_repos),
360 category='success')
360 category='success')
361
361
362 if _repo_groups and self.request.POST.get('user_repo_groups'):
362 if _repo_groups and self.request.POST.get('user_repo_groups'):
363 do = self.request.POST['user_repo_groups']
363 do = self.request.POST['user_repo_groups']
364 if do == 'detach':
364 if do == 'detach':
365 handle_repo_groups = 'detach'
365 handle_repo_groups = 'detach'
366 set_handle_flash_repo_groups = lambda: h.flash(
366 set_handle_flash_repo_groups = lambda: h.flash(
367 _('Detached %s repository groups') % len(_repo_groups),
367 _('Detached %s repository groups') % len(_repo_groups),
368 category='success')
368 category='success')
369 elif do == 'delete':
369 elif do == 'delete':
370 handle_repo_groups = 'delete'
370 handle_repo_groups = 'delete'
371 set_handle_flash_repo_groups = lambda: h.flash(
371 set_handle_flash_repo_groups = lambda: h.flash(
372 _('Deleted %s repository groups') % len(_repo_groups),
372 _('Deleted %s repository groups') % len(_repo_groups),
373 category='success')
373 category='success')
374
374
375 if _user_groups and self.request.POST.get('user_user_groups'):
375 if _user_groups and self.request.POST.get('user_user_groups'):
376 do = self.request.POST['user_user_groups']
376 do = self.request.POST['user_user_groups']
377 if do == 'detach':
377 if do == 'detach':
378 handle_user_groups = 'detach'
378 handle_user_groups = 'detach'
379 set_handle_flash_user_groups = lambda: h.flash(
379 set_handle_flash_user_groups = lambda: h.flash(
380 _('Detached %s user groups') % len(_user_groups),
380 _('Detached %s user groups') % len(_user_groups),
381 category='success')
381 category='success')
382 elif do == 'delete':
382 elif do == 'delete':
383 handle_user_groups = 'delete'
383 handle_user_groups = 'delete'
384 set_handle_flash_user_groups = lambda: h.flash(
384 set_handle_flash_user_groups = lambda: h.flash(
385 _('Deleted %s user groups') % len(_user_groups),
385 _('Deleted %s user groups') % len(_user_groups),
386 category='success')
386 category='success')
387
387
388 old_values = c.user.get_api_data()
388 old_values = c.user.get_api_data()
389 try:
389 try:
390 UserModel().delete(c.user, handle_repos=handle_repos,
390 UserModel().delete(c.user, handle_repos=handle_repos,
391 handle_repo_groups=handle_repo_groups,
391 handle_repo_groups=handle_repo_groups,
392 handle_user_groups=handle_user_groups)
392 handle_user_groups=handle_user_groups)
393
393
394 audit_logger.store_web(
394 audit_logger.store_web(
395 'user.delete', action_data={'old_data': old_values},
395 'user.delete', action_data={'old_data': old_values},
396 user=c.rhodecode_user)
396 user=c.rhodecode_user)
397
397
398 Session().commit()
398 Session().commit()
399 set_handle_flash_repos()
399 set_handle_flash_repos()
400 set_handle_flash_repo_groups()
400 set_handle_flash_repo_groups()
401 set_handle_flash_user_groups()
401 set_handle_flash_user_groups()
402 h.flash(_('Successfully deleted user'), category='success')
402 h.flash(_('Successfully deleted user'), category='success')
403 except (UserOwnsReposException, UserOwnsRepoGroupsException,
403 except (UserOwnsReposException, UserOwnsRepoGroupsException,
404 UserOwnsUserGroupsException, DefaultUserException) as e:
404 UserOwnsUserGroupsException, DefaultUserException) as e:
405 h.flash(e, category='warning')
405 h.flash(e, category='warning')
406 except Exception:
406 except Exception:
407 log.exception("Exception during deletion of user")
407 log.exception("Exception during deletion of user")
408 h.flash(_('An error occurred during deletion of user'),
408 h.flash(_('An error occurred during deletion of user'),
409 category='error')
409 category='error')
410 raise HTTPFound(h.route_path('users'))
410 raise HTTPFound(h.route_path('users'))
411
411
412 @LoginRequired()
412 @LoginRequired()
413 @HasPermissionAllDecorator('hg.admin')
413 @HasPermissionAllDecorator('hg.admin')
414 @view_config(
414 @view_config(
415 route_name='user_edit', request_method='GET',
415 route_name='user_edit', request_method='GET',
416 renderer='rhodecode:templates/admin/users/user_edit.mako')
416 renderer='rhodecode:templates/admin/users/user_edit.mako')
417 def user_edit(self):
417 def user_edit(self):
418 _ = self.request.translate
418 _ = self.request.translate
419 c = self.load_default_context()
419 c = self.load_default_context()
420 c.user = self.db_user
420 c.user = self.db_user
421
421
422 c.active = 'profile'
422 c.active = 'profile'
423 c.extern_type = c.user.extern_type
423 c.extern_type = c.user.extern_type
424 c.extern_name = c.user.extern_name
424 c.extern_name = c.user.extern_name
425 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
425 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
426
426
427 defaults = c.user.get_dict()
427 defaults = c.user.get_dict()
428 defaults.update({'language': c.user.user_data.get('language')})
428 defaults.update({'language': c.user.user_data.get('language')})
429
429
430 data = render(
430 data = render(
431 'rhodecode:templates/admin/users/user_edit.mako',
431 'rhodecode:templates/admin/users/user_edit.mako',
432 self._get_template_context(c), self.request)
432 self._get_template_context(c), self.request)
433 html = formencode.htmlfill.render(
433 html = formencode.htmlfill.render(
434 data,
434 data,
435 defaults=defaults,
435 defaults=defaults,
436 encoding="UTF-8",
436 encoding="UTF-8",
437 force_defaults=False
437 force_defaults=False
438 )
438 )
439 return Response(html)
439 return Response(html)
440
440
441 @LoginRequired()
441 @LoginRequired()
442 @HasPermissionAllDecorator('hg.admin')
442 @HasPermissionAllDecorator('hg.admin')
443 @view_config(
443 @view_config(
444 route_name='user_edit_advanced', request_method='GET',
444 route_name='user_edit_advanced', request_method='GET',
445 renderer='rhodecode:templates/admin/users/user_edit.mako')
445 renderer='rhodecode:templates/admin/users/user_edit.mako')
446 def user_edit_advanced(self):
446 def user_edit_advanced(self):
447 _ = self.request.translate
447 _ = self.request.translate
448 c = self.load_default_context()
448 c = self.load_default_context()
449
449
450 user_id = self.db_user_id
450 user_id = self.db_user_id
451 c.user = self.db_user
451 c.user = self.db_user
452
452
453 c.active = 'advanced'
453 c.active = 'advanced'
454 c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id)
454 c.personal_repo_group = RepoGroup.get_user_personal_repo_group(user_id)
455 c.personal_repo_group_name = RepoGroupModel()\
455 c.personal_repo_group_name = RepoGroupModel()\
456 .get_personal_group_name(c.user)
456 .get_personal_group_name(c.user)
457
457
458 c.user_to_review_rules = sorted(
458 c.user_to_review_rules = sorted(
459 (x.user for x in c.user.user_review_rules),
459 (x.user for x in c.user.user_review_rules),
460 key=lambda u: u.username.lower())
460 key=lambda u: u.username.lower())
461
461
462 c.first_admin = User.get_first_super_admin()
462 c.first_admin = User.get_first_super_admin()
463 defaults = c.user.get_dict()
463 defaults = c.user.get_dict()
464
464
465 # Interim workaround if the user participated on any pull requests as a
465 # Interim workaround if the user participated on any pull requests as a
466 # reviewer.
466 # reviewer.
467 has_review = len(c.user.reviewer_pull_requests)
467 has_review = len(c.user.reviewer_pull_requests)
468 c.can_delete_user = not has_review
468 c.can_delete_user = not has_review
469 c.can_delete_user_message = ''
469 c.can_delete_user_message = ''
470 inactive_link = h.link_to(
470 inactive_link = h.link_to(
471 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active'))
471 'inactive', h.route_path('user_edit', user_id=user_id, _anchor='active'))
472 if has_review == 1:
472 if has_review == 1:
473 c.can_delete_user_message = h.literal(_(
473 c.can_delete_user_message = h.literal(_(
474 'The user participates as reviewer in {} pull request and '
474 'The user participates as reviewer in {} pull request and '
475 'cannot be deleted. \nYou can set the user to '
475 'cannot be deleted. \nYou can set the user to '
476 '"{}" instead of deleting it.').format(
476 '"{}" instead of deleting it.').format(
477 has_review, inactive_link))
477 has_review, inactive_link))
478 elif has_review:
478 elif has_review:
479 c.can_delete_user_message = h.literal(_(
479 c.can_delete_user_message = h.literal(_(
480 'The user participates as reviewer in {} pull requests and '
480 'The user participates as reviewer in {} pull requests and '
481 'cannot be deleted. \nYou can set the user to '
481 'cannot be deleted. \nYou can set the user to '
482 '"{}" instead of deleting it.').format(
482 '"{}" instead of deleting it.').format(
483 has_review, inactive_link))
483 has_review, inactive_link))
484
484
485 data = render(
485 data = render(
486 'rhodecode:templates/admin/users/user_edit.mako',
486 'rhodecode:templates/admin/users/user_edit.mako',
487 self._get_template_context(c), self.request)
487 self._get_template_context(c), self.request)
488 html = formencode.htmlfill.render(
488 html = formencode.htmlfill.render(
489 data,
489 data,
490 defaults=defaults,
490 defaults=defaults,
491 encoding="UTF-8",
491 encoding="UTF-8",
492 force_defaults=False
492 force_defaults=False
493 )
493 )
494 return Response(html)
494 return Response(html)
495
495
496 @LoginRequired()
496 @LoginRequired()
497 @HasPermissionAllDecorator('hg.admin')
497 @HasPermissionAllDecorator('hg.admin')
498 @view_config(
498 @view_config(
499 route_name='user_edit_global_perms', request_method='GET',
499 route_name='user_edit_global_perms', request_method='GET',
500 renderer='rhodecode:templates/admin/users/user_edit.mako')
500 renderer='rhodecode:templates/admin/users/user_edit.mako')
501 def user_edit_global_perms(self):
501 def user_edit_global_perms(self):
502 _ = self.request.translate
502 _ = self.request.translate
503 c = self.load_default_context()
503 c = self.load_default_context()
504 c.user = self.db_user
504 c.user = self.db_user
505
505
506 c.active = 'global_perms'
506 c.active = 'global_perms'
507
507
508 c.default_user = User.get_default_user()
508 c.default_user = User.get_default_user()
509 defaults = c.user.get_dict()
509 defaults = c.user.get_dict()
510 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
510 defaults.update(c.default_user.get_default_perms(suffix='_inherited'))
511 defaults.update(c.default_user.get_default_perms())
511 defaults.update(c.default_user.get_default_perms())
512 defaults.update(c.user.get_default_perms())
512 defaults.update(c.user.get_default_perms())
513
513
514 data = render(
514 data = render(
515 'rhodecode:templates/admin/users/user_edit.mako',
515 'rhodecode:templates/admin/users/user_edit.mako',
516 self._get_template_context(c), self.request)
516 self._get_template_context(c), self.request)
517 html = formencode.htmlfill.render(
517 html = formencode.htmlfill.render(
518 data,
518 data,
519 defaults=defaults,
519 defaults=defaults,
520 encoding="UTF-8",
520 encoding="UTF-8",
521 force_defaults=False
521 force_defaults=False
522 )
522 )
523 return Response(html)
523 return Response(html)
524
524
525 @LoginRequired()
525 @LoginRequired()
526 @HasPermissionAllDecorator('hg.admin')
526 @HasPermissionAllDecorator('hg.admin')
527 @CSRFRequired()
527 @CSRFRequired()
528 @view_config(
528 @view_config(
529 route_name='user_edit_global_perms_update', request_method='POST',
529 route_name='user_edit_global_perms_update', request_method='POST',
530 renderer='rhodecode:templates/admin/users/user_edit.mako')
530 renderer='rhodecode:templates/admin/users/user_edit.mako')
531 def user_edit_global_perms_update(self):
531 def user_edit_global_perms_update(self):
532 _ = self.request.translate
532 _ = self.request.translate
533 c = self.load_default_context()
533 c = self.load_default_context()
534
534
535 user_id = self.db_user_id
535 user_id = self.db_user_id
536 c.user = self.db_user
536 c.user = self.db_user
537
537
538 c.active = 'global_perms'
538 c.active = 'global_perms'
539 try:
539 try:
540 # first stage that verifies the checkbox
540 # first stage that verifies the checkbox
541 _form = UserIndividualPermissionsForm(self.request.translate)
541 _form = UserIndividualPermissionsForm(self.request.translate)
542 form_result = _form.to_python(dict(self.request.POST))
542 form_result = _form.to_python(dict(self.request.POST))
543 inherit_perms = form_result['inherit_default_permissions']
543 inherit_perms = form_result['inherit_default_permissions']
544 c.user.inherit_default_permissions = inherit_perms
544 c.user.inherit_default_permissions = inherit_perms
545 Session().add(c.user)
545 Session().add(c.user)
546
546
547 if not inherit_perms:
547 if not inherit_perms:
548 # only update the individual ones if we un check the flag
548 # only update the individual ones if we un check the flag
549 _form = UserPermissionsForm(
549 _form = UserPermissionsForm(
550 self.request.translate,
550 self.request.translate,
551 [x[0] for x in c.repo_create_choices],
551 [x[0] for x in c.repo_create_choices],
552 [x[0] for x in c.repo_create_on_write_choices],
552 [x[0] for x in c.repo_create_on_write_choices],
553 [x[0] for x in c.repo_group_create_choices],
553 [x[0] for x in c.repo_group_create_choices],
554 [x[0] for x in c.user_group_create_choices],
554 [x[0] for x in c.user_group_create_choices],
555 [x[0] for x in c.fork_choices],
555 [x[0] for x in c.fork_choices],
556 [x[0] for x in c.inherit_default_permission_choices])()
556 [x[0] for x in c.inherit_default_permission_choices])()
557
557
558 form_result = _form.to_python(dict(self.request.POST))
558 form_result = _form.to_python(dict(self.request.POST))
559 form_result.update({'perm_user_id': c.user.user_id})
559 form_result.update({'perm_user_id': c.user.user_id})
560
560
561 PermissionModel().update_user_permissions(form_result)
561 PermissionModel().update_user_permissions(form_result)
562
562
563 # TODO(marcink): implement global permissions
563 # TODO(marcink): implement global permissions
564 # audit_log.store_web('user.edit.permissions')
564 # audit_log.store_web('user.edit.permissions')
565
565
566 Session().commit()
566 Session().commit()
567 h.flash(_('User global permissions updated successfully'),
567 h.flash(_('User global permissions updated successfully'),
568 category='success')
568 category='success')
569
569
570 except formencode.Invalid as errors:
570 except formencode.Invalid as errors:
571 data = render(
571 data = render(
572 'rhodecode:templates/admin/users/user_edit.mako',
572 'rhodecode:templates/admin/users/user_edit.mako',
573 self._get_template_context(c), self.request)
573 self._get_template_context(c), self.request)
574 html = formencode.htmlfill.render(
574 html = formencode.htmlfill.render(
575 data,
575 data,
576 defaults=errors.value,
576 defaults=errors.value,
577 errors=errors.error_dict or {},
577 errors=errors.error_dict or {},
578 prefix_error=False,
578 prefix_error=False,
579 encoding="UTF-8",
579 encoding="UTF-8",
580 force_defaults=False
580 force_defaults=False
581 )
581 )
582 return Response(html)
582 return Response(html)
583 except Exception:
583 except Exception:
584 log.exception("Exception during permissions saving")
584 log.exception("Exception during permissions saving")
585 h.flash(_('An error occurred during permissions saving'),
585 h.flash(_('An error occurred during permissions saving'),
586 category='error')
586 category='error')
587 raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id))
587 raise HTTPFound(h.route_path('user_edit_global_perms', user_id=user_id))
588
588
589 @LoginRequired()
589 @LoginRequired()
590 @HasPermissionAllDecorator('hg.admin')
590 @HasPermissionAllDecorator('hg.admin')
591 @CSRFRequired()
591 @CSRFRequired()
592 @view_config(
592 @view_config(
593 route_name='user_force_password_reset', request_method='POST',
593 route_name='user_force_password_reset', request_method='POST',
594 renderer='rhodecode:templates/admin/users/user_edit.mako')
594 renderer='rhodecode:templates/admin/users/user_edit.mako')
595 def user_force_password_reset(self):
595 def user_force_password_reset(self):
596 """
596 """
597 toggle reset password flag for this user
597 toggle reset password flag for this user
598 """
598 """
599 _ = self.request.translate
599 _ = self.request.translate
600 c = self.load_default_context()
600 c = self.load_default_context()
601
601
602 user_id = self.db_user_id
602 user_id = self.db_user_id
603 c.user = self.db_user
603 c.user = self.db_user
604
604
605 try:
605 try:
606 old_value = c.user.user_data.get('force_password_change')
606 old_value = c.user.user_data.get('force_password_change')
607 c.user.update_userdata(force_password_change=not old_value)
607 c.user.update_userdata(force_password_change=not old_value)
608
608
609 if old_value:
609 if old_value:
610 msg = _('Force password change disabled for user')
610 msg = _('Force password change disabled for user')
611 audit_logger.store_web(
611 audit_logger.store_web(
612 'user.edit.password_reset.disabled',
612 'user.edit.password_reset.disabled',
613 user=c.rhodecode_user)
613 user=c.rhodecode_user)
614 else:
614 else:
615 msg = _('Force password change enabled for user')
615 msg = _('Force password change enabled for user')
616 audit_logger.store_web(
616 audit_logger.store_web(
617 'user.edit.password_reset.enabled',
617 'user.edit.password_reset.enabled',
618 user=c.rhodecode_user)
618 user=c.rhodecode_user)
619
619
620 Session().commit()
620 Session().commit()
621 h.flash(msg, category='success')
621 h.flash(msg, category='success')
622 except Exception:
622 except Exception:
623 log.exception("Exception during password reset for user")
623 log.exception("Exception during password reset for user")
624 h.flash(_('An error occurred during password reset for user'),
624 h.flash(_('An error occurred during password reset for user'),
625 category='error')
625 category='error')
626
626
627 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
627 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
628
628
629 @LoginRequired()
629 @LoginRequired()
630 @HasPermissionAllDecorator('hg.admin')
630 @HasPermissionAllDecorator('hg.admin')
631 @CSRFRequired()
631 @CSRFRequired()
632 @view_config(
632 @view_config(
633 route_name='user_create_personal_repo_group', request_method='POST',
633 route_name='user_create_personal_repo_group', request_method='POST',
634 renderer='rhodecode:templates/admin/users/user_edit.mako')
634 renderer='rhodecode:templates/admin/users/user_edit.mako')
635 def user_create_personal_repo_group(self):
635 def user_create_personal_repo_group(self):
636 """
636 """
637 Create personal repository group for this user
637 Create personal repository group for this user
638 """
638 """
639 from rhodecode.model.repo_group import RepoGroupModel
639 from rhodecode.model.repo_group import RepoGroupModel
640
640
641 _ = self.request.translate
641 _ = self.request.translate
642 c = self.load_default_context()
642 c = self.load_default_context()
643
643
644 user_id = self.db_user_id
644 user_id = self.db_user_id
645 c.user = self.db_user
645 c.user = self.db_user
646
646
647 personal_repo_group = RepoGroup.get_user_personal_repo_group(
647 personal_repo_group = RepoGroup.get_user_personal_repo_group(
648 c.user.user_id)
648 c.user.user_id)
649 if personal_repo_group:
649 if personal_repo_group:
650 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
650 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
651
651
652 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
652 personal_repo_group_name = RepoGroupModel().get_personal_group_name(
653 c.user)
653 c.user)
654 named_personal_group = RepoGroup.get_by_group_name(
654 named_personal_group = RepoGroup.get_by_group_name(
655 personal_repo_group_name)
655 personal_repo_group_name)
656 try:
656 try:
657
657
658 if named_personal_group and named_personal_group.user_id == c.user.user_id:
658 if named_personal_group and named_personal_group.user_id == c.user.user_id:
659 # migrate the same named group, and mark it as personal
659 # migrate the same named group, and mark it as personal
660 named_personal_group.personal = True
660 named_personal_group.personal = True
661 Session().add(named_personal_group)
661 Session().add(named_personal_group)
662 Session().commit()
662 Session().commit()
663 msg = _('Linked repository group `%s` as personal' % (
663 msg = _('Linked repository group `%s` as personal' % (
664 personal_repo_group_name,))
664 personal_repo_group_name,))
665 h.flash(msg, category='success')
665 h.flash(msg, category='success')
666 elif not named_personal_group:
666 elif not named_personal_group:
667 RepoGroupModel().create_personal_repo_group(c.user)
667 RepoGroupModel().create_personal_repo_group(c.user)
668
668
669 msg = _('Created repository group `%s`' % (
669 msg = _('Created repository group `%s`' % (
670 personal_repo_group_name,))
670 personal_repo_group_name,))
671 h.flash(msg, category='success')
671 h.flash(msg, category='success')
672 else:
672 else:
673 msg = _('Repository group `%s` is already taken' % (
673 msg = _('Repository group `%s` is already taken' % (
674 personal_repo_group_name,))
674 personal_repo_group_name,))
675 h.flash(msg, category='warning')
675 h.flash(msg, category='warning')
676 except Exception:
676 except Exception:
677 log.exception("Exception during repository group creation")
677 log.exception("Exception during repository group creation")
678 msg = _(
678 msg = _(
679 'An error occurred during repository group creation for user')
679 'An error occurred during repository group creation for user')
680 h.flash(msg, category='error')
680 h.flash(msg, category='error')
681 Session().rollback()
681 Session().rollback()
682
682
683 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
683 raise HTTPFound(h.route_path('user_edit_advanced', user_id=user_id))
684
684
685 @LoginRequired()
685 @LoginRequired()
686 @HasPermissionAllDecorator('hg.admin')
686 @HasPermissionAllDecorator('hg.admin')
687 @view_config(
687 @view_config(
688 route_name='edit_user_auth_tokens', request_method='GET',
688 route_name='edit_user_auth_tokens', request_method='GET',
689 renderer='rhodecode:templates/admin/users/user_edit.mako')
689 renderer='rhodecode:templates/admin/users/user_edit.mako')
690 def auth_tokens(self):
690 def auth_tokens(self):
691 _ = self.request.translate
691 _ = self.request.translate
692 c = self.load_default_context()
692 c = self.load_default_context()
693 c.user = self.db_user
693 c.user = self.db_user
694
694
695 c.active = 'auth_tokens'
695 c.active = 'auth_tokens'
696
696
697 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
697 c.lifetime_values = AuthTokenModel.get_lifetime_values(translator=_)
698 c.role_values = [
698 c.role_values = [
699 (x, AuthTokenModel.cls._get_role_name(x))
699 (x, AuthTokenModel.cls._get_role_name(x))
700 for x in AuthTokenModel.cls.ROLES]
700 for x in AuthTokenModel.cls.ROLES]
701 c.role_options = [(c.role_values, _("Role"))]
701 c.role_options = [(c.role_values, _("Role"))]
702 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
702 c.user_auth_tokens = AuthTokenModel().get_auth_tokens(
703 c.user.user_id, show_expired=True)
703 c.user.user_id, show_expired=True)
704 c.role_vcs = AuthTokenModel.cls.ROLE_VCS
704 c.role_vcs = AuthTokenModel.cls.ROLE_VCS
705 return self._get_template_context(c)
705 return self._get_template_context(c)
706
706
707 def maybe_attach_token_scope(self, token):
707 def maybe_attach_token_scope(self, token):
708 # implemented in EE edition
708 # implemented in EE edition
709 pass
709 pass
710
710
711 @LoginRequired()
711 @LoginRequired()
712 @HasPermissionAllDecorator('hg.admin')
712 @HasPermissionAllDecorator('hg.admin')
713 @CSRFRequired()
713 @CSRFRequired()
714 @view_config(
714 @view_config(
715 route_name='edit_user_auth_tokens_add', request_method='POST')
715 route_name='edit_user_auth_tokens_add', request_method='POST')
716 def auth_tokens_add(self):
716 def auth_tokens_add(self):
717 _ = self.request.translate
717 _ = self.request.translate
718 c = self.load_default_context()
718 c = self.load_default_context()
719
719
720 user_id = self.db_user_id
720 user_id = self.db_user_id
721 c.user = self.db_user
721 c.user = self.db_user
722
722
723 user_data = c.user.get_api_data()
723 user_data = c.user.get_api_data()
724 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
724 lifetime = safe_int(self.request.POST.get('lifetime'), -1)
725 description = self.request.POST.get('description')
725 description = self.request.POST.get('description')
726 role = self.request.POST.get('role')
726 role = self.request.POST.get('role')
727
727
728 token = AuthTokenModel().create(
728 token = AuthTokenModel().create(
729 c.user.user_id, description, lifetime, role)
729 c.user.user_id, description, lifetime, role)
730 token_data = token.get_api_data()
730 token_data = token.get_api_data()
731
731
732 self.maybe_attach_token_scope(token)
732 self.maybe_attach_token_scope(token)
733 audit_logger.store_web(
733 audit_logger.store_web(
734 'user.edit.token.add', action_data={
734 'user.edit.token.add', action_data={
735 'data': {'token': token_data, 'user': user_data}},
735 'data': {'token': token_data, 'user': user_data}},
736 user=self._rhodecode_user, )
736 user=self._rhodecode_user, )
737 Session().commit()
737 Session().commit()
738
738
739 h.flash(_("Auth token successfully created"), category='success')
739 h.flash(_("Auth token successfully created"), category='success')
740 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
740 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
741
741
742 @LoginRequired()
742 @LoginRequired()
743 @HasPermissionAllDecorator('hg.admin')
743 @HasPermissionAllDecorator('hg.admin')
744 @CSRFRequired()
744 @CSRFRequired()
745 @view_config(
745 @view_config(
746 route_name='edit_user_auth_tokens_delete', request_method='POST')
746 route_name='edit_user_auth_tokens_delete', request_method='POST')
747 def auth_tokens_delete(self):
747 def auth_tokens_delete(self):
748 _ = self.request.translate
748 _ = self.request.translate
749 c = self.load_default_context()
749 c = self.load_default_context()
750
750
751 user_id = self.db_user_id
751 user_id = self.db_user_id
752 c.user = self.db_user
752 c.user = self.db_user
753
753
754 user_data = c.user.get_api_data()
754 user_data = c.user.get_api_data()
755
755
756 del_auth_token = self.request.POST.get('del_auth_token')
756 del_auth_token = self.request.POST.get('del_auth_token')
757
757
758 if del_auth_token:
758 if del_auth_token:
759 token = UserApiKeys.get_or_404(del_auth_token)
759 token = UserApiKeys.get_or_404(del_auth_token)
760 token_data = token.get_api_data()
760 token_data = token.get_api_data()
761
761
762 AuthTokenModel().delete(del_auth_token, c.user.user_id)
762 AuthTokenModel().delete(del_auth_token, c.user.user_id)
763 audit_logger.store_web(
763 audit_logger.store_web(
764 'user.edit.token.delete', action_data={
764 'user.edit.token.delete', action_data={
765 'data': {'token': token_data, 'user': user_data}},
765 'data': {'token': token_data, 'user': user_data}},
766 user=self._rhodecode_user,)
766 user=self._rhodecode_user,)
767 Session().commit()
767 Session().commit()
768 h.flash(_("Auth token successfully deleted"), category='success')
768 h.flash(_("Auth token successfully deleted"), category='success')
769
769
770 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
770 return HTTPFound(h.route_path('edit_user_auth_tokens', user_id=user_id))
771
771
772 @LoginRequired()
772 @LoginRequired()
773 @HasPermissionAllDecorator('hg.admin')
773 @HasPermissionAllDecorator('hg.admin')
774 @view_config(
774 @view_config(
775 route_name='edit_user_ssh_keys', request_method='GET',
775 route_name='edit_user_ssh_keys', request_method='GET',
776 renderer='rhodecode:templates/admin/users/user_edit.mako')
776 renderer='rhodecode:templates/admin/users/user_edit.mako')
777 def ssh_keys(self):
777 def ssh_keys(self):
778 _ = self.request.translate
778 _ = self.request.translate
779 c = self.load_default_context()
779 c = self.load_default_context()
780 c.user = self.db_user
780 c.user = self.db_user
781
781
782 c.active = 'ssh_keys'
782 c.active = 'ssh_keys'
783 c.default_key = self.request.GET.get('default_key')
783 c.default_key = self.request.GET.get('default_key')
784 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
784 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
785 return self._get_template_context(c)
785 return self._get_template_context(c)
786
786
787 @LoginRequired()
787 @LoginRequired()
788 @HasPermissionAllDecorator('hg.admin')
788 @HasPermissionAllDecorator('hg.admin')
789 @view_config(
789 @view_config(
790 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
790 route_name='edit_user_ssh_keys_generate_keypair', request_method='GET',
791 renderer='rhodecode:templates/admin/users/user_edit.mako')
791 renderer='rhodecode:templates/admin/users/user_edit.mako')
792 def ssh_keys_generate_keypair(self):
792 def ssh_keys_generate_keypair(self):
793 _ = self.request.translate
793 _ = self.request.translate
794 c = self.load_default_context()
794 c = self.load_default_context()
795
795
796 c.user = self.db_user
796 c.user = self.db_user
797
797
798 c.active = 'ssh_keys_generate'
798 c.active = 'ssh_keys_generate'
799 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
799 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
800 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
800 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
801
801
802 return self._get_template_context(c)
802 return self._get_template_context(c)
803
803
804 @LoginRequired()
804 @LoginRequired()
805 @HasPermissionAllDecorator('hg.admin')
805 @HasPermissionAllDecorator('hg.admin')
806 @CSRFRequired()
806 @CSRFRequired()
807 @view_config(
807 @view_config(
808 route_name='edit_user_ssh_keys_add', request_method='POST')
808 route_name='edit_user_ssh_keys_add', request_method='POST')
809 def ssh_keys_add(self):
809 def ssh_keys_add(self):
810 _ = self.request.translate
810 _ = self.request.translate
811 c = self.load_default_context()
811 c = self.load_default_context()
812
812
813 user_id = self.db_user_id
813 user_id = self.db_user_id
814 c.user = self.db_user
814 c.user = self.db_user
815
815
816 user_data = c.user.get_api_data()
816 user_data = c.user.get_api_data()
817 key_data = self.request.POST.get('key_data')
817 key_data = self.request.POST.get('key_data')
818 description = self.request.POST.get('description')
818 description = self.request.POST.get('description')
819
819
820 fingerprint = 'unknown'
820 fingerprint = 'unknown'
821 try:
821 try:
822 if not key_data:
822 if not key_data:
823 raise ValueError('Please add a valid public key')
823 raise ValueError('Please add a valid public key')
824
824
825 key = SshKeyModel().parse_key(key_data.strip())
825 key = SshKeyModel().parse_key(key_data.strip())
826 fingerprint = key.hash_md5()
826 fingerprint = key.hash_md5()
827
827
828 ssh_key = SshKeyModel().create(
828 ssh_key = SshKeyModel().create(
829 c.user.user_id, fingerprint, key_data, description)
829 c.user.user_id, fingerprint, key.keydata, description)
830 ssh_key_data = ssh_key.get_api_data()
830 ssh_key_data = ssh_key.get_api_data()
831
831
832 audit_logger.store_web(
832 audit_logger.store_web(
833 'user.edit.ssh_key.add', action_data={
833 'user.edit.ssh_key.add', action_data={
834 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
834 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
835 user=self._rhodecode_user, )
835 user=self._rhodecode_user, )
836 Session().commit()
836 Session().commit()
837
837
838 # Trigger an event on change of keys.
838 # Trigger an event on change of keys.
839 trigger(SshKeyFileChangeEvent(), self.request.registry)
839 trigger(SshKeyFileChangeEvent(), self.request.registry)
840
840
841 h.flash(_("Ssh Key successfully created"), category='success')
841 h.flash(_("Ssh Key successfully created"), category='success')
842
842
843 except IntegrityError:
843 except IntegrityError:
844 log.exception("Exception during ssh key saving")
844 log.exception("Exception during ssh key saving")
845 err = 'Such key with fingerprint `{}` already exists, ' \
845 err = 'Such key with fingerprint `{}` already exists, ' \
846 'please use a different one'.format(fingerprint)
846 'please use a different one'.format(fingerprint)
847 h.flash(_('An error occurred during ssh key saving: {}').format(err),
847 h.flash(_('An error occurred during ssh key saving: {}').format(err),
848 category='error')
848 category='error')
849 except Exception as e:
849 except Exception as e:
850 log.exception("Exception during ssh key saving")
850 log.exception("Exception during ssh key saving")
851 h.flash(_('An error occurred during ssh key saving: {}').format(e),
851 h.flash(_('An error occurred during ssh key saving: {}').format(e),
852 category='error')
852 category='error')
853
853
854 return HTTPFound(
854 return HTTPFound(
855 h.route_path('edit_user_ssh_keys', user_id=user_id))
855 h.route_path('edit_user_ssh_keys', user_id=user_id))
856
856
857 @LoginRequired()
857 @LoginRequired()
858 @HasPermissionAllDecorator('hg.admin')
858 @HasPermissionAllDecorator('hg.admin')
859 @CSRFRequired()
859 @CSRFRequired()
860 @view_config(
860 @view_config(
861 route_name='edit_user_ssh_keys_delete', request_method='POST')
861 route_name='edit_user_ssh_keys_delete', request_method='POST')
862 def ssh_keys_delete(self):
862 def ssh_keys_delete(self):
863 _ = self.request.translate
863 _ = self.request.translate
864 c = self.load_default_context()
864 c = self.load_default_context()
865
865
866 user_id = self.db_user_id
866 user_id = self.db_user_id
867 c.user = self.db_user
867 c.user = self.db_user
868
868
869 user_data = c.user.get_api_data()
869 user_data = c.user.get_api_data()
870
870
871 del_ssh_key = self.request.POST.get('del_ssh_key')
871 del_ssh_key = self.request.POST.get('del_ssh_key')
872
872
873 if del_ssh_key:
873 if del_ssh_key:
874 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
874 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
875 ssh_key_data = ssh_key.get_api_data()
875 ssh_key_data = ssh_key.get_api_data()
876
876
877 SshKeyModel().delete(del_ssh_key, c.user.user_id)
877 SshKeyModel().delete(del_ssh_key, c.user.user_id)
878 audit_logger.store_web(
878 audit_logger.store_web(
879 'user.edit.ssh_key.delete', action_data={
879 'user.edit.ssh_key.delete', action_data={
880 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
880 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
881 user=self._rhodecode_user,)
881 user=self._rhodecode_user,)
882 Session().commit()
882 Session().commit()
883 # Trigger an event on change of keys.
883 # Trigger an event on change of keys.
884 trigger(SshKeyFileChangeEvent(), self.request.registry)
884 trigger(SshKeyFileChangeEvent(), self.request.registry)
885 h.flash(_("Ssh key successfully deleted"), category='success')
885 h.flash(_("Ssh key successfully deleted"), category='success')
886
886
887 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
887 return HTTPFound(h.route_path('edit_user_ssh_keys', user_id=user_id))
888
888
889 @LoginRequired()
889 @LoginRequired()
890 @HasPermissionAllDecorator('hg.admin')
890 @HasPermissionAllDecorator('hg.admin')
891 @view_config(
891 @view_config(
892 route_name='edit_user_emails', request_method='GET',
892 route_name='edit_user_emails', request_method='GET',
893 renderer='rhodecode:templates/admin/users/user_edit.mako')
893 renderer='rhodecode:templates/admin/users/user_edit.mako')
894 def emails(self):
894 def emails(self):
895 _ = self.request.translate
895 _ = self.request.translate
896 c = self.load_default_context()
896 c = self.load_default_context()
897 c.user = self.db_user
897 c.user = self.db_user
898
898
899 c.active = 'emails'
899 c.active = 'emails'
900 c.user_email_map = UserEmailMap.query() \
900 c.user_email_map = UserEmailMap.query() \
901 .filter(UserEmailMap.user == c.user).all()
901 .filter(UserEmailMap.user == c.user).all()
902
902
903 return self._get_template_context(c)
903 return self._get_template_context(c)
904
904
905 @LoginRequired()
905 @LoginRequired()
906 @HasPermissionAllDecorator('hg.admin')
906 @HasPermissionAllDecorator('hg.admin')
907 @CSRFRequired()
907 @CSRFRequired()
908 @view_config(
908 @view_config(
909 route_name='edit_user_emails_add', request_method='POST')
909 route_name='edit_user_emails_add', request_method='POST')
910 def emails_add(self):
910 def emails_add(self):
911 _ = self.request.translate
911 _ = self.request.translate
912 c = self.load_default_context()
912 c = self.load_default_context()
913
913
914 user_id = self.db_user_id
914 user_id = self.db_user_id
915 c.user = self.db_user
915 c.user = self.db_user
916
916
917 email = self.request.POST.get('new_email')
917 email = self.request.POST.get('new_email')
918 user_data = c.user.get_api_data()
918 user_data = c.user.get_api_data()
919 try:
919 try:
920
920
921 form = UserExtraEmailForm(self.request.translate)()
921 form = UserExtraEmailForm(self.request.translate)()
922 data = form.to_python({'email': email})
922 data = form.to_python({'email': email})
923 email = data['email']
923 email = data['email']
924
924
925 UserModel().add_extra_email(c.user.user_id, email)
925 UserModel().add_extra_email(c.user.user_id, email)
926 audit_logger.store_web(
926 audit_logger.store_web(
927 'user.edit.email.add',
927 'user.edit.email.add',
928 action_data={'email': email, 'user': user_data},
928 action_data={'email': email, 'user': user_data},
929 user=self._rhodecode_user)
929 user=self._rhodecode_user)
930 Session().commit()
930 Session().commit()
931 h.flash(_("Added new email address `%s` for user account") % email,
931 h.flash(_("Added new email address `%s` for user account") % email,
932 category='success')
932 category='success')
933 except formencode.Invalid as error:
933 except formencode.Invalid as error:
934 h.flash(h.escape(error.error_dict['email']), category='error')
934 h.flash(h.escape(error.error_dict['email']), category='error')
935 except IntegrityError:
935 except IntegrityError:
936 log.warning("Email %s already exists", email)
936 log.warning("Email %s already exists", email)
937 h.flash(_('Email `{}` is already registered for another user.').format(email),
937 h.flash(_('Email `{}` is already registered for another user.').format(email),
938 category='error')
938 category='error')
939 except Exception:
939 except Exception:
940 log.exception("Exception during email saving")
940 log.exception("Exception during email saving")
941 h.flash(_('An error occurred during email saving'),
941 h.flash(_('An error occurred during email saving'),
942 category='error')
942 category='error')
943 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
943 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
944
944
945 @LoginRequired()
945 @LoginRequired()
946 @HasPermissionAllDecorator('hg.admin')
946 @HasPermissionAllDecorator('hg.admin')
947 @CSRFRequired()
947 @CSRFRequired()
948 @view_config(
948 @view_config(
949 route_name='edit_user_emails_delete', request_method='POST')
949 route_name='edit_user_emails_delete', request_method='POST')
950 def emails_delete(self):
950 def emails_delete(self):
951 _ = self.request.translate
951 _ = self.request.translate
952 c = self.load_default_context()
952 c = self.load_default_context()
953
953
954 user_id = self.db_user_id
954 user_id = self.db_user_id
955 c.user = self.db_user
955 c.user = self.db_user
956
956
957 email_id = self.request.POST.get('del_email_id')
957 email_id = self.request.POST.get('del_email_id')
958 user_model = UserModel()
958 user_model = UserModel()
959
959
960 email = UserEmailMap.query().get(email_id).email
960 email = UserEmailMap.query().get(email_id).email
961 user_data = c.user.get_api_data()
961 user_data = c.user.get_api_data()
962 user_model.delete_extra_email(c.user.user_id, email_id)
962 user_model.delete_extra_email(c.user.user_id, email_id)
963 audit_logger.store_web(
963 audit_logger.store_web(
964 'user.edit.email.delete',
964 'user.edit.email.delete',
965 action_data={'email': email, 'user': user_data},
965 action_data={'email': email, 'user': user_data},
966 user=self._rhodecode_user)
966 user=self._rhodecode_user)
967 Session().commit()
967 Session().commit()
968 h.flash(_("Removed email address from user account"),
968 h.flash(_("Removed email address from user account"),
969 category='success')
969 category='success')
970 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
970 raise HTTPFound(h.route_path('edit_user_emails', user_id=user_id))
971
971
972 @LoginRequired()
972 @LoginRequired()
973 @HasPermissionAllDecorator('hg.admin')
973 @HasPermissionAllDecorator('hg.admin')
974 @view_config(
974 @view_config(
975 route_name='edit_user_ips', request_method='GET',
975 route_name='edit_user_ips', request_method='GET',
976 renderer='rhodecode:templates/admin/users/user_edit.mako')
976 renderer='rhodecode:templates/admin/users/user_edit.mako')
977 def ips(self):
977 def ips(self):
978 _ = self.request.translate
978 _ = self.request.translate
979 c = self.load_default_context()
979 c = self.load_default_context()
980 c.user = self.db_user
980 c.user = self.db_user
981
981
982 c.active = 'ips'
982 c.active = 'ips'
983 c.user_ip_map = UserIpMap.query() \
983 c.user_ip_map = UserIpMap.query() \
984 .filter(UserIpMap.user == c.user).all()
984 .filter(UserIpMap.user == c.user).all()
985
985
986 c.inherit_default_ips = c.user.inherit_default_permissions
986 c.inherit_default_ips = c.user.inherit_default_permissions
987 c.default_user_ip_map = UserIpMap.query() \
987 c.default_user_ip_map = UserIpMap.query() \
988 .filter(UserIpMap.user == User.get_default_user()).all()
988 .filter(UserIpMap.user == User.get_default_user()).all()
989
989
990 return self._get_template_context(c)
990 return self._get_template_context(c)
991
991
992 @LoginRequired()
992 @LoginRequired()
993 @HasPermissionAllDecorator('hg.admin')
993 @HasPermissionAllDecorator('hg.admin')
994 @CSRFRequired()
994 @CSRFRequired()
995 @view_config(
995 @view_config(
996 route_name='edit_user_ips_add', request_method='POST')
996 route_name='edit_user_ips_add', request_method='POST')
997 # NOTE(marcink): this view is allowed for default users, as we can
997 # NOTE(marcink): this view is allowed for default users, as we can
998 # edit their IP white list
998 # edit their IP white list
999 def ips_add(self):
999 def ips_add(self):
1000 _ = self.request.translate
1000 _ = self.request.translate
1001 c = self.load_default_context()
1001 c = self.load_default_context()
1002
1002
1003 user_id = self.db_user_id
1003 user_id = self.db_user_id
1004 c.user = self.db_user
1004 c.user = self.db_user
1005
1005
1006 user_model = UserModel()
1006 user_model = UserModel()
1007 desc = self.request.POST.get('description')
1007 desc = self.request.POST.get('description')
1008 try:
1008 try:
1009 ip_list = user_model.parse_ip_range(
1009 ip_list = user_model.parse_ip_range(
1010 self.request.POST.get('new_ip'))
1010 self.request.POST.get('new_ip'))
1011 except Exception as e:
1011 except Exception as e:
1012 ip_list = []
1012 ip_list = []
1013 log.exception("Exception during ip saving")
1013 log.exception("Exception during ip saving")
1014 h.flash(_('An error occurred during ip saving:%s' % (e,)),
1014 h.flash(_('An error occurred during ip saving:%s' % (e,)),
1015 category='error')
1015 category='error')
1016 added = []
1016 added = []
1017 user_data = c.user.get_api_data()
1017 user_data = c.user.get_api_data()
1018 for ip in ip_list:
1018 for ip in ip_list:
1019 try:
1019 try:
1020 form = UserExtraIpForm(self.request.translate)()
1020 form = UserExtraIpForm(self.request.translate)()
1021 data = form.to_python({'ip': ip})
1021 data = form.to_python({'ip': ip})
1022 ip = data['ip']
1022 ip = data['ip']
1023
1023
1024 user_model.add_extra_ip(c.user.user_id, ip, desc)
1024 user_model.add_extra_ip(c.user.user_id, ip, desc)
1025 audit_logger.store_web(
1025 audit_logger.store_web(
1026 'user.edit.ip.add',
1026 'user.edit.ip.add',
1027 action_data={'ip': ip, 'user': user_data},
1027 action_data={'ip': ip, 'user': user_data},
1028 user=self._rhodecode_user)
1028 user=self._rhodecode_user)
1029 Session().commit()
1029 Session().commit()
1030 added.append(ip)
1030 added.append(ip)
1031 except formencode.Invalid as error:
1031 except formencode.Invalid as error:
1032 msg = error.error_dict['ip']
1032 msg = error.error_dict['ip']
1033 h.flash(msg, category='error')
1033 h.flash(msg, category='error')
1034 except Exception:
1034 except Exception:
1035 log.exception("Exception during ip saving")
1035 log.exception("Exception during ip saving")
1036 h.flash(_('An error occurred during ip saving'),
1036 h.flash(_('An error occurred during ip saving'),
1037 category='error')
1037 category='error')
1038 if added:
1038 if added:
1039 h.flash(
1039 h.flash(
1040 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
1040 _("Added ips %s to user whitelist") % (', '.join(ip_list), ),
1041 category='success')
1041 category='success')
1042 if 'default_user' in self.request.POST:
1042 if 'default_user' in self.request.POST:
1043 # case for editing global IP list we do it for 'DEFAULT' user
1043 # case for editing global IP list we do it for 'DEFAULT' user
1044 raise HTTPFound(h.route_path('admin_permissions_ips'))
1044 raise HTTPFound(h.route_path('admin_permissions_ips'))
1045 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1045 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1046
1046
1047 @LoginRequired()
1047 @LoginRequired()
1048 @HasPermissionAllDecorator('hg.admin')
1048 @HasPermissionAllDecorator('hg.admin')
1049 @CSRFRequired()
1049 @CSRFRequired()
1050 @view_config(
1050 @view_config(
1051 route_name='edit_user_ips_delete', request_method='POST')
1051 route_name='edit_user_ips_delete', request_method='POST')
1052 # NOTE(marcink): this view is allowed for default users, as we can
1052 # NOTE(marcink): this view is allowed for default users, as we can
1053 # edit their IP white list
1053 # edit their IP white list
1054 def ips_delete(self):
1054 def ips_delete(self):
1055 _ = self.request.translate
1055 _ = self.request.translate
1056 c = self.load_default_context()
1056 c = self.load_default_context()
1057
1057
1058 user_id = self.db_user_id
1058 user_id = self.db_user_id
1059 c.user = self.db_user
1059 c.user = self.db_user
1060
1060
1061 ip_id = self.request.POST.get('del_ip_id')
1061 ip_id = self.request.POST.get('del_ip_id')
1062 user_model = UserModel()
1062 user_model = UserModel()
1063 user_data = c.user.get_api_data()
1063 user_data = c.user.get_api_data()
1064 ip = UserIpMap.query().get(ip_id).ip_addr
1064 ip = UserIpMap.query().get(ip_id).ip_addr
1065 user_model.delete_extra_ip(c.user.user_id, ip_id)
1065 user_model.delete_extra_ip(c.user.user_id, ip_id)
1066 audit_logger.store_web(
1066 audit_logger.store_web(
1067 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
1067 'user.edit.ip.delete', action_data={'ip': ip, 'user': user_data},
1068 user=self._rhodecode_user)
1068 user=self._rhodecode_user)
1069 Session().commit()
1069 Session().commit()
1070 h.flash(_("Removed ip address from user whitelist"), category='success')
1070 h.flash(_("Removed ip address from user whitelist"), category='success')
1071
1071
1072 if 'default_user' in self.request.POST:
1072 if 'default_user' in self.request.POST:
1073 # case for editing global IP list we do it for 'DEFAULT' user
1073 # case for editing global IP list we do it for 'DEFAULT' user
1074 raise HTTPFound(h.route_path('admin_permissions_ips'))
1074 raise HTTPFound(h.route_path('admin_permissions_ips'))
1075 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1075 raise HTTPFound(h.route_path('edit_user_ips', user_id=user_id))
1076
1076
1077 @LoginRequired()
1077 @LoginRequired()
1078 @HasPermissionAllDecorator('hg.admin')
1078 @HasPermissionAllDecorator('hg.admin')
1079 @view_config(
1079 @view_config(
1080 route_name='edit_user_groups_management', request_method='GET',
1080 route_name='edit_user_groups_management', request_method='GET',
1081 renderer='rhodecode:templates/admin/users/user_edit.mako')
1081 renderer='rhodecode:templates/admin/users/user_edit.mako')
1082 def groups_management(self):
1082 def groups_management(self):
1083 c = self.load_default_context()
1083 c = self.load_default_context()
1084 c.user = self.db_user
1084 c.user = self.db_user
1085 c.data = c.user.group_member
1085 c.data = c.user.group_member
1086
1086
1087 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
1087 groups = [UserGroupModel.get_user_groups_as_dict(group.users_group)
1088 for group in c.user.group_member]
1088 for group in c.user.group_member]
1089 c.groups = json.dumps(groups)
1089 c.groups = json.dumps(groups)
1090 c.active = 'groups'
1090 c.active = 'groups'
1091
1091
1092 return self._get_template_context(c)
1092 return self._get_template_context(c)
1093
1093
1094 @LoginRequired()
1094 @LoginRequired()
1095 @HasPermissionAllDecorator('hg.admin')
1095 @HasPermissionAllDecorator('hg.admin')
1096 @CSRFRequired()
1096 @CSRFRequired()
1097 @view_config(
1097 @view_config(
1098 route_name='edit_user_groups_management_updates', request_method='POST')
1098 route_name='edit_user_groups_management_updates', request_method='POST')
1099 def groups_management_updates(self):
1099 def groups_management_updates(self):
1100 _ = self.request.translate
1100 _ = self.request.translate
1101 c = self.load_default_context()
1101 c = self.load_default_context()
1102
1102
1103 user_id = self.db_user_id
1103 user_id = self.db_user_id
1104 c.user = self.db_user
1104 c.user = self.db_user
1105
1105
1106 user_groups = set(self.request.POST.getall('users_group_id'))
1106 user_groups = set(self.request.POST.getall('users_group_id'))
1107 user_groups_objects = []
1107 user_groups_objects = []
1108
1108
1109 for ugid in user_groups:
1109 for ugid in user_groups:
1110 user_groups_objects.append(
1110 user_groups_objects.append(
1111 UserGroupModel().get_group(safe_int(ugid)))
1111 UserGroupModel().get_group(safe_int(ugid)))
1112 user_group_model = UserGroupModel()
1112 user_group_model = UserGroupModel()
1113 added_to_groups, removed_from_groups = \
1113 added_to_groups, removed_from_groups = \
1114 user_group_model.change_groups(c.user, user_groups_objects)
1114 user_group_model.change_groups(c.user, user_groups_objects)
1115
1115
1116 user_data = c.user.get_api_data()
1116 user_data = c.user.get_api_data()
1117 for user_group_id in added_to_groups:
1117 for user_group_id in added_to_groups:
1118 user_group = UserGroup.get(user_group_id)
1118 user_group = UserGroup.get(user_group_id)
1119 old_values = user_group.get_api_data()
1119 old_values = user_group.get_api_data()
1120 audit_logger.store_web(
1120 audit_logger.store_web(
1121 'user_group.edit.member.add',
1121 'user_group.edit.member.add',
1122 action_data={'user': user_data, 'old_data': old_values},
1122 action_data={'user': user_data, 'old_data': old_values},
1123 user=self._rhodecode_user)
1123 user=self._rhodecode_user)
1124
1124
1125 for user_group_id in removed_from_groups:
1125 for user_group_id in removed_from_groups:
1126 user_group = UserGroup.get(user_group_id)
1126 user_group = UserGroup.get(user_group_id)
1127 old_values = user_group.get_api_data()
1127 old_values = user_group.get_api_data()
1128 audit_logger.store_web(
1128 audit_logger.store_web(
1129 'user_group.edit.member.delete',
1129 'user_group.edit.member.delete',
1130 action_data={'user': user_data, 'old_data': old_values},
1130 action_data={'user': user_data, 'old_data': old_values},
1131 user=self._rhodecode_user)
1131 user=self._rhodecode_user)
1132
1132
1133 Session().commit()
1133 Session().commit()
1134 c.active = 'user_groups_management'
1134 c.active = 'user_groups_management'
1135 h.flash(_("Groups successfully changed"), category='success')
1135 h.flash(_("Groups successfully changed"), category='success')
1136
1136
1137 return HTTPFound(h.route_path(
1137 return HTTPFound(h.route_path(
1138 'edit_user_groups_management', user_id=user_id))
1138 'edit_user_groups_management', user_id=user_id))
1139
1139
1140 @LoginRequired()
1140 @LoginRequired()
1141 @HasPermissionAllDecorator('hg.admin')
1141 @HasPermissionAllDecorator('hg.admin')
1142 @view_config(
1142 @view_config(
1143 route_name='edit_user_audit_logs', request_method='GET',
1143 route_name='edit_user_audit_logs', request_method='GET',
1144 renderer='rhodecode:templates/admin/users/user_edit.mako')
1144 renderer='rhodecode:templates/admin/users/user_edit.mako')
1145 def user_audit_logs(self):
1145 def user_audit_logs(self):
1146 _ = self.request.translate
1146 _ = self.request.translate
1147 c = self.load_default_context()
1147 c = self.load_default_context()
1148 c.user = self.db_user
1148 c.user = self.db_user
1149
1149
1150 c.active = 'audit'
1150 c.active = 'audit'
1151
1151
1152 p = safe_int(self.request.GET.get('page', 1), 1)
1152 p = safe_int(self.request.GET.get('page', 1), 1)
1153
1153
1154 filter_term = self.request.GET.get('filter')
1154 filter_term = self.request.GET.get('filter')
1155 user_log = UserModel().get_user_log(c.user, filter_term)
1155 user_log = UserModel().get_user_log(c.user, filter_term)
1156
1156
1157 def url_generator(**kw):
1157 def url_generator(**kw):
1158 if filter_term:
1158 if filter_term:
1159 kw['filter'] = filter_term
1159 kw['filter'] = filter_term
1160 return self.request.current_route_path(_query=kw)
1160 return self.request.current_route_path(_query=kw)
1161
1161
1162 c.audit_logs = h.Page(
1162 c.audit_logs = h.Page(
1163 user_log, page=p, items_per_page=10, url=url_generator)
1163 user_log, page=p, items_per_page=10, url=url_generator)
1164 c.filter_term = filter_term
1164 c.filter_term = filter_term
1165 return self._get_template_context(c)
1165 return self._get_template_context(c)
1166
1166
1167 @LoginRequired()
1167 @LoginRequired()
1168 @HasPermissionAllDecorator('hg.admin')
1168 @HasPermissionAllDecorator('hg.admin')
1169 @view_config(
1169 @view_config(
1170 route_name='edit_user_perms_summary', request_method='GET',
1170 route_name='edit_user_perms_summary', request_method='GET',
1171 renderer='rhodecode:templates/admin/users/user_edit.mako')
1171 renderer='rhodecode:templates/admin/users/user_edit.mako')
1172 def user_perms_summary(self):
1172 def user_perms_summary(self):
1173 _ = self.request.translate
1173 _ = self.request.translate
1174 c = self.load_default_context()
1174 c = self.load_default_context()
1175 c.user = self.db_user
1175 c.user = self.db_user
1176
1176
1177 c.active = 'perms_summary'
1177 c.active = 'perms_summary'
1178 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1178 c.perm_user = c.user.AuthUser(ip_addr=self.request.remote_addr)
1179
1179
1180 return self._get_template_context(c)
1180 return self._get_template_context(c)
1181
1181
1182 @LoginRequired()
1182 @LoginRequired()
1183 @HasPermissionAllDecorator('hg.admin')
1183 @HasPermissionAllDecorator('hg.admin')
1184 @view_config(
1184 @view_config(
1185 route_name='edit_user_perms_summary_json', request_method='GET',
1185 route_name='edit_user_perms_summary_json', request_method='GET',
1186 renderer='json_ext')
1186 renderer='json_ext')
1187 def user_perms_summary_json(self):
1187 def user_perms_summary_json(self):
1188 self.load_default_context()
1188 self.load_default_context()
1189 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
1189 perm_user = self.db_user.AuthUser(ip_addr=self.request.remote_addr)
1190
1190
1191 return perm_user.permissions
1191 return perm_user.permissions
@@ -1,155 +1,155 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2018 RhodeCode GmbH
3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22
22
23 from pyramid.httpexceptions import HTTPFound
23 from pyramid.httpexceptions import HTTPFound
24 from pyramid.view import view_config
24 from pyramid.view import view_config
25
25
26 from rhodecode.apps._base import BaseAppView, DataGridAppView
26 from rhodecode.apps._base import BaseAppView, DataGridAppView
27 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
27 from rhodecode.apps.ssh_support import SshKeyFileChangeEvent
28 from rhodecode.events import trigger
28 from rhodecode.events import trigger
29 from rhodecode.lib import helpers as h
29 from rhodecode.lib import helpers as h
30 from rhodecode.lib import audit_logger
30 from rhodecode.lib import audit_logger
31 from rhodecode.lib.auth import LoginRequired, NotAnonymous, CSRFRequired
31 from rhodecode.lib.auth import LoginRequired, NotAnonymous, CSRFRequired
32 from rhodecode.model.db import IntegrityError, UserSshKeys
32 from rhodecode.model.db import IntegrityError, UserSshKeys
33 from rhodecode.model.meta import Session
33 from rhodecode.model.meta import Session
34 from rhodecode.model.ssh_key import SshKeyModel
34 from rhodecode.model.ssh_key import SshKeyModel
35
35
36 log = logging.getLogger(__name__)
36 log = logging.getLogger(__name__)
37
37
38
38
39 class MyAccountSshKeysView(BaseAppView, DataGridAppView):
39 class MyAccountSshKeysView(BaseAppView, DataGridAppView):
40
40
41 def load_default_context(self):
41 def load_default_context(self):
42 c = self._get_local_tmpl_context()
42 c = self._get_local_tmpl_context()
43 c.user = c.auth_user.get_instance()
43 c.user = c.auth_user.get_instance()
44
44
45 c.ssh_enabled = self.request.registry.settings.get(
45 c.ssh_enabled = self.request.registry.settings.get(
46 'ssh.generate_authorized_keyfile')
46 'ssh.generate_authorized_keyfile')
47
47
48 return c
48 return c
49
49
50 @LoginRequired()
50 @LoginRequired()
51 @NotAnonymous()
51 @NotAnonymous()
52 @view_config(
52 @view_config(
53 route_name='my_account_ssh_keys', request_method='GET',
53 route_name='my_account_ssh_keys', request_method='GET',
54 renderer='rhodecode:templates/admin/my_account/my_account.mako')
54 renderer='rhodecode:templates/admin/my_account/my_account.mako')
55 def my_account_ssh_keys(self):
55 def my_account_ssh_keys(self):
56 _ = self.request.translate
56 _ = self.request.translate
57
57
58 c = self.load_default_context()
58 c = self.load_default_context()
59 c.active = 'ssh_keys'
59 c.active = 'ssh_keys'
60 c.default_key = self.request.GET.get('default_key')
60 c.default_key = self.request.GET.get('default_key')
61 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
61 c.user_ssh_keys = SshKeyModel().get_ssh_keys(c.user.user_id)
62 return self._get_template_context(c)
62 return self._get_template_context(c)
63
63
64 @LoginRequired()
64 @LoginRequired()
65 @NotAnonymous()
65 @NotAnonymous()
66 @view_config(
66 @view_config(
67 route_name='my_account_ssh_keys_generate', request_method='GET',
67 route_name='my_account_ssh_keys_generate', request_method='GET',
68 renderer='rhodecode:templates/admin/my_account/my_account.mako')
68 renderer='rhodecode:templates/admin/my_account/my_account.mako')
69 def ssh_keys_generate_keypair(self):
69 def ssh_keys_generate_keypair(self):
70 _ = self.request.translate
70 _ = self.request.translate
71 c = self.load_default_context()
71 c = self.load_default_context()
72
72
73 c.active = 'ssh_keys_generate'
73 c.active = 'ssh_keys_generate'
74 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
74 comment = 'RhodeCode-SSH {}'.format(c.user.email or '')
75 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
75 c.private, c.public = SshKeyModel().generate_keypair(comment=comment)
76 c.target_form_url = h.route_path(
76 c.target_form_url = h.route_path(
77 'my_account_ssh_keys', _query=dict(default_key=c.public))
77 'my_account_ssh_keys', _query=dict(default_key=c.public))
78 return self._get_template_context(c)
78 return self._get_template_context(c)
79
79
80 @LoginRequired()
80 @LoginRequired()
81 @NotAnonymous()
81 @NotAnonymous()
82 @CSRFRequired()
82 @CSRFRequired()
83 @view_config(
83 @view_config(
84 route_name='my_account_ssh_keys_add', request_method='POST',)
84 route_name='my_account_ssh_keys_add', request_method='POST',)
85 def my_account_ssh_keys_add(self):
85 def my_account_ssh_keys_add(self):
86 _ = self.request.translate
86 _ = self.request.translate
87 c = self.load_default_context()
87 c = self.load_default_context()
88
88
89 user_data = c.user.get_api_data()
89 user_data = c.user.get_api_data()
90 key_data = self.request.POST.get('key_data')
90 key_data = self.request.POST.get('key_data')
91 description = self.request.POST.get('description')
91 description = self.request.POST.get('description')
92 fingerprint = 'unknown'
92 fingerprint = 'unknown'
93 try:
93 try:
94 if not key_data:
94 if not key_data:
95 raise ValueError('Please add a valid public key')
95 raise ValueError('Please add a valid public key')
96
96
97 key = SshKeyModel().parse_key(key_data.strip())
97 key = SshKeyModel().parse_key(key_data.strip())
98 fingerprint = key.hash_md5()
98 fingerprint = key.hash_md5()
99
99
100 ssh_key = SshKeyModel().create(
100 ssh_key = SshKeyModel().create(
101 c.user.user_id, fingerprint, key_data, description)
101 c.user.user_id, fingerprint, key.keydata, description)
102 ssh_key_data = ssh_key.get_api_data()
102 ssh_key_data = ssh_key.get_api_data()
103
103
104 audit_logger.store_web(
104 audit_logger.store_web(
105 'user.edit.ssh_key.add', action_data={
105 'user.edit.ssh_key.add', action_data={
106 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
106 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
107 user=self._rhodecode_user, )
107 user=self._rhodecode_user, )
108 Session().commit()
108 Session().commit()
109
109
110 # Trigger an event on change of keys.
110 # Trigger an event on change of keys.
111 trigger(SshKeyFileChangeEvent(), self.request.registry)
111 trigger(SshKeyFileChangeEvent(), self.request.registry)
112
112
113 h.flash(_("Ssh Key successfully created"), category='success')
113 h.flash(_("Ssh Key successfully created"), category='success')
114
114
115 except IntegrityError:
115 except IntegrityError:
116 log.exception("Exception during ssh key saving")
116 log.exception("Exception during ssh key saving")
117 err = 'Such key with fingerprint `{}` already exists, ' \
117 err = 'Such key with fingerprint `{}` already exists, ' \
118 'please use a different one'.format(fingerprint)
118 'please use a different one'.format(fingerprint)
119 h.flash(_('An error occurred during ssh key saving: {}').format(err),
119 h.flash(_('An error occurred during ssh key saving: {}').format(err),
120 category='error')
120 category='error')
121 except Exception as e:
121 except Exception as e:
122 log.exception("Exception during ssh key saving")
122 log.exception("Exception during ssh key saving")
123 h.flash(_('An error occurred during ssh key saving: {}').format(e),
123 h.flash(_('An error occurred during ssh key saving: {}').format(e),
124 category='error')
124 category='error')
125
125
126 return HTTPFound(h.route_path('my_account_ssh_keys'))
126 return HTTPFound(h.route_path('my_account_ssh_keys'))
127
127
128 @LoginRequired()
128 @LoginRequired()
129 @NotAnonymous()
129 @NotAnonymous()
130 @CSRFRequired()
130 @CSRFRequired()
131 @view_config(
131 @view_config(
132 route_name='my_account_ssh_keys_delete', request_method='POST')
132 route_name='my_account_ssh_keys_delete', request_method='POST')
133 def my_account_ssh_keys_delete(self):
133 def my_account_ssh_keys_delete(self):
134 _ = self.request.translate
134 _ = self.request.translate
135 c = self.load_default_context()
135 c = self.load_default_context()
136
136
137 user_data = c.user.get_api_data()
137 user_data = c.user.get_api_data()
138
138
139 del_ssh_key = self.request.POST.get('del_ssh_key')
139 del_ssh_key = self.request.POST.get('del_ssh_key')
140
140
141 if del_ssh_key:
141 if del_ssh_key:
142 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
142 ssh_key = UserSshKeys.get_or_404(del_ssh_key)
143 ssh_key_data = ssh_key.get_api_data()
143 ssh_key_data = ssh_key.get_api_data()
144
144
145 SshKeyModel().delete(del_ssh_key, c.user.user_id)
145 SshKeyModel().delete(del_ssh_key, c.user.user_id)
146 audit_logger.store_web(
146 audit_logger.store_web(
147 'user.edit.ssh_key.delete', action_data={
147 'user.edit.ssh_key.delete', action_data={
148 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
148 'data': {'ssh_key': ssh_key_data, 'user': user_data}},
149 user=self._rhodecode_user,)
149 user=self._rhodecode_user,)
150 Session().commit()
150 Session().commit()
151 # Trigger an event on change of keys.
151 # Trigger an event on change of keys.
152 trigger(SshKeyFileChangeEvent(), self.request.registry)
152 trigger(SshKeyFileChangeEvent(), self.request.registry)
153 h.flash(_("Ssh key successfully deleted"), category='success')
153 h.flash(_("Ssh key successfully deleted"), category='success')
154
154
155 return HTTPFound(h.route_path('my_account_ssh_keys'))
155 return HTTPFound(h.route_path('my_account_ssh_keys'))
@@ -1,131 +1,132 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2016-2018 RhodeCode GmbH
3 # Copyright (C) 2016-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import os
21 import os
22 import stat
22 import stat
23 import logging
23 import logging
24 import tempfile
24 import tempfile
25 import datetime
25 import datetime
26
26
27 from . import config_keys
27 from . import config_keys
28 from rhodecode.model.db import true, joinedload, User, UserSshKeys
28 from rhodecode.model.db import true, joinedload, User, UserSshKeys
29
29
30
30
31 log = logging.getLogger(__name__)
31 log = logging.getLogger(__name__)
32
32
33 HEADER = \
33 HEADER = \
34 "# This file is managed by RhodeCode, please do not edit it manually. # \n" \
34 "# This file is managed by RhodeCode, please do not edit it manually. # \n" \
35 "# Current entries: {}, create date: UTC:{}.\n"
35 "# Current entries: {}, create date: UTC:{}.\n"
36
36
37 # Default SSH options for authorized_keys file, can be override via .ini
37 # Default SSH options for authorized_keys file, can be override via .ini
38 SSH_OPTS = 'no-pty,no-port-forwarding,no-X11-forwarding,no-agent-forwarding'
38 SSH_OPTS = 'no-pty,no-port-forwarding,no-X11-forwarding,no-agent-forwarding'
39
39
40
40
41 def get_all_active_keys():
41 def get_all_active_keys():
42 result = UserSshKeys.query() \
42 result = UserSshKeys.query() \
43 .options(joinedload(UserSshKeys.user)) \
43 .options(joinedload(UserSshKeys.user)) \
44 .filter(UserSshKeys.user != User.get_default_user()) \
44 .filter(UserSshKeys.user != User.get_default_user()) \
45 .filter(User.active == true()) \
45 .filter(User.active == true()) \
46 .all()
46 .all()
47 return result
47 return result
48
48
49
49
50 def _generate_ssh_authorized_keys_file(
50 def _generate_ssh_authorized_keys_file(
51 authorized_keys_file_path, ssh_wrapper_cmd, allow_shell, ssh_opts, debug):
51 authorized_keys_file_path, ssh_wrapper_cmd, allow_shell, ssh_opts, debug):
52
52
53 authorized_keys_file_path = os.path.abspath(
53 authorized_keys_file_path = os.path.abspath(
54 os.path.expanduser(authorized_keys_file_path))
54 os.path.expanduser(authorized_keys_file_path))
55
55
56 import rhodecode
56 import rhodecode
57 all_active_keys = get_all_active_keys()
57 all_active_keys = get_all_active_keys()
58
58
59 if allow_shell:
59 if allow_shell:
60 ssh_wrapper_cmd = ssh_wrapper_cmd + ' --shell'
60 ssh_wrapper_cmd = ssh_wrapper_cmd + ' --shell'
61 if debug:
61 if debug:
62 ssh_wrapper_cmd = ssh_wrapper_cmd + ' --debug'
62 ssh_wrapper_cmd = ssh_wrapper_cmd + ' --debug'
63
63
64 if not os.path.isfile(authorized_keys_file_path):
64 if not os.path.isfile(authorized_keys_file_path):
65 log.debug('Creating file at %s', authorized_keys_file_path)
65 log.debug('Creating file at %s', authorized_keys_file_path)
66 with open(authorized_keys_file_path, 'w'):
66 with open(authorized_keys_file_path, 'w'):
67 pass
67 pass
68
68
69 if not os.access(authorized_keys_file_path, os.R_OK):
69 if not os.access(authorized_keys_file_path, os.R_OK):
70 raise OSError('Access to file {} is without read access'.format(
70 raise OSError('Access to file {} is without read access'.format(
71 authorized_keys_file_path))
71 authorized_keys_file_path))
72
72
73 line_tmpl = '{ssh_opts},command="{wrapper_command} {ini_path} --user-id={user_id} --user={user} --key-id={user_key_id}" {key}\n'
73 line_tmpl = '{ssh_opts},command="{wrapper_command} {ini_path} --user-id={user_id} --user={user} --key-id={user_key_id}" {key}\n'
74
74
75 fd, tmp_authorized_keys = tempfile.mkstemp(
75 fd, tmp_authorized_keys = tempfile.mkstemp(
76 '.authorized_keys_write',
76 '.authorized_keys_write',
77 dir=os.path.dirname(authorized_keys_file_path))
77 dir=os.path.dirname(authorized_keys_file_path))
78
78
79 now = datetime.datetime.utcnow().isoformat()
79 now = datetime.datetime.utcnow().isoformat()
80 keys_file = os.fdopen(fd, 'wb')
80 keys_file = os.fdopen(fd, 'wb')
81 keys_file.write(HEADER.format(len(all_active_keys), now))
81 keys_file.write(HEADER.format(len(all_active_keys), now))
82 ini_path = rhodecode.CONFIG['__file__']
82 ini_path = rhodecode.CONFIG['__file__']
83
83
84 for user_key in all_active_keys:
84 for user_key in all_active_keys:
85 username = user_key.user.username
85 username = user_key.user.username
86 user_id = user_key.user.user_id
86 user_id = user_key.user.user_id
87 # replace all newline from ends and inside
87 # replace all newline from ends and inside
88 safe_key_data = user_key.ssh_key_data\
88 safe_key_data = user_key.ssh_key_data\
89 .strip()\
89 .strip()\
90 .replace('\n', ' ')\
90 .replace('\n', ' ') \
91 .replace('\t', ' ') \
91 .replace('\r', ' ')
92 .replace('\r', ' ')
92
93
93 line = line_tmpl.format(
94 line = line_tmpl.format(
94 ssh_opts=ssh_opts or SSH_OPTS,
95 ssh_opts=ssh_opts or SSH_OPTS,
95 wrapper_command=ssh_wrapper_cmd,
96 wrapper_command=ssh_wrapper_cmd,
96 ini_path=ini_path,
97 ini_path=ini_path,
97 user_id=user_id,
98 user_id=user_id,
98 user=username,
99 user=username,
99 user_key_id=user_key.ssh_key_id,
100 user_key_id=user_key.ssh_key_id,
100 key=safe_key_data)
101 key=safe_key_data)
101
102
102 keys_file.write(line)
103 keys_file.write(line)
103 log.debug('addkey: Key added for user: `%s`', username)
104 log.debug('addkey: Key added for user: `%s`', username)
104 keys_file.close()
105 keys_file.close()
105
106
106 # Explicitly setting read-only permissions to authorized_keys
107 # Explicitly setting read-only permissions to authorized_keys
107 os.chmod(tmp_authorized_keys, stat.S_IRUSR | stat.S_IWUSR)
108 os.chmod(tmp_authorized_keys, stat.S_IRUSR | stat.S_IWUSR)
108 # Rename is atomic operation
109 # Rename is atomic operation
109 os.rename(tmp_authorized_keys, authorized_keys_file_path)
110 os.rename(tmp_authorized_keys, authorized_keys_file_path)
110
111
111
112
112 def generate_ssh_authorized_keys_file(registry):
113 def generate_ssh_authorized_keys_file(registry):
113 log.info('Generating new authorized key file')
114 log.info('Generating new authorized key file')
114
115
115 authorized_keys_file_path = registry.settings.get(
116 authorized_keys_file_path = registry.settings.get(
116 config_keys.authorized_keys_file_path)
117 config_keys.authorized_keys_file_path)
117
118
118 ssh_wrapper_cmd = registry.settings.get(
119 ssh_wrapper_cmd = registry.settings.get(
119 config_keys.wrapper_cmd)
120 config_keys.wrapper_cmd)
120 allow_shell = registry.settings.get(
121 allow_shell = registry.settings.get(
121 config_keys.wrapper_allow_shell)
122 config_keys.wrapper_allow_shell)
122 ssh_opts = registry.settings.get(
123 ssh_opts = registry.settings.get(
123 config_keys.authorized_keys_line_ssh_opts)
124 config_keys.authorized_keys_line_ssh_opts)
124 debug = registry.settings.get(
125 debug = registry.settings.get(
125 config_keys.enable_debug_logging)
126 config_keys.enable_debug_logging)
126
127
127 _generate_ssh_authorized_keys_file(
128 _generate_ssh_authorized_keys_file(
128 authorized_keys_file_path, ssh_wrapper_cmd, allow_shell, ssh_opts,
129 authorized_keys_file_path, ssh_wrapper_cmd, allow_shell, ssh_opts,
129 debug)
130 debug)
130
131
131 return 0
132 return 0
General Comments 0
You need to be logged in to leave comments. Login now