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