##// END OF EJS Templates
Merge with upstream
Nicolas VINOT -
r1591:0b63a0d2 merge beta
parent child Browse files
Show More
@@ -0,0 +1,63 b''
1 # -*- coding: utf-8 -*-
2 """
3 rhodecode.model.users_group
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
5
6 repository permission model for RhodeCode
7
8 :created_on: Oct 1, 2011
9 :author: nvinot
10 :copyright: (C) 2011-2011 Nicolas Vinot <aeris@imirhil.fr>
11 :license: GPLv3, see COPYING for more details.
12 """
13 # This program is free software: you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation, either version 3 of the License, or
16 # (at your option) any later version.
17 #
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25
26 import logging
27 from rhodecode.model.db import BaseModel, RepoToPerm, Permission
28 from rhodecode.model.meta import Session
29
30 log = logging.getLogger( __name__ )
31
32 class RepositoryPermissionModel( BaseModel ):
33 def getUserPermission( self, repository, user ):
34 return RepoToPerm.query() \
35 .filter( RepoToPerm.user == user ) \
36 .filter( RepoToPerm.repository == repository ) \
37 .scalar()
38
39 def updateUserPermission( self, repository, user, permission ):
40 permission = Permission.get_by_key( permission )
41 current = self.getUserPermission( repository, user )
42 if current:
43 if not current.permission is permission:
44 current.permission = permission
45 else:
46 p = RepoToPerm()
47 p.user = user
48 p.repository = repository
49 p.permission = permission
50 Session.add( p )
51 Session.commit()
52
53 def deleteUserPermission( self, repository, user ):
54 current = self.getUserPermission( repository, user )
55 if current:
56 Session.delete( current )
57 Session.commit()
58
59 def updateOrDeleteUserPermission( self, repository, user, permission ):
60 if permission:
61 self.updateUserPermission( repository, user, permission )
62 else:
63 self.deleteUserPermission( repository, user )
@@ -0,0 +1,89 b''
1 # -*- coding: utf-8 -*-
2 """
3 rhodecode.model.users_group
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
5
6 users group model for RhodeCode
7
8 :created_on: Oct 1, 2011
9 :author: nvinot
10 :copyright: (C) 2011-2011 Nicolas Vinot <aeris@imirhil.fr>
11 :license: GPLv3, see COPYING for more details.
12 """
13 # This program is free software: you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation, either version 3 of the License, or
16 # (at your option) any later version.
17 #
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25
26 import logging
27 import traceback
28
29 from rhodecode.model import BaseModel
30 from rhodecode.model.caching_query import FromCache
31 from rhodecode.model.db import UsersGroupMember, UsersGroup
32
33 log = logging.getLogger( __name__ )
34
35 class UsersGroupModel( BaseModel ):
36
37 def get( self, users_group_id, cache = False ):
38 users_group = UsersGroup.query()
39 if cache:
40 users_group = users_group.options( FromCache( "sql_cache_short",
41 "get_users_group_%s" % users_group_id ) )
42 return users_group.get( users_group_id )
43
44 def get_by_name( self, name, cache = False, case_insensitive = False ):
45 users_group = UsersGroup.query()
46 if case_insensitive:
47 users_group = users_group.filter( UsersGroup.users_group_name.ilike( name ) )
48 else:
49 users_group = users_group.filter( UsersGroup.users_group_name == name )
50 if cache:
51 users_group = users_group.options( FromCache( "sql_cache_short",
52 "get_users_group_%s" % name ) )
53 return users_group.scalar()
54
55 def create( self, form_data ):
56 try:
57 new_users_group = UsersGroup()
58 for k, v in form_data.items():
59 setattr( new_users_group, k, v )
60
61 self.sa.add( new_users_group )
62 self.sa.commit()
63 return new_users_group
64 except:
65 log.error( traceback.format_exc() )
66 self.sa.rollback()
67 raise
68
69 def add_user_to_group( self, users_group, user ):
70 for m in users_group.members:
71 u = m.user
72 if u.user_id == user.user_id:
73 return m
74
75 try:
76 users_group_member = UsersGroupMember()
77 users_group_member.user = user
78 users_group_member.users_group = users_group
79
80 users_group.members.append( users_group_member )
81 user.group_member.append( users_group_member )
82
83 self.sa.add( users_group_member )
84 self.sa.commit()
85 return users_group_member
86 except:
87 log.error( traceback.format_exc() )
88 self.sa.rollback()
89 raise
@@ -2,10 +2,17 b' import traceback'
2 import logging
2 import logging
3
3
4 from rhodecode.controllers.api import JSONRPCController, JSONRPCError
4 from rhodecode.controllers.api import JSONRPCController, JSONRPCError
5 from rhodecode.lib.auth import HasPermissionAllDecorator
5 from rhodecode.lib.auth import HasPermissionAllDecorator, HasPermissionAnyDecorator
6 from rhodecode.model.scm import ScmModel
6 from rhodecode.model.scm import ScmModel
7
7
8 from rhodecode.model.db import User, UsersGroup, Repository
8 from rhodecode.model.db import User, UsersGroup, Group, Repository
9 from rhodecode.model.repo import RepoModel
10 from rhodecode.model.user import UserModel
11 from rhodecode.model.repo_permission import RepositoryPermissionModel
12 from rhodecode.model.users_group import UsersGroupModel
13 from rhodecode.model import users_group
14 from rhodecode.model.repos_group import ReposGroupModel
15 from sqlalchemy.orm.exc import NoResultFound
9
16
10 log = logging.getLogger(__name__)
17 log = logging.getLogger( __name__ )
11
18
@@ -45,54 +52,322 b' class ApiController(JSONRPCController):'
45 except Exception:
52 except Exception:
46 raise JSONRPCError('Unable to pull changes from "%s"' % repo)
53 raise JSONRPCError( 'Unable to pull changes from "%s"' % repo )
47
54
55 @HasPermissionAllDecorator( 'hg.admin' )
56 def get_user( self, apiuser, username ):
57 """"
58 Get a user by username
59
60 :param apiuser
61 :param username
62 """
63
64 user = User.get_by_username( username )
65 if not user:
66 return None
67
68 return dict( id = user.user_id,
69 username = user.username,
70 firstname = user.name,
71 lastname = user.lastname,
72 email = user.email,
73 active = user.active,
74 admin = user.admin,
75 ldap = user.ldap_dn )
48
76
49 @HasPermissionAllDecorator('hg.admin')
77 @HasPermissionAllDecorator( 'hg.admin' )
50 def create_user(self, apiuser, username, password, active, admin, name,
78 def get_users( self, apiuser ):
51 lastname, email):
79 """"
80 Get all users
81
82 :param apiuser
52 """
83 """
53 Creates new user
84
85 result = []
86 for user in User.getAll():
87 result.append( dict( id = user.user_id,
88 username = user.username,
89 firstname = user.name,
90 lastname = user.lastname,
91 email = user.email,
92 active = user.active,
93 admin = user.admin,
94 ldap = user.ldap_dn ) )
95 return result
96
97 @HasPermissionAllDecorator( 'hg.admin' )
98 def create_user( self, apiuser, username, password, firstname,
99 lastname, email, active = True, admin = False, ldap_dn = None ):
100 """
101 Create new user
54
102
55 :param apiuser:
103 :param apiuser:
56 :param username:
104 :param username:
57 :param password:
105 :param password:
58 :param active:
59 :param admin:
60 :param name:
106 :param name:
61 :param lastname:
107 :param lastname:
62 :param email:
108 :param email:
109 :param active:
110 :param admin:
111 :param ldap_dn:
63 """
112 """
64
113
114 if self.get_user( apiuser, username ):
115 raise JSONRPCError( "user %s already exist" % username )
116
117 try:
65 form_data = dict(username=username,
118 form_data = dict( username = username,
66 password=password,
119 password = password,
67 active=active,
120 active = active,
68 admin=admin,
121 admin = admin,
69 name=name,
122 name = firstname,
70 lastname=lastname,
123 lastname = lastname,
71 email=email)
124 email = email,
72 try:
125 ldap_dn = ldap_dn )
73 u = User.create(form_data)
126 UserModel().create_ldap( username, password, ldap_dn, form_data )
74 return {'id':u.user_id,
127 return dict( msg = 'created new user %s' % username )
75 'msg':'created new user %s' % name}
76 except Exception:
128 except Exception:
77 log.error(traceback.format_exc())
129 log.error( traceback.format_exc() )
78 raise JSONRPCError('failed to create user %s' % name)
130 raise JSONRPCError( 'failed to create user %s' % username )
79
80
131
81 @HasPermissionAllDecorator('hg.admin')
132 @HasPermissionAllDecorator( 'hg.admin' )
82 def create_users_group(self, apiuser, name, active):
133 def get_users_group( self, apiuser, group_name ):
134 """"
135 Get users group by name
136
137 :param apiuser
138 :param group_name
139 """
140
141 users_group = UsersGroup.get_by_group_name( group_name )
142 if not users_group:
143 return None
144
145 members = []
146 for user in users_group.members:
147 user = user.user
148 members.append( dict( id = user.user_id,
149 username = user.username,
150 firstname = user.name,
151 lastname = user.lastname,
152 email = user.email,
153 active = user.active,
154 admin = user.admin,
155 ldap = user.ldap_dn ) )
156
157 return dict( id = users_group.users_group_id,
158 name = users_group.users_group_name,
159 active = users_group.users_group_active,
160 members = members )
161
162 @HasPermissionAllDecorator( 'hg.admin' )
163 def get_users_groups( self, apiuser ):
164 """"
165 Get all users groups
166
167 :param apiuser
168 """
169
170 result = []
171 for users_group in UsersGroup.getAll():
172 members = []
173 for user in users_group.members:
174 user = user.user
175 members.append( dict( id = user.user_id,
176 username = user.username,
177 firstname = user.name,
178 lastname = user.lastname,
179 email = user.email,
180 active = user.active,
181 admin = user.admin,
182 ldap = user.ldap_dn ) )
183
184 result.append( dict( id = users_group.users_group_id,
185 name = users_group.users_group_name,
186 active = users_group.users_group_active,
187 members = members ) )
188 return result
189
190 @HasPermissionAllDecorator( 'hg.admin' )
191 def create_users_group( self, apiuser, name, active = True ):
83 """
192 """
84 Creates an new usergroup
193 Creates an new usergroup
85
194
86 :param name:
195 :param name:
87 :param active:
196 :param active:
88 """
197 """
89 form_data = {'users_group_name':name,
198
90 'users_group_active':active}
199 if self.get_users_group( apiuser, name ):
200 raise JSONRPCError( "users group %s already exist" % name )
201
91 try:
202 try:
203 form_data = dict( users_group_name = name,
204 users_group_active = active )
92 ug = UsersGroup.create(form_data)
205 ug = UsersGroup.create( form_data )
93 return {'id':ug.users_group_id,
206 return dict( id = ug.users_group_id,
94 'msg':'created new users group %s' % name}
207 msg = 'created new users group %s' % name )
95 except Exception:
208 except Exception:
96 log.error(traceback.format_exc())
209 log.error( traceback.format_exc() )
97 raise JSONRPCError('failed to create group %s' % name)
210 raise JSONRPCError( 'failed to create group %s' % name )
211
212 @HasPermissionAllDecorator( 'hg.admin' )
213 def add_user_to_users_group( self, apiuser, group_name, user_name ):
214 """"
215 Add a user to a group
216
217 :param apiuser
218 :param group_name
219 :param user_name
220 """
221
222 try:
223 users_group = UsersGroup.get_by_group_name( group_name )
224 if not users_group:
225 raise JSONRPCError( 'unknown users group %s' % group_name )
226
227 try:
228 user = User.get_by_username( user_name )
229 except NoResultFound:
230 raise JSONRPCError( 'unknown user %s' % user_name )
231
232 ugm = UsersGroupModel().add_user_to_group( users_group, user )
233
234 return dict( id = ugm.users_group_member_id,
235 msg = 'created new users group member' )
236 except Exception:
237 log.error( traceback.format_exc() )
238 raise JSONRPCError( 'failed to create users group member' )
239
240 @HasPermissionAnyDecorator( 'hg.admin' )
241 def get_repo( self, apiuser, repo_name ):
242 """"
243 Get repository by name
244
245 :param apiuser
246 :param repo_name
247 """
248
249 try:
250 repo = Repository.get_by_repo_name( repo_name )
251 except NoResultFound:
252 return None
253
254 members = []
255 for user in repo.repo_to_perm:
256 perm = user.permission.permission_name
257 user = user.user
258 members.append( dict( type_ = "user",
259 id = user.user_id,
260 username = user.username,
261 firstname = user.name,
262 lastname = user.lastname,
263 email = user.email,
264 active = user.active,
265 admin = user.admin,
266 ldap = user.ldap_dn,
267 permission = perm ) )
268 for users_group in repo.users_group_to_perm:
269 perm = users_group.permission.permission_name
270 users_group = users_group.users_group
271 members.append( dict( type_ = "users_group",
272 id = users_group.users_group_id,
273 name = users_group.users_group_name,
274 active = users_group.users_group_active,
275 permission = perm ) )
276
277 return dict( id = repo.repo_id,
278 name = repo.repo_name,
279 type = repo.repo_type,
280 description = repo.description,
281 members = members )
282
283 @HasPermissionAnyDecorator( 'hg.admin' )
284 def get_repos( self, apiuser ):
285 """"
286 Get all repositories
287
288 :param apiuser
289 """
290
291 result = []
292 for repository in Repository.getAll():
293 result.append( dict( id = repository.repo_id,
294 name = repository.repo_name,
295 type = repository.repo_type,
296 description = repository.description ) )
297 return result
298
299 @HasPermissionAnyDecorator( 'hg.admin', 'hg.create.repository' )
300 def create_repo( self, apiuser, name, owner_name, description = '', repo_type = 'hg', \
301 private = False ):
302 """
303 Create a repository
304
305 :param apiuser
306 :param name
307 :param description
308 :param type
309 :param private
310 :param owner_name
311 """
312
313 try:
314 try:
315 owner = User.get_by_username( owner_name )
316 except NoResultFound:
317 raise JSONRPCError( 'unknown user %s' % owner )
318
319 if self.get_repo( apiuser, name ):
320 raise JSONRPCError( "repo %s already exist" % name )
321
322 groups = name.split( '/' )
323 real_name = groups[-1]
324 groups = groups[:-1]
325 parent_id = None
326 for g in groups:
327 group = Group.get_by_group_name( g )
328 if not group:
329 group = ReposGroupModel().create( dict( group_name = g,
330 group_description = '',
331 group_parent_id = parent_id ) )
332 parent_id = group.group_id
333
334 RepoModel().create( dict( repo_name = real_name,
335 repo_name_full = name,
336 description = description,
337 private = private,
338 repo_type = repo_type,
339 repo_group = parent_id,
340 clone_uri = None ), owner )
341 except Exception:
342 log.error( traceback.format_exc() )
343 raise JSONRPCError( 'failed to create repository %s' % name )
344
345 @HasPermissionAnyDecorator( 'hg.admin' )
346 def add_user_to_repo( self, apiuser, repo_name, user_name, perm ):
347 """
348 Add permission for a user to a repository
349
350 :param apiuser
351 :param repo_name
352 :param user_name
353 :param perm
354 """
355
356 try:
357 try:
358 repo = Repository.get_by_repo_name( repo_name )
359 except NoResultFound:
360 raise JSONRPCError( 'unknown repository %s' % repo )
361
362 try:
363 user = User.get_by_username( user_name )
364 except NoResultFound:
365 raise JSONRPCError( 'unknown user %s' % user )
366
367 RepositoryPermissionModel().updateOrDeleteUserPermission( repo, user, perm )
368 except Exception:
369 log.error( traceback.format_exc() )
370 raise JSONRPCError( 'failed to edit permission %(repo)s for %(user)s'
371 % dict( user = user_name, repo = repo_name ) )
372
98 No newline at end of file
373
@@ -128,12 +128,15 b' class BaseModel(object):'
128
128
129 @classmethod
129 @classmethod
130 def get(cls, id_):
130 def get( cls, id_ ):
131 if id_:
131 return cls.query().get( id_ )
132 return Session.query(cls).get(id_)
132
133 @classmethod
134 def getAll( cls ):
135 return cls.query().all()
133
136
134 @classmethod
137 @classmethod
135 def delete(cls, id_):
138 def delete( cls, id_ ):
136 obj = Session.query(cls).get(id_)
139 obj = cls.query().get( id_ )
137 Session.delete(obj)
140 Session.delete( obj )
138 Session.commit()
141 Session.commit()
139
142
@@ -178,13 +181,13 b' class RhodeCodeSettings(Base, BaseModel)'
178
181
179 @classmethod
182 @classmethod
180 def get_by_name(cls, ldap_key):
183 def get_by_name( cls, ldap_key ):
181 return Session.query(cls)\
184 return cls.query()\
182 .filter(cls.app_settings_name == ldap_key).scalar()
185 .filter( cls.app_settings_name == ldap_key ).scalar()
183
186
184 @classmethod
187 @classmethod
185 def get_app_settings(cls, cache=False):
188 def get_app_settings( cls, cache = False ):
186
189
187 ret = Session.query(cls)
190 ret = cls.query()
188
191
189 if cache:
192 if cache:
190 ret = ret.options(FromCache("sql_cache_short", "get_hg_settings"))
193 ret = ret.options( FromCache( "sql_cache_short", "get_hg_settings" ) )
@@ -200,7 +203,7 b' class RhodeCodeSettings(Base, BaseModel)'
200
203
201 @classmethod
204 @classmethod
202 def get_ldap_settings(cls, cache=False):
205 def get_ldap_settings( cls, cache = False ):
203 ret = Session.query(cls)\
206 ret = cls.query()\
204 .filter(cls.app_settings_name.startswith('ldap_')).all()
207 .filter( cls.app_settings_name.startswith( 'ldap_' ) ).all()
205 fd = {}
208 fd = {}
206 for row in ret:
209 for row in ret:
@@ -227,7 +230,7 b' class RhodeCodeUi(Base, BaseModel):'
227
230
228 @classmethod
231 @classmethod
229 def get_by_key(cls, key):
232 def get_by_key( cls, key ):
230 return Session.query(cls).filter(cls.ui_key == key)
233 return cls.query().filter( cls.ui_key == key )
231
234
232
235
233 @classmethod
236 @classmethod
@@ -311,7 +314,7 b' class User(Base, BaseModel):'
311
314
312 @classmethod
315 @classmethod
313 def get_by_api_key(cls, api_key):
316 def get_by_api_key( cls, api_key ):
314 return Session.query(cls).filter(cls.api_key == api_key).one()
317 return cls.query().filter( cls.api_key == api_key ).one()
315
318
316 def update_lastlogin(self):
319 def update_lastlogin( self ):
317 """Update user lastlogin"""
320 """Update user lastlogin"""
@@ -376,11 +379,11 b' class UsersGroup(Base, BaseModel):'
376 @classmethod
379 @classmethod
377 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
380 def get_by_group_name( cls, group_name, cache = False, case_insensitive = False ):
378 if case_insensitive:
381 if case_insensitive:
379 gr = Session.query(cls)\
382 gr = cls.query()\
380 .filter(cls.users_group_name.ilike(group_name))
383 .filter( cls.users_group_name.ilike( group_name ) )
381 else:
384 else:
382 gr = Session.query(UsersGroup)\
385 gr = cls.query()\
383 .filter(UsersGroup.users_group_name == group_name)
386 .filter( cls.users_group_name == group_name )
384 if cache:
387 if cache:
385 gr = gr.options(FromCache("sql_cache_short",
388 gr = gr.options( FromCache( "sql_cache_short",
386 "get_user_%s" % group_name))
389 "get_user_%s" % group_name ) )
@@ -389,7 +392,7 b' class UsersGroup(Base, BaseModel):'
389
392
390 @classmethod
393 @classmethod
391 def get(cls, users_group_id, cache=False):
394 def get( cls, users_group_id, cache = False ):
392 users_group = Session.query(cls)
395 users_group = cls.query()
393 if cache:
396 if cache:
394 users_group = users_group.options(FromCache("sql_cache_short",
397 users_group = users_group.options( FromCache( "sql_cache_short",
395 "get_users_group_%s" % users_group_id))
398 "get_users_group_%s" % users_group_id ) )
@@ -456,7 +459,6 b' class UsersGroup(Base, BaseModel):'
456 Session.rollback()
459 Session.rollback()
457 raise
460 raise
458
461
459
460 class UsersGroupMember(Base, BaseModel):
462 class UsersGroupMember( Base, BaseModel ):
461 __tablename__ = 'users_groups_members'
463 __tablename__ = 'users_groups_members'
462 __table_args__ = {'extend_existing':True}
464 __table_args__ = {'extend_existing':True}
@@ -472,6 +474,15 b' class UsersGroupMember(Base, BaseModel):'
472 self.users_group_id = gr_id
474 self.users_group_id = gr_id
473 self.user_id = u_id
475 self.user_id = u_id
474
476
477 @staticmethod
478 def add_user_to_group( group, user ):
479 ugm = UsersGroupMember()
480 ugm.users_group = group
481 ugm.user = user
482 Session.add( ugm )
483 Session.commit()
484 return ugm
485
475 class Repository(Base, BaseModel):
486 class Repository( Base, BaseModel ):
476 __tablename__ = 'repositories'
487 __tablename__ = 'repositories'
477 __table_args__ = (UniqueConstraint('repo_name'), {'extend_existing':True},)
488 __table_args__ = ( UniqueConstraint( 'repo_name' ), {'extend_existing':True}, )
@@ -513,16 +524,14 b' class Repository(Base, BaseModel):'
513 @classmethod
524 @classmethod
514 def get_by_repo_name(cls, repo_name):
525 def get_by_repo_name( cls, repo_name ):
515 q = Session.query(cls).filter(cls.repo_name == repo_name)
526 q = Session.query( cls ).filter( cls.repo_name == repo_name )
516
517 q = q.options(joinedload(Repository.fork))\
527 q = q.options( joinedload( Repository.fork ) )\
518 .options(joinedload(Repository.user))\
528 .options( joinedload( Repository.user ) )\
519 .options(joinedload(Repository.group))\
529 .options( joinedload( Repository.group ) )
520
521 return q.one()
530 return q.one()
522
531
523 @classmethod
532 @classmethod
524 def get_repo_forks(cls, repo_id):
533 def get_repo_forks( cls, repo_id ):
525 return Session.query(cls).filter(Repository.fork_id == repo_id)
534 return cls.query().filter( Repository.fork_id == repo_id )
526
535
527 @classmethod
536 @classmethod
528 def base_path(cls):
537 def base_path( cls ):
@@ -605,7 +614,7 b' class Repository(Base, BaseModel):'
605 baseui._tcfg = config.config()
614 baseui._tcfg = config.config()
606
615
607
616
608 ret = Session.query(RhodeCodeUi)\
617 ret = RhodeCodeUi.query()\
609 .options(FromCache("sql_cache_short", "repository_repo_ui")).all()
618 .options( FromCache( "sql_cache_short", "repository_repo_ui" ) ).all()
610
619
611 hg_ui = ret
620 hg_ui = ret
@@ -660,7 +669,7 b' class Repository(Base, BaseModel):'
660 None otherwise. `cache_active = False` means that this cache
669 None otherwise. `cache_active = False` means that this cache
661 state is not valid and needs to be invalidated
670 state is not valid and needs to be invalidated
662 """
671 """
663 return Session.query(CacheInvalidation)\
672 return CacheInvalidation.query()\
664 .filter(CacheInvalidation.cache_key == self.repo_name)\
673 .filter( CacheInvalidation.cache_key == self.repo_name )\
665 .filter(CacheInvalidation.cache_active == False)\
674 .filter( CacheInvalidation.cache_active == False )\
666 .scalar()
675 .scalar()
@@ -669,7 +678,7 b' class Repository(Base, BaseModel):'
669 """
678 """
670 set a cache for invalidation for this instance
679 set a cache for invalidation for this instance
671 """
680 """
672 inv = Session.query(CacheInvalidation)\
681 inv = CacheInvalidation.query()\
673 .filter(CacheInvalidation.cache_key == self.repo_name)\
682 .filter( CacheInvalidation.cache_key == self.repo_name )\
674 .scalar()
683 .scalar()
675
684
@@ -771,8 +780,17 b' class Group(Base, BaseModel):'
771 return '/'
780 return '/'
772
781
773 @classmethod
782 @classmethod
774 def get_by_group_name(cls, group_name):
783 def get_by_group_name( cls, group_name, cache = False, case_insensitive = False ):
775 return cls.query().filter(cls.group_name == group_name).scalar()
784 if case_insensitive:
785 gr = cls.query()\
786 .filter( cls.group_name.ilike( group_name ) )
787 else:
788 gr = cls.query()\
789 .filter( cls.group_name == group_name )
790 if cache:
791 gr = gr.options( FromCache( "sql_cache_short",
792 "get_group_%s" % group_name ) )
793 return gr.scalar()
776
794
777 @property
795 @property
778 def parents(self):
796 def parents( self ):
@@ -800,7 +818,7 b' class Group(Base, BaseModel):'
800
818
801 @property
819 @property
802 def children(self):
820 def children( self ):
803 return Session.query(Group).filter(Group.parent_group == self)
821 return Group.query().filter( Group.parent_group == self )
804
822
805 @property
823 @property
806 def name(self):
824 def name( self ):
@@ -808,7 +826,8 b' class Group(Base, BaseModel):'
808
826
809 @property
827 @property
810 def full_path(self):
828 def full_path( self ):
811 return self.group_name
829 return Group.url_sep().join( [g.group_name for g in self.parents] +
830 [self.group_name] )
812
831
813 @property
832 @property
814 def full_path_splitted(self):
833 def full_path_splitted( self ):
@@ -816,7 +835,7 b' class Group(Base, BaseModel):'
816
835
817 @property
836 @property
818 def repositories(self):
837 def repositories( self ):
819 return Session.query(Repository).filter(Repository.group == self)
838 return Repository.query().filter( Repository.group == self )
820
839
821 @property
840 @property
822 def repositories_recursive_count(self):
841 def repositories_recursive_count( self ):
@@ -855,7 +874,7 b' class Permission(Base, BaseModel):'
855
874
856 @classmethod
875 @classmethod
857 def get_by_key(cls, key):
876 def get_by_key( cls, key ):
858 return Session.query(cls).filter(cls.permission_name == key).scalar()
877 return cls.query().filter( cls.permission_name == key ).scalar()
859
878
860 class RepoToPerm(Base, BaseModel):
879 class RepoToPerm( Base, BaseModel ):
861 __tablename__ = 'repo_to_perm'
880 __tablename__ = 'repo_to_perm'
@@ -884,7 +903,7 b' class UserToPerm(Base, BaseModel):'
884 if not isinstance(perm, Permission):
903 if not isinstance( perm, Permission ):
885 raise Exception('perm needs to be an instance of Permission class')
904 raise Exception( 'perm needs to be an instance of Permission class' )
886
905
887 return Session.query(cls).filter(cls.user_id == user_id)\
906 return cls.query().filter( cls.user_id == user_id )\
888 .filter(cls.permission == perm).scalar() is not None
907 .filter( cls.permission == perm ).scalar() is not None
889
908
890 @classmethod
909 @classmethod
@@ -908,7 +927,7 b' class UserToPerm(Base, BaseModel):'
908 raise Exception('perm needs to be an instance of Permission class')
927 raise Exception( 'perm needs to be an instance of Permission class' )
909
928
910 try:
929 try:
911 Session.query(cls).filter(cls.user_id == user_id)\
930 cls.query().filter( cls.user_id == user_id )\
912 .filter(cls.permission == perm).delete()
931 .filter( cls.permission == perm ).delete()
913 Session.commit()
932 Session.commit()
914 except:
933 except:
@@ -944,7 +963,7 b' class UsersGroupToPerm(Base, BaseModel):'
944 if not isinstance(perm, Permission):
963 if not isinstance( perm, Permission ):
945 raise Exception('perm needs to be an instance of Permission class')
964 raise Exception( 'perm needs to be an instance of Permission class' )
946
965
947 return Session.query(cls).filter(cls.users_group_id ==
966 return cls.query().filter( cls.users_group_id ==
948 users_group_id)\
967 users_group_id )\
949 .filter(cls.permission == perm)\
968 .filter( cls.permission == perm )\
950 .scalar() is not None
969 .scalar() is not None
@@ -970,7 +989,7 b' class UsersGroupToPerm(Base, BaseModel):'
970 raise Exception('perm needs to be an instance of Permission class')
989 raise Exception( 'perm needs to be an instance of Permission class' )
971
990
972 try:
991 try:
973 Session.query(cls).filter(cls.users_group_id == users_group_id)\
992 cls.query().filter( cls.users_group_id == users_group_id )\
974 .filter(cls.permission == perm).delete()
993 .filter( cls.permission == perm ).delete()
975 Session.commit()
994 Session.commit()
976 except:
995 except:
@@ -1022,7 +1041,7 b' class UserFollowing(Base, BaseModel):'
1022
1041
1023 @classmethod
1042 @classmethod
1024 def get_repo_followers(cls, repo_id):
1043 def get_repo_followers( cls, repo_id ):
1025 return Session.query(cls).filter(cls.follows_repo_id == repo_id)
1044 return cls.query().filter( cls.follows_repo_id == repo_id )
1026
1045
1027 class CacheInvalidation(Base, BaseModel):
1046 class CacheInvalidation( Base, BaseModel ):
1028 __tablename__ = 'cache_invalidation'
1047 __tablename__ = 'cache_invalidation'
@@ -50,7 +50,7 b' class ReposGroupModel(BaseModel):'
50 q = RhodeCodeUi.get_by_key('/').one()
50 q = RhodeCodeUi.get_by_key( '/' ).one()
51 return q.ui_value
51 return q.ui_value
52
52
53 def __create_group(self, group_name):
53 def __create_group( self, group_name, parent_id ):
54 """
54 """
55 makes repositories group on filesystem
55 makes repositories group on filesystem
56
56
@@ -58,30 +58,44 b' class ReposGroupModel(BaseModel):'
58 :param parent_id:
58 :param parent_id:
59 """
59 """
60
60
61 create_path = os.path.join(self.repos_path, group_name)
61 if parent_id:
62 paths = Group.get( parent_id ).full_path.split( Group.url_sep() )
63 parent_path = os.sep.join( paths )
64 else:
65 parent_path = ''
66
67 create_path = os.path.join( self.repos_path, parent_path, group_name )
62 log.debug('creating new group in %s', create_path)
68 log.debug( 'creating new group in %s', create_path )
63
69
64 if os.path.isdir(create_path):
70 if os.path.isdir( create_path ):
65 raise Exception('That directory already exists !')
71 raise Exception( 'That directory already exists !' )
66
72
73
67 os.makedirs(create_path)
74 os.makedirs( create_path )
68
75
69 def __rename_group(self, old, new):
76
77 def __rename_group( self, old, old_parent_id, new, new_parent_id ):
70 """
78 """
71 Renames a group on filesystem
79 Renames a group on filesystem
72
80
73 :param group_name:
81 :param group_name:
74 """
82 """
75
76 if old == new:
77 log.debug('skipping group rename')
78 return
79
80 log.debug('renaming repos group from %s to %s', old, new)
83 log.debug( 'renaming repos group from %s to %s', old, new )
81
84
85 if new_parent_id:
86 paths = Group.get( new_parent_id ).full_path.split( Group.url_sep() )
87 new_parent_path = os.sep.join( paths )
88 else:
89 new_parent_path = ''
82
90
83 old_path = os.path.join(self.repos_path, old)
91 if old_parent_id:
84 new_path = os.path.join(self.repos_path, new)
92 paths = Group.get( old_parent_id ).full_path.split( Group.url_sep() )
93 old_parent_path = os.sep.join( paths )
94 else:
95 old_parent_path = ''
96
97 old_path = os.path.join( self.repos_path, old_parent_path, old )
98 new_path = os.path.join( self.repos_path, new_parent_path, new )
85
99
86 log.debug('renaming repos paths from %s to %s', old_path, new_path)
100 log.debug( 'renaming repos paths from %s to %s', old_path, new_path )
87
101
@@ -100,20 +114,20 b' class ReposGroupModel(BaseModel):'
100 paths = os.sep.join(paths)
114 paths = os.sep.join( paths )
101
115
102 rm_path = os.path.join(self.repos_path, paths)
116 rm_path = os.path.join( self.repos_path, paths )
103 if os.path.isdir(rm_path):
104 # delete only if that path really exists
105 os.rmdir(rm_path)
117 os.rmdir( rm_path )
106
118
107 def create(self, form_data):
119 def create( self, form_data ):
108 try:
120 try:
109 new_repos_group = Group()
121 new_repos_group = Group()
110 new_repos_group.group_description = form_data['group_description']
122 new_repos_group.group_name = form_data['group_name']
111 new_repos_group.parent_group = Group.get(form_data['group_parent_id'])
123 new_repos_group.group_description = \
112 new_repos_group.group_name = new_repos_group.get_new_name(form_data['group_name'])
124 form_data['group_description']
125 new_repos_group.group_parent_id = form_data['group_parent_id']
113
126
114 self.sa.add(new_repos_group)
127 self.sa.add( new_repos_group )
115
128
116 self.__create_group(new_repos_group.group_name)
129 self.__create_group( form_data['group_name'],
130 form_data['group_parent_id'] )
117
131
118 self.sa.commit()
132 self.sa.commit()
119 return new_repos_group
133 return new_repos_group
@@ -126,27 +140,23 b' class ReposGroupModel(BaseModel):'
126
140
127 try:
141 try:
128 repos_group = Group.get(repos_group_id)
142 repos_group = Group.get( repos_group_id )
129 old_path = repos_group.full_path
143 old_name = repos_group.group_name
144 old_parent_id = repos_group.group_parent_id
130
145
131 #change properties
146 repos_group.group_name = form_data['group_name']
132 repos_group.group_description = form_data['group_description']
147 repos_group.group_description = \
133 repos_group.parent_group = Group.get(form_data['group_parent_id'])
148 form_data['group_description']
134 repos_group.group_name = repos_group.get_new_name(form_data['group_name'])
149 repos_group.group_parent_id = form_data['group_parent_id']
135
136 new_path = repos_group.full_path
137
150
138 self.sa.add(repos_group)
151 self.sa.add( repos_group )
139
152
140 self.__rename_group(old_path, new_path)
153 if old_name != form_data['group_name'] or ( old_parent_id !=
141
154 form_data['group_parent_id'] ):
142 # we need to get all repositories from this new group and
155 self.__rename_group( old = old_name, old_parent_id = old_parent_id,
143 # rename them accordingly to new group path
156 new = form_data['group_name'],
144 for r in repos_group.repositories:
157 new_parent_id = form_data['group_parent_id'] )
145 r.repo_name = r.get_new_name(r.just_name)
146 self.sa.add(r)
147
158
148 self.sa.commit()
159 self.sa.commit()
149 return repos_group
150 except:
160 except:
151 log.error(traceback.format_exc())
161 log.error( traceback.format_exc() )
152 self.sa.rollback()
162 self.sa.rollback()
@@ -49,7 +49,6 b" PERM_WEIGHTS = {'repository.none': 0,"
49
49
50
50
51 class UserModel(BaseModel):
51 class UserModel(BaseModel):
52
53 def get(self, user_id, cache=False):
52 def get(self, user_id, cache=False):
54 user = self.sa.query(User)
53 user = self.sa.query(User)
55 if cache:
54 if cache:
@@ -87,6 +86,7 b' class UserModel(BaseModel):'
87 new_user.api_key = generate_api_key(form_data['username'])
86 new_user.api_key = generate_api_key(form_data['username'])
88 self.sa.add(new_user)
87 self.sa.add(new_user)
89 self.sa.commit()
88 self.sa.commit()
89 return new_user
90 except:
90 except:
91 log.error(traceback.format_exc())
91 log.error(traceback.format_exc())
92 self.sa.rollback()
92 self.sa.rollback()
General Comments 0
You need to be logged in to leave comments. Login now