##// END OF EJS Templates
first permissions commit: added permission managment on repository edit. Changed db rmissions, validators.
marcink -
r296:29370bb7 default
parent child Browse files
Show More
@@ -107,10 +107,11 b' class ReposController(BaseController):'
107 form_result = _form.to_python(dict(request.POST))
107 form_result = _form.to_python(dict(request.POST))
108 repo_model.update(id, form_result)
108 repo_model.update(id, form_result)
109 invalidate_cache('cached_repo_list')
109 invalidate_cache('cached_repo_list')
110 h.flash(_('Repository updated succesfully'), category='success')
110 h.flash(_('Repository %s updated succesfully' % id), category='success')
111
111
112 except formencode.Invalid as errors:
112 except formencode.Invalid as errors:
113 c.repo_info = repo_model.get(id)
113 c.repo_info = repo_model.get(id)
114 errors.value.update({'user':c.repo_info.user.username})
114 c.form_errors = errors.error_dict
115 c.form_errors = errors.error_dict
115 return htmlfill.render(
116 return htmlfill.render(
116 render('admin/repos/repo_edit.html'),
117 render('admin/repos/repo_edit.html'),
@@ -166,7 +167,12 b' class ReposController(BaseController):'
166
167
167 return redirect(url('repos'))
168 return redirect(url('repos'))
168 defaults = c.repo_info.__dict__
169 defaults = c.repo_info.__dict__
169 defaults.update({'user':c.repo_info.user.username})
170 defaults.update({'user':c.repo_info.user.username})
171
172 for p in c.repo_info.repo2perm:
173 defaults.update({'perm_%s' % p.user.username:
174 p.permission.permission_name})
175
170 return htmlfill.render(
176 return htmlfill.render(
171 render('admin/repos/repo_edit.html'),
177 render('admin/repos/repo_edit.html'),
172 defaults=defaults,
178 defaults=defaults,
@@ -80,12 +80,25 b' class DbManage(object):'
80 self.create_user(username, password, True)
80 self.create_user(username, password, True)
81
81
82 def create_user(self, username, password, admin=False):
82 def create_user(self, username, password, admin=False):
83
84 log.info('creating default user')
85 #create default user for handling default permissions.
86 def_user = User()
87 def_user.username = 'default'
88 def_user.password = 'default'
89 def_user.name = 'default'
90 def_user.lastname = 'default'
91 def_user.email = 'default@default'
92 def_user.admin = False
93 def_user.active = False
94
95 self.sa.add(def_user)
96
83 log.info('creating administrator user %s', username)
97 log.info('creating administrator user %s', username)
84
85 new_user = User()
98 new_user = User()
86 new_user.username = username
99 new_user.username = username
87 new_user.password = get_crypt_password(password)
100 new_user.password = get_crypt_password(password)
88 new_user.name = 'Admin'
101 new_user.name = 'Hg'
89 new_user.lastname = 'Admin'
102 new_user.lastname = 'Admin'
90 new_user.email = 'admin@localhost'
103 new_user.email = 'admin@localhost'
91 new_user.admin = admin
104 new_user.admin = admin
@@ -100,8 +113,11 b' class DbManage(object):'
100
113
101 def create_permissions(self):
114 def create_permissions(self):
102 #module.(access|create|change|delete)_[name]
115 #module.(access|create|change|delete)_[name]
103 perms = [('admin.access_home', 'Access to admin user view'),
116 #module.(read|write|owner)
104
117 perms = [('repository.none', 'Repository no access'),
118 ('repository.read', 'Repository read access'),
119 ('repository.write', 'Repository write access'),
120 ('repository.admin', 'Repository admin access'),
105 ]
121 ]
106
122
107 for p in perms:
123 for p in perms:
@@ -28,28 +28,44 b' class User(Base):'
28 class UserLog(Base):
28 class UserLog(Base):
29 __tablename__ = 'user_logs'
29 __tablename__ = 'user_logs'
30 __table_args__ = {'useexisting':True}
30 __table_args__ = {'useexisting':True}
31 user_log_id = Column("user_log_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=1)
31 user_log_id = Column("user_log_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
32 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
32 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
33 repository = Column("repository", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
33 user_ip = Column("user_ip", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
34 repository = Column("repository", TEXT(length=None, convert_unicode=False, assert_unicode=None), ForeignKey(u'repositories.repo_name'), nullable=False, unique=None, default=None)
34 action = Column("action", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
35 action = Column("action", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
35 action_date = Column("action_date", DATETIME(timezone=False), nullable=True, unique=None, default=None)
36 action_date = Column("action_date", DATETIME(timezone=False), nullable=True, unique=None, default=None)
36
37
37 user = relation('User')
38 user = relation('User')
38
39
39 class Repository(Base):
40 class Repository(Base):
40 __tablename__ = 'repositories'
41 __tablename__ = 'repositories'
42 __table_args__ = {'useexisting':True}
41 repo_name = Column("repo_name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None, primary_key=True)
43 repo_name = Column("repo_name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None, primary_key=True)
42 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=False, default=None)
44 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=False, default=None)
43 private = Column("private", BOOLEAN(), nullable=True, unique=None, default=None)
45 private = Column("private", BOOLEAN(), nullable=True, unique=None, default=None)
44 description = Column("description", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
46 description = Column("description", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
47
45 user = relation('User')
48 user = relation('User')
49 repo2perm = relation('Repo2Perm', cascade='all')
46
50
47 class Permission(Base):
51 class Permission(Base):
48 __tablename__ = 'permissions'
52 __tablename__ = 'permissions'
49 __table_args__ = {'useexisting':True}
53 __table_args__ = {'useexisting':True}
50 permission_id = Column("id", INTEGER(), nullable=False, unique=True, default=None, primary_key=1)
54 permission_id = Column("permission_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
51 permission_name = Column("permission_name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
55 permission_name = Column("permission_name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
52 permission_longname = Column("permission_longname", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
56 permission_longname = Column("permission_longname", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
53
57
54 def __repr__(self):
58 def __repr__(self):
55 return "<Permission('%s:%s')>" % (self.permission_id, self.permission_name)
59 return "<Permission('%s:%s')>" % (self.permission_id, self.permission_name)
60
61 class Repo2Perm(Base):
62 __tablename__ = 'repo_to_perm'
63 __table_args__ = (UniqueConstraint('user_id', 'permission_id', 'repository'), {'useexisting':True})
64 repo2perm_id = Column("repo2perm_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
65 user_id = Column("user_id", INTEGER(), ForeignKey(u'users.user_id'), nullable=False, unique=None, default=None)
66 permission_id = Column("permission_id", INTEGER(), ForeignKey(u'permissions.permission_id'), nullable=False, unique=None, default=None)
67 repository = Column("repository", TEXT(length=None, convert_unicode=False, assert_unicode=None), ForeignKey(u'repositories.repo_name'), nullable=False, unique=None, default=None)
68
69 user = relation('User')
70 permission = relation('Permission')
71
@@ -55,7 +55,8 b' class ValidAuthToken(formencode.validato'
55 class ValidUsername(formencode.validators.FancyValidator):
55 class ValidUsername(formencode.validators.FancyValidator):
56
56
57 def validate_python(self, value, state):
57 def validate_python(self, value, state):
58 pass
58 if value in ['default', 'new_user']:
59 raise formencode.Invalid(_('Invalid username'), value, state)
59
60
60 class ValidPassword(formencode.validators.FancyValidator):
61 class ValidPassword(formencode.validators.FancyValidator):
61
62
@@ -145,6 +146,39 b' def ValidRepoName(edit=False):'
145
146
146 return slug
147 return slug
147 return _ValidRepoName
148 return _ValidRepoName
149
150 class ValidPerms(formencode.validators.FancyValidator):
151 messages = {'perm_new_user_name':_('This username is not valid')}
152
153 def to_python(self, value, state):
154 perms_update = []
155 perms_new = []
156 #build a list of permission to update and new permission to create
157 for k, v in value.items():
158 print k, v
159 if k.startswith('perm_'):
160 if k.startswith('perm_new_user'):
161 new_perm = value.get('perm_new_user', False)
162 new_user = value.get('perm_new_user_name', False)
163 if new_user and new_perm:
164 if (new_user, new_perm) not in perms_new:
165 perms_new.append((new_user, new_perm))
166 else:
167 perms_update.append((k[5:], v))
168 #clear from form list
169 #del value[k]
170 value['perms_updates'] = perms_update
171 value['perms_new'] = perms_new
172 sa = meta.Session
173 for k, v in perms_new:
174 try:
175 self.user_db = sa.query(User).filter(User.username == k).one()
176 except Exception:
177 msg = self.message('perm_new_user_name',
178 state=State_obj)
179 raise formencode.Invalid(msg, value, state, error_dict={'perm_new_user_name':msg})
180 return value
181
148 #===============================================================================
182 #===============================================================================
149 # FORMS
183 # FORMS
150 #===============================================================================
184 #===============================================================================
@@ -192,7 +226,7 b' def UserForm(edit=False):'
192 def RepoForm(edit=False):
226 def RepoForm(edit=False):
193 class _RepoForm(formencode.Schema):
227 class _RepoForm(formencode.Schema):
194 allow_extra_fields = True
228 allow_extra_fields = True
195 filter_extra_fields = True
229 filter_extra_fields = False
196 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit))
230 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit))
197 description = UnicodeString(strip=True, min=3, not_empty=True)
231 description = UnicodeString(strip=True, min=3, not_empty=True)
198 private = StringBoolean(if_missing=False)
232 private = StringBoolean(if_missing=False)
@@ -200,4 +234,5 b' def RepoForm(edit=False):'
200 if edit:
234 if edit:
201 user = All(Int(not_empty=True), ValidRepoUser)
235 user = All(Int(not_empty=True), ValidRepoUser)
202
236
237 chained_validators = [ValidPerms]
203 return _RepoForm
238 return _RepoForm
@@ -23,12 +23,13 b' model for handling repositories actions'
23 @author: marcink
23 @author: marcink
24 """
24 """
25 from pylons_app.model.meta import Session
25 from pylons_app.model.meta import Session
26 from pylons_app.model.db import Repository
26 from pylons_app.model.db import Repository, Repo2Perm, User, Permission
27 import shutil
27 import shutil
28 import os
28 import os
29 from datetime import datetime
29 from datetime import datetime
30 from pylons_app.lib.utils import check_repo
30 from pylons_app.lib.utils import check_repo
31 from pylons import app_globals as g
31 from pylons import app_globals as g
32 import traceback
32 import logging
33 import logging
33 log = logging.getLogger(__name__)
34 log = logging.getLogger(__name__)
34
35
@@ -41,36 +42,73 b' class RepoModel(object):'
41 return self.sa.query(Repository).get(id)
42 return self.sa.query(Repository).get(id)
42
43
43
44
44 def update(self, id, form_data):
45 def update(self, repo_id, form_data):
45 try:
46 try:
46 if id != form_data['repo_name']:
47 if repo_id != form_data['repo_name']:
47 self.__rename_repo(id, form_data['repo_name'])
48 self.__rename_repo(repo_id, form_data['repo_name'])
48 cur_repo = self.sa.query(Repository).get(id)
49 cur_repo = self.sa.query(Repository).get(repo_id)
49 for k, v in form_data.items():
50 for k, v in form_data.items():
50 if k == 'user':
51 if k == 'user':
51 cur_repo.user_id = v
52 cur_repo.user_id = v
52 else:
53 else:
53 setattr(cur_repo, k, v)
54 setattr(cur_repo, k, v)
55
56 #update permissions
57 for username, perm in form_data['perms_updates']:
58 r2p = self.sa.query(Repo2Perm)\
59 .filter(Repo2Perm.user == self.sa.query(User)\
60 .filter(User.username == username).one())\
61 .filter(Repo2Perm.repository == repo_id).one()
54
62
63 r2p.permission_id = self.sa.query(Permission).filter(
64 Permission.permission_name ==
65 perm).one().permission_id
66 self.sa.add(r2p)
67
68 for username, perm in form_data['perms_new']:
69 r2p = Repo2Perm()
70 r2p.repository = repo_id
71 r2p.user = self.sa.query(User)\
72 .filter(User.username == username).one()
73
74 r2p.permission_id = self.sa.query(Permission).filter(
75 Permission.permission_name ==
76 perm).one().permission_id
77 self.sa.add(r2p)
78
55 self.sa.add(cur_repo)
79 self.sa.add(cur_repo)
56 self.sa.commit()
80 self.sa.commit()
57 except Exception as e:
81 except:
58 log.error(e)
82 log.error(traceback.format_exc())
59 self.sa.rollback()
83 self.sa.rollback()
60 raise
84 raise
61
85
62 def create(self, form_data, cur_user):
86 def create(self, form_data, cur_user, just_db=False):
63 try:
87 try:
88 repo_name = form_data['repo_name']
64 new_repo = Repository()
89 new_repo = Repository()
65 for k, v in form_data.items():
90 for k, v in form_data.items():
66 setattr(new_repo, k, v)
91 setattr(new_repo, k, v)
67
92
68 new_repo.user_id = cur_user.user_id
93 new_repo.user_id = cur_user.user_id
69 self.sa.add(new_repo)
94 self.sa.add(new_repo)
95
96 #create default permission
97 repo2perm = Repo2Perm()
98 repo2perm.permission_id = self.sa.query(Permission)\
99 .filter(Permission.permission_name == 'repository.read')\
100 .one().permission_id
101
102 repo2perm.repository = repo_name
103 repo2perm.user_id = self.sa.query(User)\
104 .filter(User.username == 'default').one().user_id
105
106 self.sa.add(repo2perm)
70 self.sa.commit()
107 self.sa.commit()
71 self.__create_repo(form_data['repo_name'])
108 if not just_db:
72 except Exception as e:
109 self.__create_repo(repo_name)
73 log.error(e)
110 except:
111 log.error(traceback.format_exc())
74 self.sa.rollback()
112 self.sa.rollback()
75 raise
113 raise
76
114
@@ -79,8 +117,8 b' class RepoModel(object):'
79 self.sa.delete(repo)
117 self.sa.delete(repo)
80 self.sa.commit()
118 self.sa.commit()
81 self.__delete_repo(repo.repo_name)
119 self.__delete_repo(repo.repo_name)
82 except Exception as e:
120 except:
83 log.error(e)
121 log.error(traceback.format_exc())
84 self.sa.rollback()
122 self.sa.rollback()
85 raise
123 raise
86
124
@@ -103,4 +141,5 b' class RepoModel(object):'
103 #disable hg
141 #disable hg
104 shutil.move(os.path.join(rm_path, '.hg'), os.path.join(rm_path, 'rm__.hg'))
142 shutil.move(os.path.join(rm_path, '.hg'), os.path.join(rm_path, 'rm__.hg'))
105 #disable repo
143 #disable repo
106 shutil.move(rm_path, os.path.join(g.base_path, 'rm__%s-%s' % (datetime.today(), id)))
144 shutil.move(rm_path, os.path.join(g.base_path, 'rm__%s__%s' \
145 % (datetime.today(), name)))
@@ -39,11 +39,71 b''
39 <td>${self.get_form_error('user')}</td>
39 <td>${self.get_form_error('user')}</td>
40 </tr>
40 </tr>
41 <tr>
41 <tr>
42 <td>${_('Permissions')}</td>
43 <td>
44 <table>
45 <tr>
46 <td>${_('none')}</td>
47 <td>${_('read')}</td>
48 <td>${_('write')}</td>
49 <td>${_('admin')}</td>
50 <td>${_('user')}</td>
51 </tr>
52
53 %for r2p in c.repo_info.repo2perm:
54 <tr>
55 <td>${h.radio('perm_%s' % r2p.user.username,'repository.none')}</td>
56 <td>${h.radio('perm_%s' % r2p.user.username,'repository.read')}</td>
57 <td>${h.radio('perm_%s' % r2p.user.username,'repository.write')}</td>
58 <td>${h.radio('perm_%s' % r2p.user.username,'repository.admin')}</td>
59 <td>${r2p.user.username}</td>
60 </tr>
61 %endfor
62
63
64 <%
65
66 if not hasattr(c,'form_errors'):
67 d = 'display:none;'
68 else:
69 d=''
70 %>
71
72 <tr id="add_perm_input" style="${d}">
73 <td>${h.radio('perm_new_user','repository.none')}</td>
74 <td>${h.radio('perm_new_user','repository.read')}</td>
75 <td>${h.radio('perm_new_user','repository.write')}</td>
76 <td>${h.radio('perm_new_user','repository.admin')}</td>
77 <td>${h.text('perm_new_user_name',size=10)}</td>
78 <td>${self.get_form_error('perm_new_user_name')}</td>
79 </tr>
80 <tr>
81 <td colspan="4">
82 <span id="add_perm" class="add_icon" style="cursor: pointer;">
83 ${_('Add another user')}
84 </span>
85 </td>
86 </tr>
87 </table>
88 </td>
89
90 </tr>
91 <tr>
42 <td></td>
92 <td></td>
43 <td>${h.submit('update','update')}</td>
93 <td>${h.submit('update','update')}</td>
44 </tr>
94 </tr>
45
95
46 </table>
96 </table>
47 ${h.end_form()}
97 ${h.end_form()}
98 <script type="text/javascript">
99 YAHOO.util.Event.onDOMReady(function(){
100 var D = YAHOO.util.Dom;
101 YAHOO.util.Event.addListener('add_perm','click',function(){
102 D.setStyle('add_perm_input','display','');
103 D.setStyle('add_perm','opacity','0.6');
104 D.setStyle('add_perm','cursor','default');
105 });
106 });
107 </script>
48 </div>
108 </div>
49 </%def>
109 </%def>
General Comments 0
You need to be logged in to leave comments. Login now