##// END OF EJS Templates
#49 Enabled anonymous access for web interface controllable from permissions pannel
marcink -
r673:dd532af2 beta
parent child Browse files
Show More
@@ -57,11 +57,12 b' class PermissionsController(BaseControll'
57 ('repository.write', _('Write'),),
57 ('repository.write', _('Write'),),
58 ('repository.admin', _('Admin'),)]
58 ('repository.admin', _('Admin'),)]
59 self.register_choices = [
59 self.register_choices = [
60 ('hg.register.none', 'disabled'),
60 ('hg.register.none',
61 _('disabled')),
61 ('hg.register.manual_activate',
62 ('hg.register.manual_activate',
62 _('allowed with manual account activation')),
63 _('allowed with manual account activation')),
63 ('hg.register.auto_activate',
64 ('hg.register.auto_activate',
64 _('allowed with automatic account activation')), ]
65 _('allowed with automatic account activation')), ]
65
66
66 self.create_choices = [('hg.create.none', _('Disabled')),
67 self.create_choices = [('hg.create.none', _('Disabled')),
67 ('hg.create.repository', _('Enabled'))]
68 ('hg.create.repository', _('Enabled'))]
@@ -142,8 +143,10 b' class PermissionsController(BaseControll'
142 c.create_choices = self.create_choices
143 c.create_choices = self.create_choices
143
144
144 if id == 'default':
145 if id == 'default':
145 defaults = {'_method':'put'}
146 default_user = UserModel().get_by_username('default')
146 for p in UserModel().get_by_username('default').user_perms:
147 defaults = {'_method':'put',
148 'anonymous':default_user.active}
149 for p in default_user.user_perms:
147 if p.permission.permission_name.startswith('repository.'):
150 if p.permission.permission_name.startswith('repository.'):
148 defaults['default_perm'] = p.permission.permission_name
151 defaults['default_perm'] = p.permission.permission_name
149
152
@@ -121,11 +121,15 b' class SettingsController(BaseController)'
121
121
122 try:
122 try:
123 hgsettings1 = self.sa.query(RhodeCodeSettings)\
123 hgsettings1 = self.sa.query(RhodeCodeSettings)\
124 .filter(RhodeCodeSettings.app_settings_name == 'title').one()
124 .filter(RhodeCodeSettings.app_settings_name \
125 == 'title').one()
126
125 hgsettings1.app_settings_value = form_result['rhodecode_title']
127 hgsettings1.app_settings_value = form_result['rhodecode_title']
126
128
127 hgsettings2 = self.sa.query(RhodeCodeSettings)\
129 hgsettings2 = self.sa.query(RhodeCodeSettings)\
128 .filter(RhodeCodeSettings.app_settings_name == 'realm').one()
130 .filter(RhodeCodeSettings.app_settings_name \
131 == 'realm').one()
132
129 hgsettings2.app_settings_value = form_result['rhodecode_realm']
133 hgsettings2.app_settings_value = form_result['rhodecode_realm']
130
134
131
135
@@ -45,26 +45,26 b' class UsersController(BaseController):'
45 # To properly map this controller, ensure your config/routing.py
45 # To properly map this controller, ensure your config/routing.py
46 # file has a resource setup:
46 # file has a resource setup:
47 # map.resource('user', 'users')
47 # map.resource('user', 'users')
48
48
49 @LoginRequired()
49 @LoginRequired()
50 @HasPermissionAllDecorator('hg.admin')
50 @HasPermissionAllDecorator('hg.admin')
51 def __before__(self):
51 def __before__(self):
52 c.admin_user = session.get('admin_user')
52 c.admin_user = session.get('admin_user')
53 c.admin_username = session.get('admin_username')
53 c.admin_username = session.get('admin_username')
54 super(UsersController, self).__before__()
54 super(UsersController, self).__before__()
55
55
56
56
57 def index(self, format='html'):
57 def index(self, format='html'):
58 """GET /users: All items in the collection"""
58 """GET /users: All items in the collection"""
59 # url('users')
59 # url('users')
60
60
61 c.users_list = self.sa.query(User).all()
61 c.users_list = self.sa.query(User).all()
62 return render('admin/users/users.html')
62 return render('admin/users/users.html')
63
63
64 def create(self):
64 def create(self):
65 """POST /users: Create a new item"""
65 """POST /users: Create a new item"""
66 # url('users')
66 # url('users')
67
67
68 user_model = UserModel()
68 user_model = UserModel()
69 login_form = UserForm()()
69 login_form = UserForm()()
70 try:
70 try:
@@ -79,13 +79,13 b' class UsersController(BaseController):'
79 defaults=errors.value,
79 defaults=errors.value,
80 errors=errors.error_dict or {},
80 errors=errors.error_dict or {},
81 prefix_error=False,
81 prefix_error=False,
82 encoding="UTF-8")
82 encoding="UTF-8")
83 except Exception:
83 except Exception:
84 log.error(traceback.format_exc())
84 log.error(traceback.format_exc())
85 h.flash(_('error occured during creation of user %s') \
85 h.flash(_('error occured during creation of user %s') \
86 % request.POST.get('username'), category='error')
86 % request.POST.get('username'), category='error')
87 return redirect(url('users'))
87 return redirect(url('users'))
88
88
89 def new(self, format='html'):
89 def new(self, format='html'):
90 """GET /users/new: Form to create a new item"""
90 """GET /users/new: Form to create a new item"""
91 # url('new_user')
91 # url('new_user')
@@ -101,7 +101,7 b' class UsersController(BaseController):'
101 # url('user', id=ID)
101 # url('user', id=ID)
102 user_model = UserModel()
102 user_model = UserModel()
103 c.user = user_model.get(id)
103 c.user = user_model.get(id)
104
104
105 _form = UserForm(edit=True, old_data={'user_id':id,
105 _form = UserForm(edit=True, old_data={'user_id':id,
106 'email':c.user.email})()
106 'email':c.user.email})()
107 form_result = {}
107 form_result = {}
@@ -109,21 +109,21 b' class UsersController(BaseController):'
109 form_result = _form.to_python(dict(request.POST))
109 form_result = _form.to_python(dict(request.POST))
110 user_model.update(id, form_result)
110 user_model.update(id, form_result)
111 h.flash(_('User updated succesfully'), category='success')
111 h.flash(_('User updated succesfully'), category='success')
112
112
113 except formencode.Invalid, errors:
113 except formencode.Invalid, errors:
114 return htmlfill.render(
114 return htmlfill.render(
115 render('admin/users/user_edit.html'),
115 render('admin/users/user_edit.html'),
116 defaults=errors.value,
116 defaults=errors.value,
117 errors=errors.error_dict or {},
117 errors=errors.error_dict or {},
118 prefix_error=False,
118 prefix_error=False,
119 encoding="UTF-8")
119 encoding="UTF-8")
120 except Exception:
120 except Exception:
121 log.error(traceback.format_exc())
121 log.error(traceback.format_exc())
122 h.flash(_('error occured during update of user %s') \
122 h.flash(_('error occured during update of user %s') \
123 % form_result.get('username'), category='error')
123 % form_result.get('username'), category='error')
124
124
125 return redirect(url('users'))
125 return redirect(url('users'))
126
126
127 def delete(self, id):
127 def delete(self, id):
128 """DELETE /users/id: Delete an existing item"""
128 """DELETE /users/id: Delete an existing item"""
129 # Forms posted to this method should contain a hidden field:
129 # Forms posted to this method should contain a hidden field:
@@ -140,14 +140,14 b' class UsersController(BaseController):'
140 h.flash(str(e), category='warning')
140 h.flash(str(e), category='warning')
141 except Exception:
141 except Exception:
142 h.flash(_('An error occured during deletion of user'),
142 h.flash(_('An error occured during deletion of user'),
143 category='error')
143 category='error')
144 return redirect(url('users'))
144 return redirect(url('users'))
145
145
146 def show(self, id, format='html'):
146 def show(self, id, format='html'):
147 """GET /users/id: Show a specific item"""
147 """GET /users/id: Show a specific item"""
148 # url('user', id=ID)
148 # url('user', id=ID)
149
149
150
150
151 def edit(self, id, format='html'):
151 def edit(self, id, format='html'):
152 """GET /users/id/edit: Form to edit an existing item"""
152 """GET /users/id/edit: Form to edit an existing item"""
153 # url('edit_user', id=ID)
153 # url('edit_user', id=ID)
@@ -155,14 +155,13 b' class UsersController(BaseController):'
155 if not c.user:
155 if not c.user:
156 return redirect(url('users'))
156 return redirect(url('users'))
157 if c.user.username == 'default':
157 if c.user.username == 'default':
158 h.flash(_("You can't edit this user since it's"
158 h.flash(_("You can't edit this user"), category='warning')
159 " crucial for entire application"), category='warning')
160 return redirect(url('users'))
159 return redirect(url('users'))
161
160
162 defaults = c.user.__dict__
161 defaults = c.user.__dict__
163 return htmlfill.render(
162 return htmlfill.render(
164 render('admin/users/user_edit.html'),
163 render('admin/users/user_edit.html'),
165 defaults=defaults,
164 defaults=defaults,
166 encoding="UTF-8",
165 encoding="UTF-8",
167 force_defaults=False
166 force_defaults=False
168 )
167 )
@@ -46,7 +46,9 b' class LoginController(BaseController):'
46 #redirect if already logged in
46 #redirect if already logged in
47 c.came_from = request.GET.get('came_from', None)
47 c.came_from = request.GET.get('came_from', None)
48
48
49 if c.rhodecode_user.is_authenticated:
49 if c.rhodecode_user.is_authenticated \
50 and c.rhodecode_user.username != 'default':
51
50 return redirect(url('home'))
52 return redirect(url('home'))
51
53
52 if request.POST:
54 if request.POST:
@@ -26,15 +26,16 b' from pylons import config, session, url,'
26 from pylons.controllers.util import abort, redirect
26 from pylons.controllers.util import abort, redirect
27 from rhodecode.lib.utils import get_repo_slug
27 from rhodecode.lib.utils import get_repo_slug
28 from rhodecode.model import meta
28 from rhodecode.model import meta
29 from rhodecode.model.user import UserModel
29 from rhodecode.model.caching_query import FromCache
30 from rhodecode.model.caching_query import FromCache
30 from rhodecode.model.db import User, RepoToPerm, Repository, Permission, \
31 from rhodecode.model.db import User, RepoToPerm, Repository, Permission, \
31 UserToPerm
32 UserToPerm
32 import bcrypt
33 import bcrypt
33 from decorator import decorator
34 from decorator import decorator
34 import logging
35 import logging
35 import random
36 import random
36
37
37 log = logging.getLogger(__name__)
38 log = logging.getLogger(__name__)
38
39
39 class PasswordGenerator(object):
40 class PasswordGenerator(object):
40 """This is a simple class for generating password from
41 """This is a simple class for generating password from
@@ -53,7 +54,7 b' class PasswordGenerator(object):'
53 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
54 ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
54 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM#[6]
55 ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM#[6]
55 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM#[7]
56 ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM#[7]
56
57
57 def __init__(self, passwd=''):
58 def __init__(self, passwd=''):
58 self.passwd = passwd
59 self.passwd = passwd
59
60
@@ -61,20 +62,19 b' class PasswordGenerator(object):'
61 self.passwd = ''.join([random.choice(type) for _ in xrange(len)])
62 self.passwd = ''.join([random.choice(type) for _ in xrange(len)])
62 return self.passwd
63 return self.passwd
63
64
64
65
65 def get_crypt_password(password):
66 def get_crypt_password(password):
66 """Cryptographic function used for password hashing based on sha1
67 """Cryptographic function used for password hashing based on sha1
67 :param password: password to hash
68 :param password: password to hash
68 """
69 """
69 return bcrypt.hashpw(password, bcrypt.gensalt(10))
70 return bcrypt.hashpw(password, bcrypt.gensalt(10))
70
71
71 def check_password(password, hashed):
72 def check_password(password, hashed):
72 return bcrypt.hashpw(password, hashed) == hashed
73 return bcrypt.hashpw(password, hashed) == hashed
73
74
74 def authfunc(environ, username, password):
75 def authfunc(environ, username, password):
75 from rhodecode.model.user import UserModel
76 user = UserModel().get_by_username(username, cache=False)
76 user = UserModel().get_by_username(username, cache=False)
77
77
78 if user:
78 if user:
79 if user.active:
79 if user.active:
80 if user.username == username and check_password(password, user.password):
80 if user.username == username and check_password(password, user.password):
@@ -82,7 +82,7 b' def authfunc(environ, username, password'
82 return True
82 return True
83 else:
83 else:
84 log.error('user %s is disabled', username)
84 log.error('user %s is disabled', username)
85
85
86 return False
86 return False
87
87
88 class AuthUser(object):
88 class AuthUser(object):
@@ -99,6 +99,8 b' class AuthUser(object):'
99 self.is_admin = False
99 self.is_admin = False
100 self.permissions = {}
100 self.permissions = {}
101
101
102 def __repr__(self):
103 return "<AuthUser('id:%s:%s')>" % (self.user_id, self.username)
102
104
103 def set_available_permissions(config):
105 def set_available_permissions(config):
104 """
106 """
@@ -116,85 +118,56 b' def set_available_permissions(config):'
116 pass
118 pass
117 finally:
119 finally:
118 meta.Session.remove()
120 meta.Session.remove()
119
121
120 config['available_permissions'] = [x.permission_name for x in all_perms]
122 config['available_permissions'] = [x.permission_name for x in all_perms]
121
123
122 def set_base_path(config):
124 def set_base_path(config):
123 config['base_path'] = config['pylons.app_globals'].base_path
125 config['base_path'] = config['pylons.app_globals'].base_path
124
126
125 def fill_data(user):
127
126 """
127 Fills user data with those from database and log out user if not present
128 in database
129 :param user:
130 """
131 sa = meta.Session()
132 try:
133 dbuser = sa.query(User)\
134 .options(FromCache('sql_cache_short', 'getuser_%s' % user.user_id))\
135 .get(user.user_id)
136 except:
137 pass
138 finally:
139 meta.Session.remove()
140
141 if dbuser:
142 user.username = dbuser.username
143 user.is_admin = dbuser.admin
144 user.name = dbuser.name
145 user.lastname = dbuser.lastname
146 user.email = dbuser.email
147 else:
148 user.is_authenticated = False
149
150
151 return user
152
153 def fill_perms(user):
128 def fill_perms(user):
154 """
129 """
155 Fills user permission attribute with permissions taken from database
130 Fills user permission attribute with permissions taken from database
156 :param user:
131 :param user:
157 """
132 """
158
133
159 sa = meta.Session()
134 sa = meta.Session()
160 user.permissions['repositories'] = {}
135 user.permissions['repositories'] = {}
161 user.permissions['global'] = set()
136 user.permissions['global'] = set()
162
137
163 #===========================================================================
138 #===========================================================================
164 # fetch default permissions
139 # fetch default permissions
165 #===========================================================================
140 #===========================================================================
166 default_user = sa.query(User)\
141 default_user = UserModel(sa).get_by_username('default', cache=True)
167 .options(FromCache('sql_cache_short', 'getuser_%s' % 'default'))\
142
168 .filter(User.username == 'default').scalar()
169
170 default_perms = sa.query(RepoToPerm, Repository, Permission)\
143 default_perms = sa.query(RepoToPerm, Repository, Permission)\
171 .join((Repository, RepoToPerm.repository_id == Repository.repo_id))\
144 .join((Repository, RepoToPerm.repository_id == Repository.repo_id))\
172 .join((Permission, RepoToPerm.permission_id == Permission.permission_id))\
145 .join((Permission, RepoToPerm.permission_id == Permission.permission_id))\
173 .filter(RepoToPerm.user == default_user).all()
146 .filter(RepoToPerm.user == default_user).all()
174
147
175 if user.is_admin:
148 if user.is_admin:
176 #=======================================================================
149 #=======================================================================
177 # #admin have all default rights set to admin
150 # #admin have all default rights set to admin
178 #=======================================================================
151 #=======================================================================
179 user.permissions['global'].add('hg.admin')
152 user.permissions['global'].add('hg.admin')
180
153
181 for perm in default_perms:
154 for perm in default_perms:
182 p = 'repository.admin'
155 p = 'repository.admin'
183 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
156 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
184
157
185 else:
158 else:
186 #=======================================================================
159 #=======================================================================
187 # set default permissions
160 # set default permissions
188 #=======================================================================
161 #=======================================================================
189
162
190 #default global
163 #default global
191 default_global_perms = sa.query(UserToPerm)\
164 default_global_perms = sa.query(UserToPerm)\
192 .filter(UserToPerm.user == sa.query(User).filter(User.username ==
165 .filter(UserToPerm.user == sa.query(User).filter(User.username ==
193 'default').one())
166 'default').one())
194
167
195 for perm in default_global_perms:
168 for perm in default_global_perms:
196 user.permissions['global'].add(perm.permission.permission_name)
169 user.permissions['global'].add(perm.permission.permission_name)
197
170
198 #default repositories
171 #default repositories
199 for perm in default_perms:
172 for perm in default_perms:
200 if perm.Repository.private and not perm.Repository.user_id == user.user_id:
173 if perm.Repository.private and not perm.Repository.user_id == user.user_id:
@@ -205,9 +178,9 b' def fill_perms(user):'
205 p = 'repository.admin'
178 p = 'repository.admin'
206 else:
179 else:
207 p = perm.Permission.permission_name
180 p = perm.Permission.permission_name
208
181
209 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
182 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
210
183
211 #=======================================================================
184 #=======================================================================
212 # #overwrite default with user permissions if any
185 # #overwrite default with user permissions if any
213 #=======================================================================
186 #=======================================================================
@@ -215,38 +188,52 b' def fill_perms(user):'
215 .join((Repository, RepoToPerm.repository_id == Repository.repo_id))\
188 .join((Repository, RepoToPerm.repository_id == Repository.repo_id))\
216 .join((Permission, RepoToPerm.permission_id == Permission.permission_id))\
189 .join((Permission, RepoToPerm.permission_id == Permission.permission_id))\
217 .filter(RepoToPerm.user_id == user.user_id).all()
190 .filter(RepoToPerm.user_id == user.user_id).all()
218
191
219 for perm in user_perms:
192 for perm in user_perms:
220 if perm.Repository.user_id == user.user_id:#set admin if owner
193 if perm.Repository.user_id == user.user_id:#set admin if owner
221 p = 'repository.admin'
194 p = 'repository.admin'
222 else:
195 else:
223 p = perm.Permission.permission_name
196 p = perm.Permission.permission_name
224 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
197 user.permissions['repositories'][perm.RepoToPerm.repository.repo_name] = p
225 meta.Session.remove()
198 meta.Session.remove()
226 return user
199 return user
227
200
228 def get_user(session):
201 def get_user(session):
229 """
202 """
230 Gets user from session, and wraps permissions into user
203 Gets user from session, and wraps permissions into user
231 :param session:
204 :param session:
232 """
205 """
233 user = session.get('rhodecode_user', AuthUser())
206 user = session.get('rhodecode_user', AuthUser())
207
208
209 #if the user is not logged in we check for anonymous access
210 #if user is logged and it's a default user check if we still have anonymous
211 #access enabled
212 if user.user_id is None or user.username == 'default':
213 anonymous_user = UserModel().get_by_username('default', cache=True)
214 if anonymous_user.active is True:
215 #then we set this user is logged in
216 user.is_authenticated = True
217 else:
218 user.is_authenticated = False
219
234 if user.is_authenticated:
220 if user.is_authenticated:
235 user = fill_data(user)
221 user = UserModel().fill_data(user)
222
236 user = fill_perms(user)
223 user = fill_perms(user)
237 session['rhodecode_user'] = user
224 session['rhodecode_user'] = user
238 session.save()
225 session.save()
239 return user
226 return user
240
227
241 #===============================================================================
228 #===============================================================================
242 # CHECK DECORATORS
229 # CHECK DECORATORS
243 #===============================================================================
230 #===============================================================================
244 class LoginRequired(object):
231 class LoginRequired(object):
245 """Must be logged in to execute this function else redirect to login page"""
232 """Must be logged in to execute this function else redirect to login page"""
246
233
247 def __call__(self, func):
234 def __call__(self, func):
248 return decorator(self.__wrapper, func)
235 return decorator(self.__wrapper, func)
249
236
250 def __wrapper(self, func, *fargs, **fkwargs):
237 def __wrapper(self, func, *fargs, **fkwargs):
251 user = session.get('rhodecode_user', AuthUser())
238 user = session.get('rhodecode_user', AuthUser())
252 log.debug('Checking login required for user:%s', user.username)
239 log.debug('Checking login required for user:%s', user.username)
@@ -255,21 +242,21 b' class LoginRequired(object):'
255 return func(*fargs, **fkwargs)
242 return func(*fargs, **fkwargs)
256 else:
243 else:
257 log.warn('user %s not authenticated', user.username)
244 log.warn('user %s not authenticated', user.username)
258
245
259 p = ''
246 p = ''
260 if request.environ.get('SCRIPT_NAME') != '/':
247 if request.environ.get('SCRIPT_NAME') != '/':
261 p += request.environ.get('SCRIPT_NAME')
248 p += request.environ.get('SCRIPT_NAME')
262
249
263 p += request.environ.get('PATH_INFO')
250 p += request.environ.get('PATH_INFO')
264 if request.environ.get('QUERY_STRING'):
251 if request.environ.get('QUERY_STRING'):
265 p += '?' + request.environ.get('QUERY_STRING')
252 p += '?' + request.environ.get('QUERY_STRING')
266
253
267 log.debug('redirecting to login page with %s', p)
254 log.debug('redirecting to login page with %s', p)
268 return redirect(url('login_home', came_from=p))
255 return redirect(url('login_home', came_from=p))
269
256
270 class PermsDecorator(object):
257 class PermsDecorator(object):
271 """Base class for decorators"""
258 """Base class for decorators"""
272
259
273 def __init__(self, *required_perms):
260 def __init__(self, *required_perms):
274 available_perms = config['available_permissions']
261 available_perms = config['available_permissions']
275 for perm in required_perms:
262 for perm in required_perms:
@@ -277,32 +264,33 b' class PermsDecorator(object):'
277 raise Exception("'%s' permission is not defined" % perm)
264 raise Exception("'%s' permission is not defined" % perm)
278 self.required_perms = set(required_perms)
265 self.required_perms = set(required_perms)
279 self.user_perms = None
266 self.user_perms = None
280
267
281 def __call__(self, func):
268 def __call__(self, func):
282 return decorator(self.__wrapper, func)
269 return decorator(self.__wrapper, func)
283
270
284
271
285 def __wrapper(self, func, *fargs, **fkwargs):
272 def __wrapper(self, func, *fargs, **fkwargs):
286 # _wrapper.__name__ = func.__name__
273 # _wrapper.__name__ = func.__name__
287 # _wrapper.__dict__.update(func.__dict__)
274 # _wrapper.__dict__.update(func.__dict__)
288 # _wrapper.__doc__ = func.__doc__
275 # _wrapper.__doc__ = func.__doc__
276 self.user = session.get('rhodecode_user', AuthUser())
277 self.user_perms = self.user.permissions
278 log.debug('checking %s permissions %s for %s %s',
279 self.__class__.__name__, self.required_perms, func.__name__,
280 self.user)
289
281
290 self.user_perms = session.get('rhodecode_user', AuthUser()).permissions
291 log.debug('checking %s permissions %s for %s',
292 self.__class__.__name__, self.required_perms, func.__name__)
293
294 if self.check_permissions():
282 if self.check_permissions():
295 log.debug('Permission granted for %s', func.__name__)
283 log.debug('Permission granted for %s %s', func.__name__, self.user)
296
284
297 return func(*fargs, **fkwargs)
285 return func(*fargs, **fkwargs)
298
286
299 else:
287 else:
300 log.warning('Permission denied for %s', func.__name__)
288 log.warning('Permission denied for %s %s', func.__name__, self.user)
301 #redirect with forbidden ret code
289 #redirect with forbidden ret code
302 return abort(403)
290 return abort(403)
303
291
304
292
305
293
306 def check_permissions(self):
294 def check_permissions(self):
307 """Dummy function for overriding"""
295 """Dummy function for overriding"""
308 raise Exception('You have to write this function in child class')
296 raise Exception('You have to write this function in child class')
@@ -311,18 +299,18 b' class HasPermissionAllDecorator(PermsDec'
311 """Checks for access permission for all given predicates. All of them
299 """Checks for access permission for all given predicates. All of them
312 have to be meet in order to fulfill the request
300 have to be meet in order to fulfill the request
313 """
301 """
314
302
315 def check_permissions(self):
303 def check_permissions(self):
316 if self.required_perms.issubset(self.user_perms.get('global')):
304 if self.required_perms.issubset(self.user_perms.get('global')):
317 return True
305 return True
318 return False
306 return False
319
307
320
308
321 class HasPermissionAnyDecorator(PermsDecorator):
309 class HasPermissionAnyDecorator(PermsDecorator):
322 """Checks for access permission for any of given predicates. In order to
310 """Checks for access permission for any of given predicates. In order to
323 fulfill the request any of predicates must be meet
311 fulfill the request any of predicates must be meet
324 """
312 """
325
313
326 def check_permissions(self):
314 def check_permissions(self):
327 if self.required_perms.intersection(self.user_perms.get('global')):
315 if self.required_perms.intersection(self.user_perms.get('global')):
328 return True
316 return True
@@ -332,7 +320,7 b' class HasRepoPermissionAllDecorator(Perm'
332 """Checks for access permission for all given predicates for specific
320 """Checks for access permission for all given predicates for specific
333 repository. All of them have to be meet in order to fulfill the request
321 repository. All of them have to be meet in order to fulfill the request
334 """
322 """
335
323
336 def check_permissions(self):
324 def check_permissions(self):
337 repo_name = get_repo_slug(request)
325 repo_name = get_repo_slug(request)
338 try:
326 try:
@@ -342,16 +330,16 b' class HasRepoPermissionAllDecorator(Perm'
342 if self.required_perms.issubset(user_perms):
330 if self.required_perms.issubset(user_perms):
343 return True
331 return True
344 return False
332 return False
345
333
346
334
347 class HasRepoPermissionAnyDecorator(PermsDecorator):
335 class HasRepoPermissionAnyDecorator(PermsDecorator):
348 """Checks for access permission for any of given predicates for specific
336 """Checks for access permission for any of given predicates for specific
349 repository. In order to fulfill the request any of predicates must be meet
337 repository. In order to fulfill the request any of predicates must be meet
350 """
338 """
351
339
352 def check_permissions(self):
340 def check_permissions(self):
353 repo_name = get_repo_slug(request)
341 repo_name = get_repo_slug(request)
354
342
355 try:
343 try:
356 user_perms = set([self.user_perms['repositories'][repo_name]])
344 user_perms = set([self.user_perms['repositories'][repo_name]])
357 except KeyError:
345 except KeyError:
@@ -365,10 +353,10 b' class HasRepoPermissionAnyDecorator(Perm'
365
353
366 class PermsFunction(object):
354 class PermsFunction(object):
367 """Base function for other check functions"""
355 """Base function for other check functions"""
368
356
369 def __init__(self, *perms):
357 def __init__(self, *perms):
370 available_perms = config['available_permissions']
358 available_perms = config['available_permissions']
371
359
372 for perm in perms:
360 for perm in perms:
373 if perm not in available_perms:
361 if perm not in available_perms:
374 raise Exception("'%s' permission in not defined" % perm)
362 raise Exception("'%s' permission in not defined" % perm)
@@ -376,29 +364,30 b' class PermsFunction(object):'
376 self.user_perms = None
364 self.user_perms = None
377 self.granted_for = ''
365 self.granted_for = ''
378 self.repo_name = None
366 self.repo_name = None
379
367
380 def __call__(self, check_Location=''):
368 def __call__(self, check_Location=''):
381 user = session.get('rhodecode_user', False)
369 user = session.get('rhodecode_user', False)
382 if not user:
370 if not user:
383 return False
371 return False
384 self.user_perms = user.permissions
372 self.user_perms = user.permissions
385 self.granted_for = user.username
373 self.granted_for = user.username
386 log.debug('checking %s %s', self.__class__.__name__, self.required_perms)
374 log.debug('checking %s %s %s', self.__class__.__name__,
387
375 self.required_perms, user)
376
388 if self.check_permissions():
377 if self.check_permissions():
389 log.debug('Permission granted for %s @%s', self.granted_for,
378 log.debug('Permission granted for %s @ %s %s', self.granted_for,
390 check_Location)
379 check_Location, user)
391 return True
380 return True
392
381
393 else:
382 else:
394 log.warning('Permission denied for %s @%s', self.granted_for,
383 log.warning('Permission denied for %s @ %s %s', self.granted_for,
395 check_Location)
384 check_Location, user)
396 return False
385 return False
397
386
398 def check_permissions(self):
387 def check_permissions(self):
399 """Dummy function for overriding"""
388 """Dummy function for overriding"""
400 raise Exception('You have to write this function in child class')
389 raise Exception('You have to write this function in child class')
401
390
402 class HasPermissionAll(PermsFunction):
391 class HasPermissionAll(PermsFunction):
403 def check_permissions(self):
392 def check_permissions(self):
404 if self.required_perms.issubset(self.user_perms.get('global')):
393 if self.required_perms.issubset(self.user_perms.get('global')):
@@ -412,11 +401,11 b' class HasPermissionAny(PermsFunction):'
412 return False
401 return False
413
402
414 class HasRepoPermissionAll(PermsFunction):
403 class HasRepoPermissionAll(PermsFunction):
415
404
416 def __call__(self, repo_name=None, check_Location=''):
405 def __call__(self, repo_name=None, check_Location=''):
417 self.repo_name = repo_name
406 self.repo_name = repo_name
418 return super(HasRepoPermissionAll, self).__call__(check_Location)
407 return super(HasRepoPermissionAll, self).__call__(check_Location)
419
408
420 def check_permissions(self):
409 def check_permissions(self):
421 if not self.repo_name:
410 if not self.repo_name:
422 self.repo_name = get_repo_slug(request)
411 self.repo_name = get_repo_slug(request)
@@ -426,17 +415,17 b' class HasRepoPermissionAll(PermsFunction'
426 [self.repo_name]])
415 [self.repo_name]])
427 except KeyError:
416 except KeyError:
428 return False
417 return False
429 self.granted_for = self.repo_name
418 self.granted_for = self.repo_name
430 if self.required_perms.issubset(self.user_perms):
419 if self.required_perms.issubset(self.user_perms):
431 return True
420 return True
432 return False
421 return False
433
422
434 class HasRepoPermissionAny(PermsFunction):
423 class HasRepoPermissionAny(PermsFunction):
435
424
436 def __call__(self, repo_name=None, check_Location=''):
425 def __call__(self, repo_name=None, check_Location=''):
437 self.repo_name = repo_name
426 self.repo_name = repo_name
438 return super(HasRepoPermissionAny, self).__call__(check_Location)
427 return super(HasRepoPermissionAny, self).__call__(check_Location)
439
428
440 def check_permissions(self):
429 def check_permissions(self):
441 if not self.repo_name:
430 if not self.repo_name:
442 self.repo_name = get_repo_slug(request)
431 self.repo_name = get_repo_slug(request)
@@ -458,13 +447,13 b' class HasRepoPermissionAny(PermsFunction'
458 class HasPermissionAnyMiddleware(object):
447 class HasPermissionAnyMiddleware(object):
459 def __init__(self, *perms):
448 def __init__(self, *perms):
460 self.required_perms = set(perms)
449 self.required_perms = set(perms)
461
450
462 def __call__(self, user, repo_name):
451 def __call__(self, user, repo_name):
463 usr = AuthUser()
452 usr = AuthUser()
464 usr.user_id = user.user_id
453 usr.user_id = user.user_id
465 usr.username = user.username
454 usr.username = user.username
466 usr.is_admin = user.admin
455 usr.is_admin = user.admin
467
456
468 try:
457 try:
469 self.user_perms = set([fill_perms(usr)\
458 self.user_perms = set([fill_perms(usr)\
470 .permissions['repositories'][repo_name]])
459 .permissions['repositories'][repo_name]])
@@ -472,9 +461,9 b' class HasPermissionAnyMiddleware(object)'
472 self.user_perms = set()
461 self.user_perms = set()
473 self.granted_for = ''
462 self.granted_for = ''
474 self.username = user.username
463 self.username = user.username
475 self.repo_name = repo_name
464 self.repo_name = repo_name
476 return self.check_permissions()
465 return self.check_permissions()
477
466
478 def check_permissions(self):
467 def check_permissions(self):
479 log.debug('checking mercurial protocol '
468 log.debug('checking mercurial protocol '
480 'permissions for user:%s repository:%s',
469 'permissions for user:%s repository:%s',
@@ -138,17 +138,17 b' class DbManage(object):'
138 hooks2.ui_section = 'hooks'
138 hooks2.ui_section = 'hooks'
139 hooks2.ui_key = 'changegroup.repo_size'
139 hooks2.ui_key = 'changegroup.repo_size'
140 hooks2.ui_value = 'python:rhodecode.lib.hooks.repo_size'
140 hooks2.ui_value = 'python:rhodecode.lib.hooks.repo_size'
141
141
142 hooks3 = RhodeCodeUi()
142 hooks3 = RhodeCodeUi()
143 hooks3.ui_section = 'hooks'
143 hooks3.ui_section = 'hooks'
144 hooks3.ui_key = 'pretxnchangegroup.push_logger'
144 hooks3.ui_key = 'pretxnchangegroup.push_logger'
145 hooks3.ui_value = 'python:rhodecode.lib.hooks.log_push_action'
145 hooks3.ui_value = 'python:rhodecode.lib.hooks.log_push_action'
146
146
147 hooks4 = RhodeCodeUi()
147 hooks4 = RhodeCodeUi()
148 hooks4.ui_section = 'hooks'
148 hooks4.ui_section = 'hooks'
149 hooks4.ui_key = 'preoutgoing.pull_logger'
149 hooks4.ui_key = 'preoutgoing.pull_logger'
150 hooks4.ui_value = 'python:rhodecode.lib.hooks.log_pull_action'
150 hooks4.ui_value = 'python:rhodecode.lib.hooks.log_pull_action'
151
151
152
152
153 web1 = RhodeCodeUi()
153 web1 = RhodeCodeUi()
154 web1.ui_section = 'web'
154 web1.ui_section = 'web'
@@ -227,9 +227,9 b' class DbManage(object):'
227 def_user = User()
227 def_user = User()
228 def_user.username = 'default'
228 def_user.username = 'default'
229 def_user.password = get_crypt_password(str(uuid.uuid1())[:8])
229 def_user.password = get_crypt_password(str(uuid.uuid1())[:8])
230 def_user.name = 'default'
230 def_user.name = 'Anonymous'
231 def_user.lastname = 'default'
231 def_user.lastname = 'User'
232 def_user.email = 'default@default.com'
232 def_user.email = 'anonymous@rhodecode.org'
233 def_user.admin = False
233 def_user.admin = False
234 def_user.active = False
234 def_user.active = False
235 try:
235 try:
@@ -358,6 +358,7 b' def DefaultPermissionsForm(perms_choices'
358 allow_extra_fields = True
358 allow_extra_fields = True
359 filter_extra_fields = True
359 filter_extra_fields = True
360 overwrite_default = OneOf(['true', 'false'], if_missing='false')
360 overwrite_default = OneOf(['true', 'false'], if_missing='false')
361 anonymous = OneOf(['True', 'False'], if_missing=False)
361 default_perm = OneOf(perms_choices)
362 default_perm = OneOf(perms_choices)
362 default_register = OneOf(register_choices)
363 default_register = OneOf(register_choices)
363 default_create = OneOf(create_choices)
364 default_create = OneOf(create_choices)
@@ -59,30 +59,41 b' class PermissionModel(object):'
59 .filter(User.username == form_result['perm_user_name']).scalar()
59 .filter(User.username == form_result['perm_user_name']).scalar()
60 u2p = self.sa.query(UserToPerm).filter(UserToPerm.user == perm_user).all()
60 u2p = self.sa.query(UserToPerm).filter(UserToPerm.user == perm_user).all()
61 if len(u2p) != 3:
61 if len(u2p) != 3:
62 raise Exception('There is more than 3 defined'
62 raise Exception('Defined: %s should be 3 permissions for default'
63 ' permissions for default user. This should not happen please verify'
63 ' user. This should not happen please verify'
64 ' your database')
64 ' your database' % len(u2p))
65
65
66 try:
66 try:
67 #stage 1 change defaults
67 #stage 1 change defaults
68 for p in u2p:
68 for p in u2p:
69 if p.permission.permission_name.startswith('repository.'):
69 if p.permission.permission_name.startswith('repository.'):
70 p.permission = self.get_permission_by_name(form_result['default_perm'])
70 p.permission = self.get_permission_by_name(
71 form_result['default_perm'])
71 self.sa.add(p)
72 self.sa.add(p)
72
73
73 if p.permission.permission_name.startswith('hg.register.'):
74 if p.permission.permission_name.startswith('hg.register.'):
74 p.permission = self.get_permission_by_name(form_result['default_register'])
75 p.permission = self.get_permission_by_name(
76 form_result['default_register'])
75 self.sa.add(p)
77 self.sa.add(p)
76
78
77 if p.permission.permission_name.startswith('hg.create.'):
79 if p.permission.permission_name.startswith('hg.create.'):
78 p.permission = self.get_permission_by_name(form_result['default_create'])
80 p.permission = self.get_permission_by_name(
81 form_result['default_create'])
79 self.sa.add(p)
82 self.sa.add(p)
80 #stage 2 update all default permissions for repos if checked
83 #stage 2 update all default permissions for repos if checked
81 if form_result['overwrite_default'] == 'true':
84 if form_result['overwrite_default'] == 'true':
82 for r2p in self.sa.query(RepoToPerm).filter(RepoToPerm.user == perm_user).all():
85 for r2p in self.sa.query(RepoToPerm)\
83 r2p.permission = self.get_permission_by_name(form_result['default_perm'])
86 .filter(RepoToPerm.user == perm_user).all():
87 r2p.permission = self.get_permission_by_name(
88 form_result['default_perm'])
84 self.sa.add(r2p)
89 self.sa.add(r2p)
85
90
91 #stage 3 set anonymous access
92 if perm_user.username == 'default':
93 perm_user.active = bool(form_result['anonymous'])
94 self.sa.add(perm_user)
95
96
86 self.sa.commit()
97 self.sa.commit()
87 except:
98 except:
88 log.error(traceback.format_exc())
99 log.error(traceback.format_exc())
@@ -143,3 +143,24 b' class UserModel(object):'
143 def reset_password(self, data):
143 def reset_password(self, data):
144 from rhodecode.lib.celerylib import tasks, run_task
144 from rhodecode.lib.celerylib import tasks, run_task
145 run_task(tasks.reset_user_password, data['email'])
145 run_task(tasks.reset_user_password, data['email'])
146
147
148 def fill_data(self, user):
149 """
150 Fills user data with those from database and log out user if not
151 present in database
152 :param user:
153 """
154 log.debug('filling auth user data')
155 try:
156 dbuser = self.get(user.user_id)
157 user.username = dbuser.username
158 user.is_admin = dbuser.admin
159 user.name = dbuser.name
160 user.lastname = dbuser.lastname
161 user.email = dbuser.email
162 except:
163 log.error(traceback.format_exc())
164 user.is_authenticated = False
165
166 return user
@@ -2096,7 +2096,7 b' border:1px solid #666;'
2096 clear:both;
2096 clear:both;
2097 overflow:hidden;
2097 overflow:hidden;
2098 margin:0;
2098 margin:0;
2099 padding:2px 0;
2099 padding:2px 2px;
2100 }
2100 }
2101
2101
2102 #content div.box div.form div.fields div.field div.checkboxes div.checkbox input,#content div.box div.form div.fields div.field div.radios div.radio input {
2102 #content div.box div.form div.fields div.field div.checkboxes div.checkbox input,#content div.box div.form div.fields div.field div.radios div.radio input {
@@ -26,7 +26,16 b''
26 <div class="form">
26 <div class="form">
27 <!-- fields -->
27 <!-- fields -->
28 <div class="fields">
28 <div class="fields">
29
29 <div class="field">
30 <div class="label label-checkbox">
31 <label for="anonymous">${_('Anonymous access')}:</label>
32 </div>
33 <div class="checkboxes">
34 <div class="checkbox">
35 ${h.checkbox('anonymous',True)}
36 </div>
37 </div>
38 </div>
30 <div class="field">
39 <div class="field">
31 <div class="label">
40 <div class="label">
32 <label for="default_perm">${_('Repository permission')}:</label>
41 <label for="default_perm">${_('Repository permission')}:</label>
@@ -20,12 +20,22 b''
20 <div class="gravatar">
20 <div class="gravatar">
21 <img alt="gravatar" src="${h.gravatar_url(c.rhodecode_user.email,24)}" />
21 <img alt="gravatar" src="${h.gravatar_url(c.rhodecode_user.email,24)}" />
22 </div>
22 </div>
23 %if c.rhodecode_user.username == 'default':
24 <div class="account">
25 ${h.link_to('%s %s'%(c.rhodecode_user.name,c.rhodecode_user.lastname),h.url('#'))}<br/>
26 ${h.link_to(c.rhodecode_user.username,h.url('#'))}
27 </div>
28 </li>
29 <li class="last highlight">${h.link_to(u'Login',h.url('login_home'))}</li>
30 %else:
31
23 <div class="account">
32 <div class="account">
24 ${h.link_to('%s %s'%(c.rhodecode_user.name,c.rhodecode_user.lastname),h.url('admin_settings_my_account'))}<br/>
33 ${h.link_to('%s %s'%(c.rhodecode_user.name,c.rhodecode_user.lastname),h.url('admin_settings_my_account'))}<br/>
25 ${h.link_to(c.rhodecode_user.username,h.url('admin_settings_my_account'))}
34 ${h.link_to(c.rhodecode_user.username,h.url('admin_settings_my_account'))}
26 </div>
35 </div>
27 </li>
36 </li>
28 <li class="last highlight">${h.link_to(u'Logout',h.url('logout_home'))}</li>
37 <li class="last highlight">${h.link_to(u'Logout',h.url('logout_home'))}</li>
38 %endif
29 </ul>
39 </ul>
30 <!-- end user -->
40 <!-- end user -->
31 <div id="header-inner" class="title top-left-rounded-corner top-right-rounded-corner">
41 <div id="header-inner" class="title top-left-rounded-corner top-right-rounded-corner">
General Comments 0
You need to be logged in to leave comments. Login now