##// END OF EJS Templates
Fixed #161 form saves the create repository permission....
marcink -
r1266:a1bcfe58 beta
parent child Browse files
Show More
@@ -105,16 +105,42 b' def make_map(config):'
105 controller='admin/repos_groups', path_prefix='/_admin')
105 controller='admin/repos_groups', path_prefix='/_admin')
106
106
107 #ADMIN USER REST ROUTES
107 #ADMIN USER REST ROUTES
108 rmap.resource('user', 'users', controller='admin/users',
108 with rmap.submapper(path_prefix='/_admin', controller='admin/users') as m:
109 path_prefix='/_admin')
109 m.connect("users", "/users",
110 action="create", conditions=dict(method=["POST"]))
111 m.connect("users", "/users",
112 action="index", conditions=dict(method=["GET"]))
113 m.connect("formatted_users", "/users.{format}",
114 action="index", conditions=dict(method=["GET"]))
115 m.connect("new_user", "/users/new",
116 action="new", conditions=dict(method=["GET"]))
117 m.connect("formatted_new_user", "/users/new.{format}",
118 action="new", conditions=dict(method=["GET"]))
119 m.connect("update_user", "/users/{id}",
120 action="update", conditions=dict(method=["PUT"]))
121 m.connect("delete_user", "/users/{id}",
122 action="delete", conditions=dict(method=["DELETE"]))
123 m.connect("edit_user", "/users/{id}/edit",
124 action="edit", conditions=dict(method=["GET"]))
125 m.connect("formatted_edit_user",
126 "/users/{id}.{format}/edit",
127 action="edit", conditions=dict(method=["GET"]))
128 m.connect("user", "/users/{id}",
129 action="show", conditions=dict(method=["GET"]))
130 m.connect("formatted_user", "/users/{id}.{format}",
131 action="show", conditions=dict(method=["GET"]))
132
133 #EXTRAS USER ROUTES
134 m.connect("user_perm", "/users_perm/{id}",
135 action="update_perm", conditions=dict(method=["PUT"]))
110
136
111 #ADMIN USERS REST ROUTES
137 #ADMIN USERS REST ROUTES
112 rmap.resource('users_group', 'users_groups',
138 rmap.resource('users_group', 'users_groups',
113 controller='admin/users_groups', path_prefix='/_admin')
139 controller='admin/users_groups', path_prefix='/_admin')
114
140
115 #ADMIN GROUP REST ROUTES
141 #ADMIN GROUP REST ROUTES
116 rmap.resource('group', 'groups', controller='admin/groups',
142 rmap.resource('group', 'groups',
117 path_prefix='/_admin')
143 controller='admin/groups', path_prefix='/_admin')
118
144
119 #ADMIN PERMISSIONS REST ROUTES
145 #ADMIN PERMISSIONS REST ROUTES
120 rmap.resource('permission', 'permissions',
146 rmap.resource('permission', 'permissions',
@@ -124,6 +150,7 b' def make_map(config):'
124 rmap.connect('ldap_settings', '/_admin/ldap',
150 rmap.connect('ldap_settings', '/_admin/ldap',
125 controller='admin/ldap_settings', action='ldap_settings',
151 controller='admin/ldap_settings', action='ldap_settings',
126 conditions=dict(method=["POST"]))
152 conditions=dict(method=["POST"]))
153
127 rmap.connect('ldap_home', '/_admin/ldap',
154 rmap.connect('ldap_home', '/_admin/ldap',
128 controller='admin/ldap_settings')
155 controller='admin/ldap_settings')
129
156
@@ -33,7 +33,6 b' from rhodecode.lib.auth_ldap import Ldap'
33 from rhodecode.lib.base import BaseController, render
33 from rhodecode.lib.base import BaseController, render
34 from rhodecode.model.forms import LdapSettingsForm, DefaultPermissionsForm
34 from rhodecode.model.forms import LdapSettingsForm, DefaultPermissionsForm
35 from rhodecode.model.permission import PermissionModel
35 from rhodecode.model.permission import PermissionModel
36 from rhodecode.model.settings import SettingsModel
37 from rhodecode.model.user import UserModel
36 from rhodecode.model.user import UserModel
38 import formencode
37 import formencode
39 import logging
38 import logging
@@ -38,7 +38,7 b' from rhodecode.lib import helpers as h'
38 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
38 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
39 from rhodecode.lib.base import BaseController, render
39 from rhodecode.lib.base import BaseController, render
40
40
41 from rhodecode.model.db import User
41 from rhodecode.model.db import User, RepoToPerm, UserToPerm, Permission
42 from rhodecode.model.forms import UserForm
42 from rhodecode.model.forms import UserForm
43 from rhodecode.model.user import UserModel
43 from rhodecode.model.user import UserModel
44
44
@@ -101,7 +101,7 b' class UsersController(BaseController):'
101 # Forms posted to this method should contain a hidden field:
101 # Forms posted to this method should contain a hidden field:
102 # <input type="hidden" name="_method" value="PUT" />
102 # <input type="hidden" name="_method" value="PUT" />
103 # Or using helpers:
103 # Or using helpers:
104 # h.form(url('user', id=ID),
104 # h.form(url('update_user', id=ID),
105 # method='put')
105 # method='put')
106 # url('user', id=ID)
106 # url('user', id=ID)
107 user_model = UserModel()
107 user_model = UserModel()
@@ -113,13 +113,16 b' class UsersController(BaseController):'
113 try:
113 try:
114 form_result = _form.to_python(dict(request.POST))
114 form_result = _form.to_python(dict(request.POST))
115 user_model.update(id, form_result)
115 user_model.update(id, form_result)
116 h.flash(_('User updated succesfully'), category='success')
116 h.flash(_('User updated successfully'), category='success')
117
117
118 except formencode.Invalid, errors:
118 except formencode.Invalid, errors:
119 e = errors.error_dict or {}
120 perm = Permission.get_by_key('hg.create.repository')
121 e.update({'create_repo_perm': UserToPerm.has_perm(id, perm)})
119 return htmlfill.render(
122 return htmlfill.render(
120 render('admin/users/user_edit.html'),
123 render('admin/users/user_edit.html'),
121 defaults=errors.value,
124 defaults=errors.value,
122 errors=errors.error_dict or {},
125 errors=e,
123 prefix_error=False,
126 prefix_error=False,
124 encoding="UTF-8")
127 encoding="UTF-8")
125 except Exception:
128 except Exception:
@@ -134,7 +137,7 b' class UsersController(BaseController):'
134 # Forms posted to this method should contain a hidden field:
137 # Forms posted to this method should contain a hidden field:
135 # <input type="hidden" name="_method" value="DELETE" />
138 # <input type="hidden" name="_method" value="DELETE" />
136 # Or using helpers:
139 # Or using helpers:
137 # h.form(url('user', id=ID),
140 # h.form(url('delete_user', id=ID),
138 # method='delete')
141 # method='delete')
139 # url('user', id=ID)
142 # url('user', id=ID)
140 user_model = UserModel()
143 user_model = UserModel()
@@ -167,6 +170,8 b' class UsersController(BaseController):'
167 .permissions['global']
170 .permissions['global']
168
171
169 defaults = c.user.get_dict()
172 defaults = c.user.get_dict()
173 perm = Permission.get_by_key('hg.create.repository')
174 defaults.update({'create_repo_perm': UserToPerm.has_perm(id, perm)})
170
175
171 return htmlfill.render(
176 return htmlfill.render(
172 render('admin/users/user_edit.html'),
177 render('admin/users/user_edit.html'),
@@ -174,3 +179,29 b' class UsersController(BaseController):'
174 encoding="UTF-8",
179 encoding="UTF-8",
175 force_defaults=False
180 force_defaults=False
176 )
181 )
182
183 def update_perm(self, id):
184 """PUT /users_perm/id: Update an existing item"""
185 # url('user_perm', id=ID, method='put')
186
187 grant_perm = request.POST.get('create_repo_perm', False)
188
189 if grant_perm:
190 perm = Permission.get_by_key('hg.create.none')
191 UserToPerm.revoke_perm(id, perm)
192
193 perm = Permission.get_by_key('hg.create.repository')
194 UserToPerm.grant_perm(id, perm)
195 h.flash(_("Granted 'repository create' permission to user"),
196 category='success')
197
198 else:
199 perm = Permission.get_by_key('hg.create.repository')
200 UserToPerm.revoke_perm(id, perm)
201
202 perm = Permission.get_by_key('hg.create.none')
203 UserToPerm.grant_perm(id, perm)
204 h.flash(_("Revoked 'repository create' permission to user"),
205 category='success')
206
207 return redirect(url('edit_user', id=id))
@@ -36,13 +36,14 b' from rhodecode.model import meta'
36 from rhodecode.lib.auth import get_crypt_password, generate_api_key
36 from rhodecode.lib.auth import get_crypt_password, generate_api_key
37 from rhodecode.lib.utils import ask_ok
37 from rhodecode.lib.utils import ask_ok
38 from rhodecode.model import init_model
38 from rhodecode.model import init_model
39 from rhodecode.model.db import User, Permission, RhodeCodeUi, RhodeCodeSettings, \
39 from rhodecode.model.db import User, Permission, RhodeCodeUi, \
40 UserToPerm, DbMigrateVersion
40 RhodeCodeSettings, UserToPerm, DbMigrateVersion
41
41
42 from sqlalchemy.engine import create_engine
42 from sqlalchemy.engine import create_engine
43
43
44 log = logging.getLogger(__name__)
44 log = logging.getLogger(__name__)
45
45
46
46 class DbManage(object):
47 class DbManage(object):
47 def __init__(self, log_sql, dbconf, root, tests=False):
48 def __init__(self, log_sql, dbconf, root, tests=False):
48 self.dbname = dbconf.split('/')[-1]
49 self.dbname = dbconf.split('/')[-1]
@@ -76,8 +77,6 b' class DbManage(object):'
76 meta.Base.metadata.create_all(checkfirst=checkfirst)
77 meta.Base.metadata.create_all(checkfirst=checkfirst)
77 log.info('Created tables for %s', self.dbname)
78 log.info('Created tables for %s', self.dbname)
78
79
79
80
81 def set_db_version(self):
80 def set_db_version(self):
82 try:
81 try:
83 ver = DbMigrateVersion()
82 ver = DbMigrateVersion()
@@ -91,7 +90,6 b' class DbManage(object):'
91 raise
90 raise
92 log.info('db version set to: %s', __dbversion__)
91 log.info('db version set to: %s', __dbversion__)
93
92
94
95 def upgrade(self):
93 def upgrade(self):
96 """Upgrades given database schema to given revision following
94 """Upgrades given database schema to given revision following
97 all needed steps, to perform the upgrade
95 all needed steps, to perform the upgrade
@@ -170,8 +168,6 b' class DbManage(object):'
170 print ('performing upgrade step %s' % step)
168 print ('performing upgrade step %s' % step)
171 callable = getattr(UpgradeSteps(self), 'step_%s' % step)()
169 callable = getattr(UpgradeSteps(self), 'step_%s' % step)()
172
170
173
174
175 def fix_repo_paths(self):
171 def fix_repo_paths(self):
176 """Fixes a old rhodecode version path into new one without a '*'
172 """Fixes a old rhodecode version path into new one without a '*'
177 """
173 """
@@ -225,9 +221,9 b' class DbManage(object):'
225 if not self.tests:
221 if not self.tests:
226 import getpass
222 import getpass
227
223
228
229 def get_password():
224 def get_password():
230 password = getpass.getpass('Specify admin password (min 6 chars):')
225 password = getpass.getpass('Specify admin password '
226 '(min 6 chars):')
231 confirm = getpass.getpass('Confirm password:')
227 confirm = getpass.getpass('Confirm password:')
232
228
233 if password != confirm:
229 if password != confirm:
@@ -252,9 +248,12 b' class DbManage(object):'
252 self.create_user(username, password, email, True)
248 self.create_user(username, password, email, True)
253 else:
249 else:
254 log.info('creating admin and regular test users')
250 log.info('creating admin and regular test users')
255 self.create_user('test_admin', 'test12', 'test_admin@mail.com', True)
251 self.create_user('test_admin', 'test12',
256 self.create_user('test_regular', 'test12', 'test_regular@mail.com', False)
252 'test_admin@mail.com', True)
257 self.create_user('test_regular2', 'test12', 'test_regular2@mail.com', False)
253 self.create_user('test_regular', 'test12',
254 'test_regular@mail.com', False)
255 self.create_user('test_regular2', 'test12',
256 'test_regular2@mail.com', False)
258
257
259 def create_ui_settings(self):
258 def create_ui_settings(self):
260 """Creates ui settings, fills out hooks
259 """Creates ui settings, fills out hooks
@@ -308,7 +307,6 b' class DbManage(object):'
308 self.sa.rollback()
307 self.sa.rollback()
309 raise
308 raise
310
309
311
312 def create_ldap_options(self):
310 def create_ldap_options(self):
313 """Creates ldap settings"""
311 """Creates ldap settings"""
314
312
@@ -321,7 +319,6 b' class DbManage(object):'
321 ('ldap_attr_login', ''), ('ldap_attr_firstname', ''),
319 ('ldap_attr_login', ''), ('ldap_attr_firstname', ''),
322 ('ldap_attr_lastname', ''), ('ldap_attr_email', '')]:
320 ('ldap_attr_lastname', ''), ('ldap_attr_email', '')]:
323
321
324
325 setting = RhodeCodeSettings(k, v)
322 setting = RhodeCodeSettings(k, v)
326 self.sa.add(setting)
323 self.sa.add(setting)
327 self.sa.commit()
324 self.sa.commit()
@@ -353,14 +350,12 b' class DbManage(object):'
353 log.error('No write permission to given path: %s [%s/3]',
350 log.error('No write permission to given path: %s [%s/3]',
354 path, retries)
351 path, retries)
355
352
356
357 if retries == 0:
353 if retries == 0:
358 sys.exit()
354 sys.exit()
359 if path_ok is False:
355 if path_ok is False:
360 retries -= 1
356 retries -= 1
361 return self.config_prompt(test_repo_path, retries)
357 return self.config_prompt(test_repo_path, retries)
362
358
363
364 return path
359 return path
365
360
366 def create_settings(self, path):
361 def create_settings(self, path):
@@ -393,12 +388,10 b' class DbManage(object):'
393 paths.ui_key = '/'
388 paths.ui_key = '/'
394 paths.ui_value = path
389 paths.ui_value = path
395
390
396
397 hgsettings1 = RhodeCodeSettings('realm', 'RhodeCode authentication')
391 hgsettings1 = RhodeCodeSettings('realm', 'RhodeCode authentication')
398 hgsettings2 = RhodeCodeSettings('title', 'RhodeCode')
392 hgsettings2 = RhodeCodeSettings('title', 'RhodeCode')
399 hgsettings3 = RhodeCodeSettings('ga_code', '')
393 hgsettings3 = RhodeCodeSettings('ga_code', '')
400
394
401
402 try:
395 try:
403 self.sa.add(web1)
396 self.sa.add(web1)
404 self.sa.add(web2)
397 self.sa.add(web2)
@@ -467,8 +460,13 b' class DbManage(object):'
467 ('hg.create.repository', 'Repository create'),
460 ('hg.create.repository', 'Repository create'),
468 ('hg.create.none', 'Repository creation disabled'),
461 ('hg.create.none', 'Repository creation disabled'),
469 ('hg.register.none', 'Register disabled'),
462 ('hg.register.none', 'Register disabled'),
470 ('hg.register.manual_activate', 'Register new user with RhodeCode without manual activation'),
463 ('hg.register.manual_activate', 'Register new user with '
471 ('hg.register.auto_activate', 'Register new user with RhodeCode without auto activation'),
464 'RhodeCode without manual'
465 'activation'),
466
467 ('hg.register.auto_activate', 'Register new user with '
468 'RhodeCode without auto '
469 'activation'),
472 ]
470 ]
473
471
474 for p in perms:
472 for p in perms:
@@ -33,7 +33,9 b' from sqlalchemy.exc import DatabaseError'
33 from sqlalchemy.orm import relationship, backref
33 from sqlalchemy.orm import relationship, backref
34 from sqlalchemy.orm.interfaces import MapperExtension
34 from sqlalchemy.orm.interfaces import MapperExtension
35
35
36 from rhodecode.lib import str2bool
36 from rhodecode.model.meta import Base, Session
37 from rhodecode.model.meta import Base, Session
38 from rhodecode.model.caching_query import FromCache
37
39
38 log = logging.getLogger(__name__)
40 log = logging.getLogger(__name__)
39
41
@@ -61,6 +63,35 b' class RhodeCodeSettings(Base):'
61 return "<%s('%s:%s')>" % (self.__class__.__name__,
63 return "<%s('%s:%s')>" % (self.__class__.__name__,
62 self.app_settings_name, self.app_settings_value)
64 self.app_settings_name, self.app_settings_value)
63
65
66
67 @classmethod
68 def get_app_settings(cls, cache=False):
69
70 ret = Session.query(cls)
71
72 if cache:
73 ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
74
75 if not ret:
76 raise Exception('Could not get application settings !')
77 settings = {}
78 for each in ret:
79 settings['rhodecode_' + each.app_settings_name] = \
80 each.app_settings_value
81
82 return settings
83
84 @classmethod
85 def get_ldap_settings(cls, cache=False):
86 ret = Session.query(cls)\
87 .filter(cls.app_settings_name.startswith('ldap_'))\
88 .all()
89 fd = {}
90 for row in ret:
91 fd.update({row.app_settings_name:str2bool(row.app_settings_value)})
92 return fd
93
94
64 class RhodeCodeUi(Base):
95 class RhodeCodeUi(Base):
65 __tablename__ = 'rhodecode_ui'
96 __tablename__ = 'rhodecode_ui'
66 __table_args__ = {'useexisting':True}
97 __table_args__ = {'useexisting':True}
@@ -285,6 +316,10 b' class Permission(Base):'
285 return "<%s('%s:%s')>" % (self.__class__.__name__,
316 return "<%s('%s:%s')>" % (self.__class__.__name__,
286 self.permission_id, self.permission_name)
317 self.permission_id, self.permission_name)
287
318
319 @classmethod
320 def get_by_key(cls, key):
321 return Session.query(cls).filter(cls.permission_name == key).scalar()
322
288 class RepoToPerm(Base):
323 class RepoToPerm(Base):
289 __tablename__ = 'repo_to_perm'
324 __tablename__ = 'repo_to_perm'
290 __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'useexisting':True})
325 __table_args__ = (UniqueConstraint('user_id', 'repository_id'), {'useexisting':True})
@@ -307,6 +342,40 b' class UserToPerm(Base):'
307 user = relationship('User')
342 user = relationship('User')
308 permission = relationship('Permission')
343 permission = relationship('Permission')
309
344
345 @classmethod
346 def has_perm(cls, user_id, perm):
347 if not isinstance(perm, Permission):
348 raise Exception('perm needs to be an instance of Permission class')
349
350 return Session.query(cls).filter(cls.user_id == user_id)\
351 .filter(cls.permission == perm).scalar() is not None
352
353 @classmethod
354 def grant_perm(cls, user_id, perm):
355 if not isinstance(perm, Permission):
356 raise Exception('perm needs to be an instance of Permission class')
357
358 new = cls()
359 new.user_id = user_id
360 new.permission = perm
361 try:
362 Session.add(new)
363 Session.commit()
364 except:
365 Session.rollback()
366
367
368 @classmethod
369 def revoke_perm(cls, user_id, perm):
370 if not isinstance(perm, Permission):
371 raise Exception('perm needs to be an instance of Permission class')
372
373 try:
374 Session.query(cls).filter(cls.user_id == user_id)\
375 .filter(cls.permission == perm).delete()
376 Session.commit()
377 except:
378 Session.rollback()
310
379
311 class UsersGroupToPerm(Base):
380 class UsersGroupToPerm(Base):
312 __tablename__ = 'users_group_to_perm'
381 __tablename__ = 'users_group_to_perm'
@@ -24,7 +24,7 b''
24 ${self.breadcrumbs()}
24 ${self.breadcrumbs()}
25 </div>
25 </div>
26 <!-- end box / title -->
26 <!-- end box / title -->
27 ${h.form(url('user', id=c.user.user_id),method='put')}
27 ${h.form(url('update_user', id=c.user.user_id),method='put')}
28 <div class="form">
28 <div class="form">
29 <div class="field">
29 <div class="field">
30 <div class="gravatar_box">
30 <div class="gravatar_box">
@@ -126,7 +126,7 b''
126 <div class="title">
126 <div class="title">
127 <h5>${_('Permissions')}</h5>
127 <h5>${_('Permissions')}</h5>
128 </div>
128 </div>
129 ${h.form(url('user', id=c.user.user_id),method='put')}
129 ${h.form(url('user_perm', id=c.user.user_id),method='put')}
130 <div class="form">
130 <div class="form">
131 <!-- fields -->
131 <!-- fields -->
132 <div class="fields">
132 <div class="fields">
@@ -135,7 +135,7 b''
135 <label for="">${_('Create repositories')}:</label>
135 <label for="">${_('Create repositories')}:</label>
136 </div>
136 </div>
137 <div class="checkboxes">
137 <div class="checkboxes">
138 ${h.checkbox('create',value=True)}
138 ${h.checkbox('create_repo_perm',value=True)}
139 </div>
139 </div>
140 </div>
140 </div>
141 <div class="buttons">
141 <div class="buttons">
@@ -51,7 +51,7 b''
51 <td>${h.bool2icon(user.admin)}</td>
51 <td>${h.bool2icon(user.admin)}</td>
52 <td>${h.bool2icon(bool(user.ldap_dn))}</td>
52 <td>${h.bool2icon(bool(user.ldap_dn))}</td>
53 <td>
53 <td>
54 ${h.form(url('user', id=user.user_id),method='delete')}
54 ${h.form(url('delete_user', id=user.user_id),method='delete')}
55 ${h.submit('remove_','delete',id="remove_user_%s" % user.user_id,
55 ${h.submit('remove_','delete',id="remove_user_%s" % user.user_id,
56 class_="delete_icon action_button",onclick="return confirm('Confirm to delete this user');")}
56 class_="delete_icon action_button",onclick="return confirm('Confirm to delete this user');")}
57 ${h.end_form()}
57 ${h.end_form()}
@@ -247,7 +247,7 b''
247 <div class="title">
247 <div class="title">
248 <h5>${_('Permissions')}</h5>
248 <h5>${_('Permissions')}</h5>
249 </div>
249 </div>
250 ${h.form(url('user', id=''),method='put')}
250 ${h.form(url('xxx', id=''),method='put')}
251 <div class="form">
251 <div class="form">
252 <!-- fields -->
252 <!-- fields -->
253 <div class="fields">
253 <div class="fields">
General Comments 0
You need to be logged in to leave comments. Login now