##// END OF EJS Templates
fixes #30. Rewrite default permissions query + some other small fixes
marcink -
r423:16253f33 default
parent child Browse files
Show More
@@ -1,450 +1,452 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 # authentication and permission libraries
3 # authentication and permission libraries
4 # Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
4 # Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
5 #
5 #
6 # This program is free software; you can redistribute it and/or
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; version 2
8 # as published by the Free Software Foundation; version 2
9 # of the License or (at your opinion) any later version of the license.
9 # of the License or (at your opinion) any later version of the license.
10 #
10 #
11 # This program is distributed in the hope that it will be useful,
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
14 # GNU General Public License for more details.
15 #
15 #
16 # You should have received a copy of the GNU General Public License
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 # MA 02110-1301, USA.
19 # MA 02110-1301, USA.
20 """
20 """
21 Created on April 4, 2010
21 Created on April 4, 2010
22
22
23 @author: marcink
23 @author: marcink
24 """
24 """
25 from beaker.cache import cache_region
25 from beaker.cache import cache_region
26 from pylons import config, session, url, request
26 from pylons import config, session, url, request
27 from pylons.controllers.util import abort, redirect
27 from pylons.controllers.util import abort, redirect
28 from pylons_app.lib.utils import get_repo_slug
28 from pylons_app.lib.utils import get_repo_slug
29 from pylons_app.model import meta
29 from pylons_app.model import meta
30 from pylons_app.model.db import User, RepoToPerm, Repository, Permission, \
30 from pylons_app.model.db import User, RepoToPerm, Repository, Permission, \
31 UserToPerm
31 UserToPerm
32 from sqlalchemy.exc import OperationalError
32 from sqlalchemy.exc import OperationalError
33 from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
33 from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
34 import bcrypt
34 import bcrypt
35 from decorator import decorator
35 from decorator import decorator
36 import logging
36 import logging
37
37
38 log = logging.getLogger(__name__)
38 log = logging.getLogger(__name__)
39
39
40 def get_crypt_password(password):
40 def get_crypt_password(password):
41 """Cryptographic function used for password hashing based on sha1
41 """Cryptographic function used for password hashing based on sha1
42 @param password: password to hash
42 @param password: password to hash
43 """
43 """
44 return bcrypt.hashpw(password, bcrypt.gensalt(10))
44 return bcrypt.hashpw(password, bcrypt.gensalt(10))
45
45
46 def check_password(password, hashed):
46 def check_password(password, hashed):
47 return bcrypt.hashpw(password, hashed) == hashed
47 return bcrypt.hashpw(password, hashed) == hashed
48
48
49 @cache_region('super_short_term', 'cached_user')
49 @cache_region('super_short_term', 'cached_user')
50 def get_user_cached(username):
50 def get_user_cached(username):
51 sa = meta.Session
51 sa = meta.Session
52 try:
52 try:
53 user = sa.query(User).filter(User.username == username).one()
53 user = sa.query(User).filter(User.username == username).one()
54 finally:
54 finally:
55 meta.Session.remove()
55 meta.Session.remove()
56 return user
56 return user
57
57
58 def authfunc(environ, username, password):
58 def authfunc(environ, username, password):
59 try:
59 try:
60 user = get_user_cached(username)
60 user = get_user_cached(username)
61 except (NoResultFound, MultipleResultsFound, OperationalError) as e:
61 except (NoResultFound, MultipleResultsFound, OperationalError) as e:
62 log.error(e)
62 log.error(e)
63 user = None
63 user = None
64
64
65 if user:
65 if user:
66 if user.active:
66 if user.active:
67 if user.username == username and check_password(password, user.password):
67 if user.username == username and check_password(password, user.password):
68 log.info('user %s authenticated correctly', username)
68 log.info('user %s authenticated correctly', username)
69 return True
69 return True
70 else:
70 else:
71 log.error('user %s is disabled', username)
71 log.error('user %s is disabled', username)
72
72
73 return False
73 return False
74
74
75 class AuthUser(object):
75 class AuthUser(object):
76 """
76 """
77 A simple object that handles a mercurial username for authentication
77 A simple object that handles a mercurial username for authentication
78 """
78 """
79 def __init__(self):
79 def __init__(self):
80 self.username = 'None'
80 self.username = 'None'
81 self.name = ''
81 self.name = ''
82 self.lastname = ''
82 self.lastname = ''
83 self.email = ''
83 self.email = ''
84 self.user_id = None
84 self.user_id = None
85 self.is_authenticated = False
85 self.is_authenticated = False
86 self.is_admin = False
86 self.is_admin = False
87 self.permissions = {}
87 self.permissions = {}
88
88
89
89
90 def set_available_permissions(config):
90 def set_available_permissions(config):
91 """
91 """
92 This function will propagate pylons globals with all available defined
92 This function will propagate pylons globals with all available defined
93 permission given in db. We don't wannt to check each time from db for new
93 permission given in db. We don't wannt to check each time from db for new
94 permissions since adding a new permission also requires application restart
94 permissions since adding a new permission also requires application restart
95 ie. to decorate new views with the newly created permission
95 ie. to decorate new views with the newly created permission
96 @param config:
96 @param config:
97 """
97 """
98 log.info('getting information about all available permissions')
98 log.info('getting information about all available permissions')
99 try:
99 try:
100 sa = meta.Session
100 sa = meta.Session
101 all_perms = sa.query(Permission).all()
101 all_perms = sa.query(Permission).all()
102 finally:
102 finally:
103 meta.Session.remove()
103 meta.Session.remove()
104
104
105 config['available_permissions'] = [x.permission_name for x in all_perms]
105 config['available_permissions'] = [x.permission_name for x in all_perms]
106
106
107 def set_base_path(config):
107 def set_base_path(config):
108 config['base_path'] = config['pylons.app_globals'].base_path
108 config['base_path'] = config['pylons.app_globals'].base_path
109
109
110 def fill_data(user):
110 def fill_data(user):
111 """
111 """
112 Fills user data with those from database and log out user if not present
112 Fills user data with those from database and log out user if not present
113 in database
113 in database
114 @param user:
114 @param user:
115 """
115 """
116 sa = meta.Session
116 sa = meta.Session
117 dbuser = sa.query(User).get(user.user_id)
117 dbuser = sa.query(User).get(user.user_id)
118 if dbuser:
118 if dbuser:
119 user.username = dbuser.username
119 user.username = dbuser.username
120 user.is_admin = dbuser.admin
120 user.is_admin = dbuser.admin
121 user.name = dbuser.name
121 user.name = dbuser.name
122 user.lastname = dbuser.lastname
122 user.lastname = dbuser.lastname
123 user.email = dbuser.email
123 user.email = dbuser.email
124 else:
124 else:
125 user.is_authenticated = False
125 user.is_authenticated = False
126 meta.Session.remove()
126 meta.Session.remove()
127 from pprint import pprint
127 from pprint import pprint
128 pprint(user.permissions)
128 pprint(user.permissions)
129 return user
129 return user
130
130
131 def fill_perms(user):
131 def fill_perms(user):
132 """
132 """
133 Fills user permission attribute with permissions taken from database
133 Fills user permission attribute with permissions taken from database
134 @param user:
134 @param user:
135 """
135 """
136
136
137 sa = meta.Session
137 sa = meta.Session
138 user.permissions['repositories'] = {}
138 user.permissions['repositories'] = {}
139 user.permissions['global'] = set()
139 user.permissions['global'] = set()
140
140
141 #===========================================================================
141 #===========================================================================
142 # fetch default permissions
142 # fetch default permissions
143 #===========================================================================
143 #===========================================================================
144 default_perms = sa.query(RepoToPerm, UserToPerm, Repository, Permission)\
144 default_perms = sa.query(RepoToPerm, Repository, Permission)\
145 .outerjoin((UserToPerm, RepoToPerm.user_id == UserToPerm.user_id))\
146 .join((Repository, RepoToPerm.repository_id == Repository.repo_id))\
145 .join((Repository, RepoToPerm.repository_id == Repository.repo_id))\
147 .join((Permission, RepoToPerm.permission_id == Permission.permission_id))\
146 .join((Permission, RepoToPerm.permission_id == Permission.permission_id))\
148 .filter(RepoToPerm.user_id == sa.query(User).filter(User.username ==
147 .filter(RepoToPerm.user == sa.query(User).filter(User.username ==
149 'default').one().user_id).all()
148 'default').scalar()).all()
150
149
151 if user.is_admin:
150 if user.is_admin:
152 #=======================================================================
151 #=======================================================================
153 # #admin have all rights set to admin
152 # #admin have all default rights set to admin
154 #=======================================================================
153 #=======================================================================
155 user.permissions['global'].add('hg.admin')
154 user.permissions['global'].add('hg.admin')
156
155
157 for perm in default_perms:
156 for perm in default_perms:
158 p = 'repository.admin'
157 p = 'repository.admin'
159 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
158 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
160
159
161 else:
160 else:
162 #=======================================================================
161 #=======================================================================
163 # set default permissions
162 # set default permissions
164 #=======================================================================
163 #=======================================================================
165
164
166 #default global
165 #default global
167 for perm in default_perms:
166 default_global_perms = sa.query(UserToPerm)\
168 user.permissions['global'].add(perm.UserToPerm.permission.permission_name)
167 .filter(UserToPerm.user == sa.query(User).filter(User.username ==
168 'default').one())
169
170 for perm in default_global_perms:
171 user.permissions['global'].add(perm.permission.permission_name)
169
172
170 #default repositories
173 #default repositories
171 for perm in default_perms:
174 for perm in default_perms:
172 if perm.Repository.private and not perm.Repository.user_id == user.user_id:
175 if perm.Repository.private and not perm.Repository.user_id == user.user_id:
173 #disable defaults for private repos,
176 #disable defaults for private repos,
174 p = 'repository.none'
177 p = 'repository.none'
175 elif perm.Repository.user_id == user.user_id:
178 elif perm.Repository.user_id == user.user_id:
176 #set admin if owner
179 #set admin if owner
177 p = 'repository.admin'
180 p = 'repository.admin'
178 else:
181 else:
179 p = perm.Permission.permission_name
182 p = perm.Permission.permission_name
180
183
181 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
184 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
182
185
183 #=======================================================================
186 #=======================================================================
184 # #overwrite default with user permissions if any
187 # #overwrite default with user permissions if any
185 #=======================================================================
188 #=======================================================================
186 user_perms = sa.query(RepoToPerm, UserToPerm, Permission, Repository)\
189 user_perms = sa.query(RepoToPerm, Permission, Repository)\
187 .outerjoin((UserToPerm, RepoToPerm.user_id == UserToPerm.user_id))\
188 .join((Repository, RepoToPerm.repository_id == Repository.repo_id))\
190 .join((Repository, RepoToPerm.repository_id == Repository.repo_id))\
189 .join((Permission, RepoToPerm.permission_id == Permission.permission_id))\
191 .join((Permission, RepoToPerm.permission_id == Permission.permission_id))\
190 .filter(RepoToPerm.user_id == user.user_id).all()
192 .filter(RepoToPerm.user_id == user.user_id).all()
191
193
192 for perm in user_perms:
194 for perm in user_perms:
193 if perm.Repository.user_id == user.user_id:#set admin if owner
195 if perm.Repository.user_id == user.user_id:#set admin if owner
194 p = 'repository.admin'
196 p = 'repository.admin'
195 else:
197 else:
196 p = perm.Permission.permission_name
198 p = perm.Permission.permission_name
197 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
199 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
198 meta.Session.remove()
200 meta.Session.remove()
199 return user
201 return user
200
202
201 def get_user(session):
203 def get_user(session):
202 """
204 """
203 Gets user from session, and wraps permissions into user
205 Gets user from session, and wraps permissions into user
204 @param session:
206 @param session:
205 """
207 """
206 user = session.get('hg_app_user', AuthUser())
208 user = session.get('hg_app_user', AuthUser())
207 if user.is_authenticated:
209 if user.is_authenticated:
208 user = fill_data(user)
210 user = fill_data(user)
209 user = fill_perms(user)
211 user = fill_perms(user)
210 session['hg_app_user'] = user
212 session['hg_app_user'] = user
211 session.save()
213 session.save()
212 return user
214 return user
213
215
214 #===============================================================================
216 #===============================================================================
215 # CHECK DECORATORS
217 # CHECK DECORATORS
216 #===============================================================================
218 #===============================================================================
217 class LoginRequired(object):
219 class LoginRequired(object):
218 """Must be logged in to execute this function else redirect to login page"""
220 """Must be logged in to execute this function else redirect to login page"""
219
221
220 def __call__(self, func):
222 def __call__(self, func):
221 return decorator(self.__wrapper, func)
223 return decorator(self.__wrapper, func)
222
224
223 def __wrapper(self, func, *fargs, **fkwargs):
225 def __wrapper(self, func, *fargs, **fkwargs):
224 user = session.get('hg_app_user', AuthUser())
226 user = session.get('hg_app_user', AuthUser())
225 log.debug('Checking login required for user:%s', user.username)
227 log.debug('Checking login required for user:%s', user.username)
226 if user.is_authenticated:
228 if user.is_authenticated:
227 log.debug('user %s is authenticated', user.username)
229 log.debug('user %s is authenticated', user.username)
228 return func(*fargs, **fkwargs)
230 return func(*fargs, **fkwargs)
229 else:
231 else:
230 log.warn('user %s not authenticated', user.username)
232 log.warn('user %s not authenticated', user.username)
231 log.debug('redirecting to login page')
233 log.debug('redirecting to login page')
232 return redirect(url('login_home'))
234 return redirect(url('login_home'))
233
235
234 class PermsDecorator(object):
236 class PermsDecorator(object):
235 """Base class for decorators"""
237 """Base class for decorators"""
236
238
237 def __init__(self, *required_perms):
239 def __init__(self, *required_perms):
238 available_perms = config['available_permissions']
240 available_perms = config['available_permissions']
239 for perm in required_perms:
241 for perm in required_perms:
240 if perm not in available_perms:
242 if perm not in available_perms:
241 raise Exception("'%s' permission is not defined" % perm)
243 raise Exception("'%s' permission is not defined" % perm)
242 self.required_perms = set(required_perms)
244 self.required_perms = set(required_perms)
243 self.user_perms = None
245 self.user_perms = None
244
246
245 def __call__(self, func):
247 def __call__(self, func):
246 return decorator(self.__wrapper, func)
248 return decorator(self.__wrapper, func)
247
249
248
250
249 def __wrapper(self, func, *fargs, **fkwargs):
251 def __wrapper(self, func, *fargs, **fkwargs):
250 # _wrapper.__name__ = func.__name__
252 # _wrapper.__name__ = func.__name__
251 # _wrapper.__dict__.update(func.__dict__)
253 # _wrapper.__dict__.update(func.__dict__)
252 # _wrapper.__doc__ = func.__doc__
254 # _wrapper.__doc__ = func.__doc__
253
255
254 self.user_perms = session.get('hg_app_user', AuthUser()).permissions
256 self.user_perms = session.get('hg_app_user', AuthUser()).permissions
255 log.debug('checking %s permissions %s for %s',
257 log.debug('checking %s permissions %s for %s',
256 self.__class__.__name__, self.required_perms, func.__name__)
258 self.__class__.__name__, self.required_perms, func.__name__)
257
259
258 if self.check_permissions():
260 if self.check_permissions():
259 log.debug('Permission granted for %s', func.__name__)
261 log.debug('Permission granted for %s', func.__name__)
260
262
261 return func(*fargs, **fkwargs)
263 return func(*fargs, **fkwargs)
262
264
263 else:
265 else:
264 log.warning('Permission denied for %s', func.__name__)
266 log.warning('Permission denied for %s', func.__name__)
265 #redirect with forbidden ret code
267 #redirect with forbidden ret code
266 return abort(403)
268 return abort(403)
267
269
268
270
269
271
270 def check_permissions(self):
272 def check_permissions(self):
271 """Dummy function for overriding"""
273 """Dummy function for overriding"""
272 raise Exception('You have to write this function in child class')
274 raise Exception('You have to write this function in child class')
273
275
274 class HasPermissionAllDecorator(PermsDecorator):
276 class HasPermissionAllDecorator(PermsDecorator):
275 """Checks for access permission for all given predicates. All of them
277 """Checks for access permission for all given predicates. All of them
276 have to be meet in order to fulfill the request
278 have to be meet in order to fulfill the request
277 """
279 """
278
280
279 def check_permissions(self):
281 def check_permissions(self):
280 if self.required_perms.issubset(self.user_perms.get('global')):
282 if self.required_perms.issubset(self.user_perms.get('global')):
281 return True
283 return True
282 return False
284 return False
283
285
284
286
285 class HasPermissionAnyDecorator(PermsDecorator):
287 class HasPermissionAnyDecorator(PermsDecorator):
286 """Checks for access permission for any of given predicates. In order to
288 """Checks for access permission for any of given predicates. In order to
287 fulfill the request any of predicates must be meet
289 fulfill the request any of predicates must be meet
288 """
290 """
289
291
290 def check_permissions(self):
292 def check_permissions(self):
291 if self.required_perms.intersection(self.user_perms.get('global')):
293 if self.required_perms.intersection(self.user_perms.get('global')):
292 return True
294 return True
293 return False
295 return False
294
296
295 class HasRepoPermissionAllDecorator(PermsDecorator):
297 class HasRepoPermissionAllDecorator(PermsDecorator):
296 """Checks for access permission for all given predicates for specific
298 """Checks for access permission for all given predicates for specific
297 repository. All of them have to be meet in order to fulfill the request
299 repository. All of them have to be meet in order to fulfill the request
298 """
300 """
299
301
300 def check_permissions(self):
302 def check_permissions(self):
301 repo_name = get_repo_slug(request)
303 repo_name = get_repo_slug(request)
302 try:
304 try:
303 user_perms = set([self.user_perms['repositories'][repo_name]])
305 user_perms = set([self.user_perms['repositories'][repo_name]])
304 except KeyError:
306 except KeyError:
305 return False
307 return False
306 if self.required_perms.issubset(user_perms):
308 if self.required_perms.issubset(user_perms):
307 return True
309 return True
308 return False
310 return False
309
311
310
312
311 class HasRepoPermissionAnyDecorator(PermsDecorator):
313 class HasRepoPermissionAnyDecorator(PermsDecorator):
312 """Checks for access permission for any of given predicates for specific
314 """Checks for access permission for any of given predicates for specific
313 repository. In order to fulfill the request any of predicates must be meet
315 repository. In order to fulfill the request any of predicates must be meet
314 """
316 """
315
317
316 def check_permissions(self):
318 def check_permissions(self):
317 repo_name = get_repo_slug(request)
319 repo_name = get_repo_slug(request)
318
320
319 try:
321 try:
320 user_perms = set([self.user_perms['repositories'][repo_name]])
322 user_perms = set([self.user_perms['repositories'][repo_name]])
321 except KeyError:
323 except KeyError:
322 return False
324 return False
323 if self.required_perms.intersection(user_perms):
325 if self.required_perms.intersection(user_perms):
324 return True
326 return True
325 return False
327 return False
326 #===============================================================================
328 #===============================================================================
327 # CHECK FUNCTIONS
329 # CHECK FUNCTIONS
328 #===============================================================================
330 #===============================================================================
329
331
330 class PermsFunction(object):
332 class PermsFunction(object):
331 """Base function for other check functions"""
333 """Base function for other check functions"""
332
334
333 def __init__(self, *perms):
335 def __init__(self, *perms):
334 available_perms = config['available_permissions']
336 available_perms = config['available_permissions']
335
337
336 for perm in perms:
338 for perm in perms:
337 if perm not in available_perms:
339 if perm not in available_perms:
338 raise Exception("'%s' permission in not defined" % perm)
340 raise Exception("'%s' permission in not defined" % perm)
339 self.required_perms = set(perms)
341 self.required_perms = set(perms)
340 self.user_perms = None
342 self.user_perms = None
341 self.granted_for = ''
343 self.granted_for = ''
342 self.repo_name = None
344 self.repo_name = None
343
345
344 def __call__(self, check_Location=''):
346 def __call__(self, check_Location=''):
345 user = session.get('hg_app_user', False)
347 user = session.get('hg_app_user', False)
346 if not user:
348 if not user:
347 return False
349 return False
348 self.user_perms = user.permissions
350 self.user_perms = user.permissions
349 self.granted_for = user.username
351 self.granted_for = user.username
350 log.debug('checking %s %s', self.__class__.__name__, self.required_perms)
352 log.debug('checking %s %s', self.__class__.__name__, self.required_perms)
351
353
352 if self.check_permissions():
354 if self.check_permissions():
353 log.debug('Permission granted for %s @%s', self.granted_for,
355 log.debug('Permission granted for %s @%s', self.granted_for,
354 check_Location)
356 check_Location)
355 return True
357 return True
356
358
357 else:
359 else:
358 log.warning('Permission denied for %s @%s', self.granted_for,
360 log.warning('Permission denied for %s @%s', self.granted_for,
359 check_Location)
361 check_Location)
360 return False
362 return False
361
363
362 def check_permissions(self):
364 def check_permissions(self):
363 """Dummy function for overriding"""
365 """Dummy function for overriding"""
364 raise Exception('You have to write this function in child class')
366 raise Exception('You have to write this function in child class')
365
367
366 class HasPermissionAll(PermsFunction):
368 class HasPermissionAll(PermsFunction):
367 def check_permissions(self):
369 def check_permissions(self):
368 if self.required_perms.issubset(self.user_perms.get('global')):
370 if self.required_perms.issubset(self.user_perms.get('global')):
369 return True
371 return True
370 return False
372 return False
371
373
372 class HasPermissionAny(PermsFunction):
374 class HasPermissionAny(PermsFunction):
373 def check_permissions(self):
375 def check_permissions(self):
374 if self.required_perms.intersection(self.user_perms.get('global')):
376 if self.required_perms.intersection(self.user_perms.get('global')):
375 return True
377 return True
376 return False
378 return False
377
379
378 class HasRepoPermissionAll(PermsFunction):
380 class HasRepoPermissionAll(PermsFunction):
379
381
380 def __call__(self, repo_name=None, check_Location=''):
382 def __call__(self, repo_name=None, check_Location=''):
381 self.repo_name = repo_name
383 self.repo_name = repo_name
382 return super(HasRepoPermissionAll, self).__call__(check_Location)
384 return super(HasRepoPermissionAll, self).__call__(check_Location)
383
385
384 def check_permissions(self):
386 def check_permissions(self):
385 if not self.repo_name:
387 if not self.repo_name:
386 self.repo_name = get_repo_slug(request)
388 self.repo_name = get_repo_slug(request)
387
389
388 try:
390 try:
389 self.user_perms = set([self.user_perms['repositories']\
391 self.user_perms = set([self.user_perms['repositories']\
390 [self.repo_name]])
392 [self.repo_name]])
391 except KeyError:
393 except KeyError:
392 return False
394 return False
393 self.granted_for = self.repo_name
395 self.granted_for = self.repo_name
394 if self.required_perms.issubset(self.user_perms):
396 if self.required_perms.issubset(self.user_perms):
395 return True
397 return True
396 return False
398 return False
397
399
398 class HasRepoPermissionAny(PermsFunction):
400 class HasRepoPermissionAny(PermsFunction):
399
401
400 def __call__(self, repo_name=None, check_Location=''):
402 def __call__(self, repo_name=None, check_Location=''):
401 self.repo_name = repo_name
403 self.repo_name = repo_name
402 return super(HasRepoPermissionAny, self).__call__(check_Location)
404 return super(HasRepoPermissionAny, self).__call__(check_Location)
403
405
404 def check_permissions(self):
406 def check_permissions(self):
405 if not self.repo_name:
407 if not self.repo_name:
406 self.repo_name = get_repo_slug(request)
408 self.repo_name = get_repo_slug(request)
407
409
408 try:
410 try:
409 self.user_perms = set([self.user_perms['repositories']\
411 self.user_perms = set([self.user_perms['repositories']\
410 [self.repo_name]])
412 [self.repo_name]])
411 except KeyError:
413 except KeyError:
412 return False
414 return False
413 self.granted_for = self.repo_name
415 self.granted_for = self.repo_name
414 if self.required_perms.intersection(self.user_perms):
416 if self.required_perms.intersection(self.user_perms):
415 return True
417 return True
416 return False
418 return False
417
419
418 #===============================================================================
420 #===============================================================================
419 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
421 # SPECIAL VERSION TO HANDLE MIDDLEWARE AUTH
420 #===============================================================================
422 #===============================================================================
421
423
422 class HasPermissionAnyMiddleware(object):
424 class HasPermissionAnyMiddleware(object):
423 def __init__(self, *perms):
425 def __init__(self, *perms):
424 self.required_perms = set(perms)
426 self.required_perms = set(perms)
425
427
426 def __call__(self, user, repo_name):
428 def __call__(self, user, repo_name):
427 usr = AuthUser()
429 usr = AuthUser()
428 usr.user_id = user.user_id
430 usr.user_id = user.user_id
429 usr.username = user.username
431 usr.username = user.username
430 usr.is_admin = user.admin
432 usr.is_admin = user.admin
431
433
432 try:
434 try:
433 self.user_perms = set([fill_perms(usr)\
435 self.user_perms = set([fill_perms(usr)\
434 .permissions['repositories'][repo_name]])
436 .permissions['repositories'][repo_name]])
435 except:
437 except:
436 self.user_perms = set()
438 self.user_perms = set()
437 self.granted_for = ''
439 self.granted_for = ''
438 self.username = user.username
440 self.username = user.username
439 self.repo_name = repo_name
441 self.repo_name = repo_name
440 return self.check_permissions()
442 return self.check_permissions()
441
443
442 def check_permissions(self):
444 def check_permissions(self):
443 log.debug('checking mercurial protocol '
445 log.debug('checking mercurial protocol '
444 'permissions for user:%s repository:%s',
446 'permissions for user:%s repository:%s',
445 self.username, self.repo_name)
447 self.username, self.repo_name)
446 if self.required_perms.intersection(self.user_perms):
448 if self.required_perms.intersection(self.user_perms):
447 log.debug('permission granted')
449 log.debug('permission granted')
448 return True
450 return True
449 log.debug('permission denied')
451 log.debug('permission denied')
450 return False
452 return False
General Comments 0
You need to be logged in to leave comments. Login now