##// 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,7 +57,8 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',
@@ -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
@@ -155,8 +155,7 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__
@@ -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,6 +26,7 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
@@ -72,7 +73,6 b' 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:
@@ -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 """
@@ -122,33 +124,6 b' def set_available_permissions(config):'
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):
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
127
153 def fill_perms(user):
128 def fill_perms(user):
154 """
129 """
@@ -163,9 +138,7 b' def fill_perms(user):'
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'))\
168 .filter(User.username == 'default').scalar()
169
142
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))\
@@ -231,8 +204,22 b' def get_user(session):'
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()
@@ -286,18 +273,19 b' class PermsDecorator(object):'
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__
289
276 self.user = session.get('rhodecode_user', AuthUser())
290 self.user_perms = session.get('rhodecode_user', AuthUser()).permissions
277 self.user_perms = self.user.permissions
291 log.debug('checking %s permissions %s for %s',
278 log.debug('checking %s permissions %s for %s %s',
292 self.__class__.__name__, self.required_perms, func.__name__)
279 self.__class__.__name__, self.required_perms, func.__name__,
280 self.user)
293
281
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
@@ -383,16 +371,17 b' class PermsFunction(object):'
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__,
375 self.required_perms, user)
387
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):
@@ -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