##// END OF EJS Templates
Code refactoring,models renames...
marcink -
r629:7e536d1a beta
parent child Browse files
Show More
@@ -6,7 +6,7 b' from rhodecode.config.routing import mak'
6 from rhodecode.lib.auth import set_available_permissions, set_base_path
6 from rhodecode.lib.auth import set_available_permissions, set_base_path
7 from rhodecode.lib.utils import repo2db_mapper, make_ui, set_rhodecode_config
7 from rhodecode.lib.utils import repo2db_mapper, make_ui, set_rhodecode_config
8 from rhodecode.model import init_model
8 from rhodecode.model import init_model
9 from rhodecode.model.hg_model import _get_repos_cached_initial
9 from rhodecode.model.hg import _get_repos_cached_initial
10 from sqlalchemy import engine_from_config
10 from sqlalchemy import engine_from_config
11 import logging
11 import logging
12 import os
12 import os
@@ -30,10 +30,9 b' from pylons.i18n.translation import _'
30 from rhodecode.lib import helpers as h
30 from rhodecode.lib import helpers as h
31 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
31 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
32 from rhodecode.lib.base import BaseController, render
32 from rhodecode.lib.base import BaseController, render
33 from rhodecode.model.db import User, UserLog
34 from rhodecode.model.forms import UserForm, DefaultPermissionsForm
33 from rhodecode.model.forms import UserForm, DefaultPermissionsForm
35 from rhodecode.model.permission_model import PermissionModel
34 from rhodecode.model.permission_model import PermissionModel
36 from rhodecode.model.user_model import UserModel
35 from rhodecode.model.user import UserModel
37 import formencode
36 import formencode
38 import logging
37 import logging
39 import traceback
38 import traceback
@@ -45,14 +44,14 b' class PermissionsController(BaseControll'
45 # To properly map this controller, ensure your config/routing.py
44 # To properly map this controller, ensure your config/routing.py
46 # file has a resource setup:
45 # file has a resource setup:
47 # map.resource('permission', 'permissions')
46 # map.resource('permission', 'permissions')
48
47
49 @LoginRequired()
48 @LoginRequired()
50 @HasPermissionAllDecorator('hg.admin')
49 @HasPermissionAllDecorator('hg.admin')
51 def __before__(self):
50 def __before__(self):
52 c.admin_user = session.get('admin_user')
51 c.admin_user = session.get('admin_user')
53 c.admin_username = session.get('admin_username')
52 c.admin_username = session.get('admin_username')
54 super(PermissionsController, self).__before__()
53 super(PermissionsController, self).__before__()
55
54
56 self.perms_choices = [('repository.none', _('None'),),
55 self.perms_choices = [('repository.none', _('None'),),
57 ('repository.read', _('Read'),),
56 ('repository.read', _('Read'),),
58 ('repository.write', _('Write'),),
57 ('repository.write', _('Write'),),
@@ -63,11 +62,11 b' class PermissionsController(BaseControll'
63 _('allowed with manual account activation')),
62 _('allowed with manual account activation')),
64 ('hg.register.auto_activate',
63 ('hg.register.auto_activate',
65 _('allowed with automatic account activation')), ]
64 _('allowed with automatic account activation')), ]
66
65
67 self.create_choices = [('hg.create.none', _('Disabled')),
66 self.create_choices = [('hg.create.none', _('Disabled')),
68 ('hg.create.repository', _('Enabled'))]
67 ('hg.create.repository', _('Enabled'))]
69
68
70
69
71 def index(self, format='html'):
70 def index(self, format='html'):
72 """GET /permissions: All items in the collection"""
71 """GET /permissions: All items in the collection"""
73 # url('permissions')
72 # url('permissions')
@@ -88,38 +87,38 b' class PermissionsController(BaseControll'
88 # h.form(url('permission', id=ID),
87 # h.form(url('permission', id=ID),
89 # method='put')
88 # method='put')
90 # url('permission', id=ID)
89 # url('permission', id=ID)
91
90
92 permission_model = PermissionModel()
91 permission_model = PermissionModel()
93
92
94 _form = DefaultPermissionsForm([x[0] for x in self.perms_choices],
93 _form = DefaultPermissionsForm([x[0] for x in self.perms_choices],
95 [x[0] for x in self.register_choices],
94 [x[0] for x in self.register_choices],
96 [x[0] for x in self.create_choices])()
95 [x[0] for x in self.create_choices])()
97
96
98 try:
97 try:
99 form_result = _form.to_python(dict(request.POST))
98 form_result = _form.to_python(dict(request.POST))
100 form_result.update({'perm_user_name':id})
99 form_result.update({'perm_user_name':id})
101 permission_model.update(form_result)
100 permission_model.update(form_result)
102 h.flash(_('Default permissions updated succesfully'),
101 h.flash(_('Default permissions updated succesfully'),
103 category='success')
102 category='success')
104
103
105 except formencode.Invalid, errors:
104 except formencode.Invalid, errors:
106 c.perms_choices = self.perms_choices
105 c.perms_choices = self.perms_choices
107 c.register_choices = self.register_choices
106 c.register_choices = self.register_choices
108 c.create_choices = self.create_choices
107 c.create_choices = self.create_choices
109
108
110 return htmlfill.render(
109 return htmlfill.render(
111 render('admin/permissions/permissions.html'),
110 render('admin/permissions/permissions.html'),
112 defaults=errors.value,
111 defaults=errors.value,
113 errors=errors.error_dict or {},
112 errors=errors.error_dict or {},
114 prefix_error=False,
113 prefix_error=False,
115 encoding="UTF-8")
114 encoding="UTF-8")
116 except Exception:
115 except Exception:
117 log.error(traceback.format_exc())
116 log.error(traceback.format_exc())
118 h.flash(_('error occured during update of permissions'),
117 h.flash(_('error occured during update of permissions'),
119 category='error')
118 category='error')
120
119
121 return redirect(url('edit_permission', id=id))
120 return redirect(url('edit_permission', id=id))
122
121
123
122
124
123
125 def delete(self, id):
124 def delete(self, id):
@@ -141,23 +140,23 b' class PermissionsController(BaseControll'
141 c.perms_choices = self.perms_choices
140 c.perms_choices = self.perms_choices
142 c.register_choices = self.register_choices
141 c.register_choices = self.register_choices
143 c.create_choices = self.create_choices
142 c.create_choices = self.create_choices
144
143
145 if id == 'default':
144 if id == 'default':
146 defaults = {'_method':'put'}
145 defaults = {'_method':'put'}
147 for p in UserModel().get_default().user_perms:
146 for p in UserModel().get_default().user_perms:
148 if p.permission.permission_name.startswith('repository.'):
147 if p.permission.permission_name.startswith('repository.'):
149 defaults['default_perm'] = p.permission.permission_name
148 defaults['default_perm'] = p.permission.permission_name
150
149
151 if p.permission.permission_name.startswith('hg.register.'):
150 if p.permission.permission_name.startswith('hg.register.'):
152 defaults['default_register'] = p.permission.permission_name
151 defaults['default_register'] = p.permission.permission_name
153
152
154 if p.permission.permission_name.startswith('hg.create.'):
153 if p.permission.permission_name.startswith('hg.create.'):
155 defaults['default_create'] = p.permission.permission_name
154 defaults['default_create'] = p.permission.permission_name
156
155
157 return htmlfill.render(
156 return htmlfill.render(
158 render('admin/permissions/permissions.html'),
157 render('admin/permissions/permissions.html'),
159 defaults=defaults,
158 defaults=defaults,
160 encoding="UTF-8",
159 encoding="UTF-8",
161 force_defaults=True,)
160 force_defaults=True,)
162 else:
161 else:
163 return redirect(url('admin_home'))
162 return redirect(url('admin_home'))
@@ -35,8 +35,8 b' from rhodecode.lib.base import BaseContr'
35 from rhodecode.lib.utils import invalidate_cache, action_logger
35 from rhodecode.lib.utils import invalidate_cache, action_logger
36 from rhodecode.model.db import User
36 from rhodecode.model.db import User
37 from rhodecode.model.forms import RepoForm
37 from rhodecode.model.forms import RepoForm
38 from rhodecode.model.hg_model import HgModel
38 from rhodecode.model.hg import HgModel
39 from rhodecode.model.repo_model import RepoModel
39 from rhodecode.model.repo import RepoModel
40 import formencode
40 import formencode
41 import logging
41 import logging
42 import traceback
42 import traceback
@@ -32,17 +32,17 b' from rhodecode.lib.auth import LoginRequ'
32 HasPermissionAnyDecorator
32 HasPermissionAnyDecorator
33 from rhodecode.lib.base import BaseController, render
33 from rhodecode.lib.base import BaseController, render
34 from rhodecode.lib.utils import repo2db_mapper, invalidate_cache, \
34 from rhodecode.lib.utils import repo2db_mapper, invalidate_cache, \
35 set_rhodecode_config, get_hg_settings, get_hg_ui_settings, make_ui
35 set_rhodecode_config, get_hg_settings, get_hg_ui_settings
36 from rhodecode.model.db import User, UserLog, RhodeCodeSettings, RhodeCodeUi
36 from rhodecode.model.db import RhodeCodeSettings, RhodeCodeUi
37 from rhodecode.model.forms import UserForm, ApplicationSettingsForm, \
37 from rhodecode.model.forms import UserForm, ApplicationSettingsForm, \
38 ApplicationUiSettingsForm
38 ApplicationUiSettingsForm
39 from rhodecode.model.hg_model import HgModel
39 from rhodecode.model.hg import HgModel
40 from rhodecode.model.user_model import UserModel
40 from rhodecode.model.user import UserModel
41 from rhodecode.lib.celerylib import tasks, run_task
41 from rhodecode.lib.celerylib import tasks, run_task
42 import formencode
42 import formencode
43 import logging
43 import logging
44 import traceback
44 import traceback
45
45
46 log = logging.getLogger(__name__)
46 log = logging.getLogger(__name__)
47
47
48
48
@@ -59,9 +59,9 b' class SettingsController(BaseController)'
59 c.admin_user = session.get('admin_user')
59 c.admin_user = session.get('admin_user')
60 c.admin_username = session.get('admin_username')
60 c.admin_username = session.get('admin_username')
61 super(SettingsController, self).__before__()
61 super(SettingsController, self).__before__()
62
62
63
63
64 @HasPermissionAllDecorator('hg.admin')
64 @HasPermissionAllDecorator('hg.admin')
65 def index(self, format='html'):
65 def index(self, format='html'):
66 """GET /admin/settings: All items in the collection"""
66 """GET /admin/settings: All items in the collection"""
67 # url('admin_settings')
67 # url('admin_settings')
@@ -73,18 +73,18 b' class SettingsController(BaseController)'
73 defaults=defaults,
73 defaults=defaults,
74 encoding="UTF-8",
74 encoding="UTF-8",
75 force_defaults=False
75 force_defaults=False
76 )
76 )
77
77
78 @HasPermissionAllDecorator('hg.admin')
78 @HasPermissionAllDecorator('hg.admin')
79 def create(self):
79 def create(self):
80 """POST /admin/settings: Create a new item"""
80 """POST /admin/settings: Create a new item"""
81 # url('admin_settings')
81 # url('admin_settings')
82
82
83 @HasPermissionAllDecorator('hg.admin')
83 @HasPermissionAllDecorator('hg.admin')
84 def new(self, format='html'):
84 def new(self, format='html'):
85 """GET /admin/settings/new: Form to create a new item"""
85 """GET /admin/settings/new: Form to create a new item"""
86 # url('admin_new_setting')
86 # url('admin_new_setting')
87
87
88 @HasPermissionAllDecorator('hg.admin')
88 @HasPermissionAllDecorator('hg.admin')
89 def update(self, setting_id):
89 def update(self, setting_id):
90 """PUT /admin/settings/setting_id: Update an existing item"""
90 """PUT /admin/settings/setting_id: Update an existing item"""
@@ -101,44 +101,44 b' class SettingsController(BaseController)'
101 initial = HgModel.repo_scan(g.paths[0][0], g.paths[0][1], g.baseui)
101 initial = HgModel.repo_scan(g.paths[0][0], g.paths[0][1], g.baseui)
102 repo2db_mapper(initial, rm_obsolete)
102 repo2db_mapper(initial, rm_obsolete)
103 invalidate_cache('cached_repo_list')
103 invalidate_cache('cached_repo_list')
104 h.flash(_('Repositories successfully rescanned'), category='success')
104 h.flash(_('Repositories successfully rescanned'), category='success')
105
105
106 if setting_id == 'whoosh':
106 if setting_id == 'whoosh':
107 repo_location = get_hg_ui_settings()['paths_root_path']
107 repo_location = get_hg_ui_settings()['paths_root_path']
108 full_index = request.POST.get('full_index', False)
108 full_index = request.POST.get('full_index', False)
109 task = run_task(tasks.whoosh_index, repo_location, full_index)
109 task = run_task(tasks.whoosh_index, repo_location, full_index)
110
110
111 h.flash(_('Whoosh reindex task scheduled'), category='success')
111 h.flash(_('Whoosh reindex task scheduled'), category='success')
112 if setting_id == 'global':
112 if setting_id == 'global':
113
113
114 application_form = ApplicationSettingsForm()()
114 application_form = ApplicationSettingsForm()()
115 try:
115 try:
116 form_result = application_form.to_python(dict(request.POST))
116 form_result = application_form.to_python(dict(request.POST))
117
117
118 try:
118 try:
119 hgsettings1 = self.sa.query(RhodeCodeSettings)\
119 hgsettings1 = self.sa.query(RhodeCodeSettings)\
120 .filter(RhodeCodeSettings.app_settings_name == 'title').one()
120 .filter(RhodeCodeSettings.app_settings_name == 'title').one()
121 hgsettings1.app_settings_value = form_result['rhodecode_title']
121 hgsettings1.app_settings_value = form_result['rhodecode_title']
122
122
123 hgsettings2 = self.sa.query(RhodeCodeSettings)\
123 hgsettings2 = self.sa.query(RhodeCodeSettings)\
124 .filter(RhodeCodeSettings.app_settings_name == 'realm').one()
124 .filter(RhodeCodeSettings.app_settings_name == 'realm').one()
125 hgsettings2.app_settings_value = form_result['rhodecode_realm']
125 hgsettings2.app_settings_value = form_result['rhodecode_realm']
126
126
127
127
128 self.sa.add(hgsettings1)
128 self.sa.add(hgsettings1)
129 self.sa.add(hgsettings2)
129 self.sa.add(hgsettings2)
130 self.sa.commit()
130 self.sa.commit()
131 set_rhodecode_config(config)
131 set_rhodecode_config(config)
132 h.flash(_('Updated application settings'),
132 h.flash(_('Updated application settings'),
133 category='success')
133 category='success')
134
134
135 except:
135 except:
136 log.error(traceback.format_exc())
136 log.error(traceback.format_exc())
137 h.flash(_('error occurred during updating application settings'),
137 h.flash(_('error occurred during updating application settings'),
138 category='error')
138 category='error')
139
139
140 self.sa.rollback()
140 self.sa.rollback()
141
141
142
142
143 except formencode.Invalid, errors:
143 except formencode.Invalid, errors:
144 return htmlfill.render(
144 return htmlfill.render(
@@ -146,52 +146,52 b' class SettingsController(BaseController)'
146 defaults=errors.value,
146 defaults=errors.value,
147 errors=errors.error_dict or {},
147 errors=errors.error_dict or {},
148 prefix_error=False,
148 prefix_error=False,
149 encoding="UTF-8")
149 encoding="UTF-8")
150
150
151 if setting_id == 'mercurial':
151 if setting_id == 'mercurial':
152 application_form = ApplicationUiSettingsForm()()
152 application_form = ApplicationUiSettingsForm()()
153 try:
153 try:
154 form_result = application_form.to_python(dict(request.POST))
154 form_result = application_form.to_python(dict(request.POST))
155
155
156 try:
156 try:
157
157
158 hgsettings1 = self.sa.query(RhodeCodeUi)\
158 hgsettings1 = self.sa.query(RhodeCodeUi)\
159 .filter(RhodeCodeUi.ui_key == 'push_ssl').one()
159 .filter(RhodeCodeUi.ui_key == 'push_ssl').one()
160 hgsettings1.ui_value = form_result['web_push_ssl']
160 hgsettings1.ui_value = form_result['web_push_ssl']
161
161
162 hgsettings2 = self.sa.query(RhodeCodeUi)\
162 hgsettings2 = self.sa.query(RhodeCodeUi)\
163 .filter(RhodeCodeUi.ui_key == '/').one()
163 .filter(RhodeCodeUi.ui_key == '/').one()
164 hgsettings2.ui_value = form_result['paths_root_path']
164 hgsettings2.ui_value = form_result['paths_root_path']
165
165
166
166
167 #HOOKS
167 #HOOKS
168 hgsettings3 = self.sa.query(RhodeCodeUi)\
168 hgsettings3 = self.sa.query(RhodeCodeUi)\
169 .filter(RhodeCodeUi.ui_key == 'changegroup.update').one()
169 .filter(RhodeCodeUi.ui_key == 'changegroup.update').one()
170 hgsettings3.ui_active = bool(form_result['hooks_changegroup_update'])
170 hgsettings3.ui_active = bool(form_result['hooks_changegroup_update'])
171
171
172 hgsettings4 = self.sa.query(RhodeCodeUi)\
172 hgsettings4 = self.sa.query(RhodeCodeUi)\
173 .filter(RhodeCodeUi.ui_key == 'changegroup.repo_size').one()
173 .filter(RhodeCodeUi.ui_key == 'changegroup.repo_size').one()
174 hgsettings4.ui_active = bool(form_result['hooks_changegroup_repo_size'])
174 hgsettings4.ui_active = bool(form_result['hooks_changegroup_repo_size'])
175
175
176
176
177
177
178
178
179 self.sa.add(hgsettings1)
179 self.sa.add(hgsettings1)
180 self.sa.add(hgsettings2)
180 self.sa.add(hgsettings2)
181 self.sa.add(hgsettings3)
181 self.sa.add(hgsettings3)
182 self.sa.add(hgsettings4)
182 self.sa.add(hgsettings4)
183 self.sa.commit()
183 self.sa.commit()
184
184
185 h.flash(_('Updated mercurial settings'),
185 h.flash(_('Updated mercurial settings'),
186 category='success')
186 category='success')
187
187
188 except:
188 except:
189 log.error(traceback.format_exc())
189 log.error(traceback.format_exc())
190 h.flash(_('error occurred during updating application settings'),
190 h.flash(_('error occurred during updating application settings'),
191 category='error')
191 category='error')
192
192
193 self.sa.rollback()
193 self.sa.rollback()
194
194
195
195
196 except formencode.Invalid, errors:
196 except formencode.Invalid, errors:
197 return htmlfill.render(
197 return htmlfill.render(
@@ -199,12 +199,12 b' class SettingsController(BaseController)'
199 defaults=errors.value,
199 defaults=errors.value,
200 errors=errors.error_dict or {},
200 errors=errors.error_dict or {},
201 prefix_error=False,
201 prefix_error=False,
202 encoding="UTF-8")
202 encoding="UTF-8")
203
203
204
204
205
205
206 return redirect(url('admin_settings'))
206 return redirect(url('admin_settings'))
207
207
208 @HasPermissionAllDecorator('hg.admin')
208 @HasPermissionAllDecorator('hg.admin')
209 def delete(self, setting_id):
209 def delete(self, setting_id):
210 """DELETE /admin/settings/setting_id: Delete an existing item"""
210 """DELETE /admin/settings/setting_id: Delete an existing item"""
@@ -214,13 +214,13 b' class SettingsController(BaseController)'
214 # h.form(url('admin_setting', setting_id=ID),
214 # h.form(url('admin_setting', setting_id=ID),
215 # method='delete')
215 # method='delete')
216 # url('admin_setting', setting_id=ID)
216 # url('admin_setting', setting_id=ID)
217
217
218 @HasPermissionAllDecorator('hg.admin')
218 @HasPermissionAllDecorator('hg.admin')
219 def show(self, setting_id, format='html'):
219 def show(self, setting_id, format='html'):
220 """GET /admin/settings/setting_id: Show a specific item"""
220 """GET /admin/settings/setting_id: Show a specific item"""
221 # url('admin_setting', setting_id=ID)
221 # url('admin_setting', setting_id=ID)
222
222
223 @HasPermissionAllDecorator('hg.admin')
223 @HasPermissionAllDecorator('hg.admin')
224 def edit(self, setting_id, format='html'):
224 def edit(self, setting_id, format='html'):
225 """GET /admin/settings/setting_id/edit: Form to edit an existing item"""
225 """GET /admin/settings/setting_id/edit: Form to edit an existing item"""
226 # url('admin_edit_setting', setting_id=ID)
226 # url('admin_edit_setting', setting_id=ID)
@@ -231,24 +231,24 b' class SettingsController(BaseController)'
231 GET /_admin/my_account Displays info about my account
231 GET /_admin/my_account Displays info about my account
232 """
232 """
233 # url('admin_settings_my_account')
233 # url('admin_settings_my_account')
234 c.user = self.sa.query(User).get(c.rhodecode_user.user_id)
234 c.user = UserModel(self.sa).get(c.rhodecode_user.user_id, cache=False)
235 c.user_repos = []
235 c.user_repos = []
236 for repo in c.cached_repo_list.values():
236 for repo in c.cached_repo_list.values():
237 if repo.dbrepo.user.username == c.user.username:
237 if repo.dbrepo.user.username == c.user.username:
238 c.user_repos.append(repo)
238 c.user_repos.append(repo)
239
239
240 if c.user.username == 'default':
240 if c.user.username == 'default':
241 h.flash(_("You can't edit this user since it's"
241 h.flash(_("You can't edit this user since it's"
242 " crucial for entire application"), category='warning')
242 " crucial for entire application"), category='warning')
243 return redirect(url('users'))
243 return redirect(url('users'))
244
244
245 defaults = c.user.__dict__
245 defaults = c.user.__dict__
246 return htmlfill.render(
246 return htmlfill.render(
247 render('admin/users/user_edit_my_account.html'),
247 render('admin/users/user_edit_my_account.html'),
248 defaults=defaults,
248 defaults=defaults,
249 encoding="UTF-8",
249 encoding="UTF-8",
250 force_defaults=False
250 force_defaults=False
251 )
251 )
252
252
253 def my_account_update(self):
253 def my_account_update(self):
254 """PUT /_admin/my_account_update: Update an existing item"""
254 """PUT /_admin/my_account_update: Update an existing item"""
@@ -268,13 +268,13 b' class SettingsController(BaseController)'
268 user_model.update_my_account(uid, form_result)
268 user_model.update_my_account(uid, form_result)
269 h.flash(_('Your account was updated succesfully'),
269 h.flash(_('Your account was updated succesfully'),
270 category='success')
270 category='success')
271
271
272 except formencode.Invalid, errors:
272 except formencode.Invalid, errors:
273 c.user = self.sa.query(User).get(c.rhodecode_user.user_id)
273 c.user = user_model.get(c.rhodecode_user.user_id, cache=False)
274 c.user_repos = []
274 c.user_repos = []
275 for repo in c.cached_repo_list.values():
275 for repo in c.cached_repo_list.values():
276 if repo.dbrepo.user.username == c.user.username:
276 if repo.dbrepo.user.username == c.user.username:
277 c.user_repos.append(repo)
277 c.user_repos.append(repo)
278 return htmlfill.render(
278 return htmlfill.render(
279 render('admin/users/user_edit_my_account.html'),
279 render('admin/users/user_edit_my_account.html'),
280 defaults=errors.value,
280 defaults=errors.value,
@@ -285,9 +285,9 b' class SettingsController(BaseController)'
285 log.error(traceback.format_exc())
285 log.error(traceback.format_exc())
286 h.flash(_('error occured during update of user %s') \
286 h.flash(_('error occured during update of user %s') \
287 % form_result.get('username'), category='error')
287 % form_result.get('username'), category='error')
288
288
289 return redirect(url('my_account'))
289 return redirect(url('my_account'))
290
290
291 @HasPermissionAnyDecorator('hg.admin', 'hg.create.repository')
291 @HasPermissionAnyDecorator('hg.admin', 'hg.create.repository')
292 def create_repository(self):
292 def create_repository(self):
293 """GET /_admin/create_repository: Form to create a new item"""
293 """GET /_admin/create_repository: Form to create a new item"""
@@ -295,4 +295,4 b' class SettingsController(BaseController)'
295 c.new_repo = h.repo_name_slug(new_repo)
295 c.new_repo = h.repo_name_slug(new_repo)
296
296
297 return render('admin/repos/repo_add_create_repository.html')
297 return render('admin/repos/repo_add_create_repository.html')
298
298
@@ -33,7 +33,7 b' from rhodecode.lib.auth import LoginRequ'
33 from rhodecode.lib.base import BaseController, render
33 from rhodecode.lib.base import BaseController, render
34 from rhodecode.model.db import User, UserLog
34 from rhodecode.model.db import User, UserLog
35 from rhodecode.model.forms import UserForm
35 from rhodecode.model.forms import UserForm
36 from rhodecode.model.user_model import UserModel, DefaultUserException
36 from rhodecode.model.user import UserModel, DefaultUserException
37 import formencode
37 import formencode
38 import logging
38 import logging
39 import traceback
39 import traceback
@@ -100,7 +100,7 b' class UsersController(BaseController):'
100 # method='put')
100 # method='put')
101 # url('user', id=ID)
101 # url('user', id=ID)
102 user_model = UserModel()
102 user_model = UserModel()
103 c.user = user_model.get_user(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})()
@@ -26,7 +26,7 b' from pylons import tmpl_context as c'
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
27 from rhodecode.lib.base import BaseController, render
27 from rhodecode.lib.base import BaseController, render
28 from rhodecode.lib.utils import OrderedDict
28 from rhodecode.lib.utils import OrderedDict
29 from rhodecode.model.hg_model import HgModel
29 from rhodecode.model.hg import HgModel
30 import logging
30 import logging
31 log = logging.getLogger(__name__)
31 log = logging.getLogger(__name__)
32
32
@@ -32,7 +32,7 b' from mercurial.graphmod import colored, '
32 from pylons import request, session, tmpl_context as c
32 from pylons import request, session, tmpl_context as c
33 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
33 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
34 from rhodecode.lib.base import BaseController, render
34 from rhodecode.lib.base import BaseController, render
35 from rhodecode.model.hg_model import HgModel
35 from rhodecode.model.hg import HgModel
36 from webhelpers.paginate import Page
36 from webhelpers.paginate import Page
37 import logging
37 import logging
38 log = logging.getLogger(__name__)
38 log = logging.getLogger(__name__)
@@ -27,7 +27,7 b' from pylons.i18n.translation import _'
27 from pylons.controllers.util import redirect
27 from pylons.controllers.util import redirect
28 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
28 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
29 from rhodecode.lib.base import BaseController, render
29 from rhodecode.lib.base import BaseController, render
30 from rhodecode.model.hg_model import HgModel
30 from rhodecode.model.hg import HgModel
31 from vcs.exceptions import RepositoryError, ChangesetError
31 from vcs.exceptions import RepositoryError, ChangesetError
32 from vcs.nodes import FileNode
32 from vcs.nodes import FileNode
33 from vcs.utils import diffs as differ
33 from vcs.utils import diffs as differ
@@ -24,7 +24,7 b' feed controller for pylons'
24 """
24 """
25 from pylons import tmpl_context as c, url, response
25 from pylons import tmpl_context as c, url, response
26 from rhodecode.lib.base import BaseController, render
26 from rhodecode.lib.base import BaseController, render
27 from rhodecode.model.hg_model import HgModel
27 from rhodecode.model.hg import HgModel
28 from webhelpers.feedgenerator import Atom1Feed, Rss201rev2Feed
28 from webhelpers.feedgenerator import Atom1Feed, Rss201rev2Feed
29 import logging
29 import logging
30 log = logging.getLogger(__name__)
30 log = logging.getLogger(__name__)
@@ -29,7 +29,7 b' from pylons.controllers.util import redi'
29 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
29 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
30 from rhodecode.lib.base import BaseController, render
30 from rhodecode.lib.base import BaseController, render
31 from rhodecode.lib.utils import EmptyChangeset
31 from rhodecode.lib.utils import EmptyChangeset
32 from rhodecode.model.hg_model import HgModel
32 from rhodecode.model.hg import HgModel
33 from vcs.exceptions import RepositoryError, ChangesetError
33 from vcs.exceptions import RepositoryError, ChangesetError
34 from vcs.nodes import FileNode
34 from vcs.nodes import FileNode
35 from vcs.utils import diffs as differ
35 from vcs.utils import diffs as differ
@@ -26,7 +26,7 b' from operator import itemgetter'
26 from pylons import tmpl_context as c, request
26 from pylons import tmpl_context as c, request
27 from rhodecode.lib.auth import LoginRequired
27 from rhodecode.lib.auth import LoginRequired
28 from rhodecode.lib.base import BaseController, render
28 from rhodecode.lib.base import BaseController, render
29 from rhodecode.model.hg_model import HgModel
29 from rhodecode.model.hg import HgModel
30 import logging
30 import logging
31 log = logging.getLogger(__name__)
31 log = logging.getLogger(__name__)
32
32
@@ -31,7 +31,7 b' from rhodecode.lib.base import BaseContr'
31 import rhodecode.lib.helpers as h
31 import rhodecode.lib.helpers as h
32 from pylons.i18n.translation import _
32 from pylons.i18n.translation import _
33 from rhodecode.model.forms import LoginForm, RegisterForm, PasswordResetForm
33 from rhodecode.model.forms import LoginForm, RegisterForm, PasswordResetForm
34 from rhodecode.model.user_model import UserModel
34 from rhodecode.model.user import UserModel
35 import formencode
35 import formencode
36 import logging
36 import logging
37
37
@@ -55,7 +55,7 b' class LoginController(BaseController):'
55 try:
55 try:
56 c.form_result = login_form.to_python(dict(request.POST))
56 c.form_result = login_form.to_python(dict(request.POST))
57 username = c.form_result['username']
57 username = c.form_result['username']
58 user = UserModel().get_user_by_name(username)
58 user = UserModel().get_by_username(username)
59 auth_user = AuthUser()
59 auth_user = AuthUser()
60 auth_user.username = user.username
60 auth_user.username = user.username
61 auth_user.is_authenticated = True
61 auth_user.is_authenticated = True
@@ -89,7 +89,7 b' class LoginController(BaseController):'
89 def register(self):
89 def register(self):
90 user_model = UserModel()
90 user_model = UserModel()
91 c.auto_active = False
91 c.auto_active = False
92 for perm in user_model.get_default().user_perms:
92 for perm in user_model.get_by_username('default', cache=False).user_perms:
93 if perm.permission.permission_name == 'hg.register.auto_activate':
93 if perm.permission.permission_name == 'hg.register.auto_activate':
94 c.auto_active = True
94 c.auto_active = True
95 break
95 break
@@ -30,7 +30,7 b' from rhodecode.lib.auth import LoginRequ'
30 from rhodecode.lib.base import BaseController, render
30 from rhodecode.lib.base import BaseController, render
31 from rhodecode.lib.utils import invalidate_cache, action_logger
31 from rhodecode.lib.utils import invalidate_cache, action_logger
32 from rhodecode.model.forms import RepoSettingsForm, RepoForkForm
32 from rhodecode.model.forms import RepoSettingsForm, RepoForkForm
33 from rhodecode.model.repo_model import RepoModel
33 from rhodecode.model.repo import RepoModel
34 import formencode
34 import formencode
35 import logging
35 import logging
36 import rhodecode.lib.helpers as h
36 import rhodecode.lib.helpers as h
@@ -25,7 +25,7 b' shortlog controller for pylons'
25 from pylons import tmpl_context as c, request
25 from pylons import tmpl_context as c, request
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
27 from rhodecode.lib.base import BaseController, render
27 from rhodecode.lib.base import BaseController, render
28 from rhodecode.model.hg_model import HgModel
28 from rhodecode.model.hg import HgModel
29 from webhelpers.paginate import Page
29 from webhelpers.paginate import Page
30 import logging
30 import logging
31 log = logging.getLogger(__name__)
31 log = logging.getLogger(__name__)
@@ -26,7 +26,7 b' from pylons import tmpl_context as c, re'
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
27 from rhodecode.lib.base import BaseController, render
27 from rhodecode.lib.base import BaseController, render
28 from rhodecode.lib.utils import OrderedDict
28 from rhodecode.lib.utils import OrderedDict
29 from rhodecode.model.hg_model import HgModel
29 from rhodecode.model.hg import HgModel
30 from rhodecode.model.db import Statistics
30 from rhodecode.model.db import Statistics
31 from webhelpers.paginate import Page
31 from webhelpers.paginate import Page
32 from rhodecode.lib.celerylib import run_task
32 from rhodecode.lib.celerylib import run_task
@@ -26,7 +26,7 b' from pylons import tmpl_context as c'
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
26 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
27 from rhodecode.lib.base import BaseController, render
27 from rhodecode.lib.base import BaseController, render
28 from rhodecode.lib.utils import OrderedDict
28 from rhodecode.lib.utils import OrderedDict
29 from rhodecode.model.hg_model import HgModel
29 from rhodecode.model.hg import HgModel
30 import logging
30 import logging
31 log = logging.getLogger(__name__)
31 log = logging.getLogger(__name__)
32
32
@@ -22,16 +22,13 b' Created on April 4, 2010'
22
22
23 @author: marcink
23 @author: marcink
24 """
24 """
25 from beaker.cache import cache_region
26 from pylons import config, session, url, request
25 from pylons import config, session, url, request
27 from pylons.controllers.util import abort, redirect
26 from pylons.controllers.util import abort, redirect
28 from rhodecode.lib.utils import get_repo_slug
27 from rhodecode.lib.utils import get_repo_slug
29 from rhodecode.model import meta
28 from rhodecode.model import meta
30 from rhodecode.model.caching_query import FromCache
29 from rhodecode.model.caching_query import FromCache
31 from rhodecode.model.db import User, RepoToPerm, Repository, Permission, \
30 from rhodecode.model.db import User, RepoToPerm, Repository, Permission, \
32 UserToPerm
31 UserToPerm
33 from sqlalchemy.exc import OperationalError
34 from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
35 import bcrypt
32 import bcrypt
36 from decorator import decorator
33 from decorator import decorator
37 import logging
34 import logging
@@ -74,22 +71,10 b' def get_crypt_password(password):'
74 def check_password(password, hashed):
71 def check_password(password, hashed):
75 return bcrypt.hashpw(password, hashed) == hashed
72 return bcrypt.hashpw(password, hashed) == hashed
76
73
77 @cache_region('super_short_term', 'cached_user')
78 def get_user_cached(username):
79 sa = meta.Session
80 try:
81 user = sa.query(User).filter(User.username == username).one()
82 finally:
83 meta.Session.remove()
84 return user
85
86 def authfunc(environ, username, password):
74 def authfunc(environ, username, password):
87 try:
75 from rhodecode.model.user import UserModel
88 user = get_user_cached(username)
76 user = UserModel().get_by_username(username, cache=False)
89 except (NoResultFound, MultipleResultsFound, OperationalError), e:
77
90 log.error(e)
91 user = None
92
93 if user:
78 if user:
94 if user.active:
79 if user.active:
95 if user.username == username and check_password(password, user.password):
80 if user.username == username and check_password(password, user.password):
@@ -125,8 +110,10 b' def set_available_permissions(config):'
125 """
110 """
126 log.info('getting information about all available permissions')
111 log.info('getting information about all available permissions')
127 try:
112 try:
128 sa = meta.Session
113 sa = meta.Session()
129 all_perms = sa.query(Permission).all()
114 all_perms = sa.query(Permission).all()
115 except:
116 pass
130 finally:
117 finally:
131 meta.Session.remove()
118 meta.Session.remove()
132
119
@@ -141,10 +128,16 b' def fill_data(user):'
141 in database
128 in database
142 :param user:
129 :param user:
143 """
130 """
144 sa = meta.Session
131 sa = meta.Session()
145 dbuser = sa.query(User).options(FromCache('sql_cache_short',
132 try:
146 'getuser_%s' % user.user_id))\
133 dbuser = sa.query(User)\
134 .options(FromCache('sql_cache_short', 'getuser_%s' % user.user_id))\
147 .get(user.user_id)
135 .get(user.user_id)
136 except:
137 pass
138 finally:
139 meta.Session.remove()
140
148 if dbuser:
141 if dbuser:
149 user.username = dbuser.username
142 user.username = dbuser.username
150 user.is_admin = dbuser.admin
143 user.is_admin = dbuser.admin
@@ -153,7 +146,8 b' def fill_data(user):'
153 user.email = dbuser.email
146 user.email = dbuser.email
154 else:
147 else:
155 user.is_authenticated = False
148 user.is_authenticated = False
156 meta.Session.remove()
149
150
157 return user
151 return user
158
152
159 def fill_perms(user):
153 def fill_perms(user):
@@ -162,7 +156,7 b' def fill_perms(user):'
162 :param user:
156 :param user:
163 """
157 """
164
158
165 sa = meta.Session
159 sa = meta.Session()
166 user.permissions['repositories'] = {}
160 user.permissions['repositories'] = {}
167 user.permissions['global'] = set()
161 user.permissions['global'] = set()
168
162
@@ -170,7 +164,7 b' def fill_perms(user):'
170 # fetch default permissions
164 # fetch default permissions
171 #===========================================================================
165 #===========================================================================
172 default_user = sa.query(User)\
166 default_user = sa.query(User)\
173 .options(FromCache('sql_cache_short','getuser_%s' % 'default'))\
167 .options(FromCache('sql_cache_short', 'getuser_%s' % 'default'))\
174 .filter(User.username == 'default').scalar()
168 .filter(User.username == 'default').scalar()
175
169
176 default_perms = sa.query(RepoToPerm, Repository, Permission)\
170 default_perms = sa.query(RepoToPerm, Repository, Permission)\
@@ -9,7 +9,7 b' from rhodecode import __version__'
9 from rhodecode.lib import auth
9 from rhodecode.lib import auth
10 from rhodecode.lib.utils import get_repo_slug
10 from rhodecode.lib.utils import get_repo_slug
11 from rhodecode.model import meta
11 from rhodecode.model import meta
12 from rhodecode.model.hg_model import _get_repos_cached, \
12 from rhodecode.model.hg import _get_repos_cached, \
13 _get_repos_switcher_cached
13 _get_repos_switcher_cached
14
14
15 class BaseController(WSGIController):
15 class BaseController(WSGIController):
@@ -31,7 +31,7 b' class BaseController(WSGIController):'
31 c.repository_tags = {}
31 c.repository_tags = {}
32 c.repository_branches = {}
32 c.repository_branches = {}
33
33
34 self.sa = meta.Session
34 self.sa = meta.Session()
35
35
36 def __call__(self, environ, start_response):
36 def __call__(self, environ, start_response):
37 """Invoke the Controller"""
37 """Invoke the Controller"""
@@ -38,28 +38,28 b' def get_session():'
38 else:
38 else:
39 #If we don't use celery reuse our current application Session
39 #If we don't use celery reuse our current application Session
40 from rhodecode.model.meta import Session
40 from rhodecode.model.meta import Session
41 sa = Session
41 sa = Session()
42
42
43 return sa
43 return sa
44
44
45 def get_hg_settings():
45 def get_hg_settings():
46 from rhodecode.model.db import RhodeCodeSettings
46 from rhodecode.model.db import RhodeCodeSettings
47 sa = get_session()
47 sa = get_session()
48 ret = sa.query(RhodeCodeSettings).all()
48 ret = sa.query(RhodeCodeSettings).all()
49
49
50 if not ret:
50 if not ret:
51 raise Exception('Could not get application settings !')
51 raise Exception('Could not get application settings !')
52 settings = {}
52 settings = {}
53 for each in ret:
53 for each in ret:
54 settings['rhodecode_' + each.app_settings_name] = each.app_settings_value
54 settings['rhodecode_' + each.app_settings_name] = each.app_settings_value
55
55
56 return settings
56 return settings
57
57
58 def get_hg_ui_settings():
58 def get_hg_ui_settings():
59 from rhodecode.model.db import RhodeCodeUi
59 from rhodecode.model.db import RhodeCodeUi
60 sa = get_session()
60 sa = get_session()
61 ret = sa.query(RhodeCodeUi).all()
61 ret = sa.query(RhodeCodeUi).all()
62
62
63 if not ret:
63 if not ret:
64 raise Exception('Could not get application ui settings !')
64 raise Exception('Could not get application ui settings !')
65 settings = {}
65 settings = {}
@@ -68,16 +68,16 b' def get_hg_ui_settings():'
68 v = each.ui_value
68 v = each.ui_value
69 if k == '/':
69 if k == '/':
70 k = 'root_path'
70 k = 'root_path'
71
71
72 if k.find('.') != -1:
72 if k.find('.') != -1:
73 k = k.replace('.', '_')
73 k = k.replace('.', '_')
74
74
75 if each.ui_section == 'hooks':
75 if each.ui_section == 'hooks':
76 v = each.ui_active
76 v = each.ui_active
77
77
78 settings[each.ui_section + '_' + k] = v
78 settings[each.ui_section + '_' + k] = v
79
79
80 return settings
80 return settings
81
81
82 @task
82 @task
83 @locked_task
83 @locked_task
@@ -92,7 +92,7 b' def get_commits_stats(repo_name, ts_min_'
92 from rhodecode.model.db import Statistics, Repository
92 from rhodecode.model.db import Statistics, Repository
93 log = get_commits_stats.get_logger()
93 log = get_commits_stats.get_logger()
94 author_key_cleaner = lambda k: person(k).replace('"', "") #for js data compatibilty
94 author_key_cleaner = lambda k: person(k).replace('"', "") #for js data compatibilty
95
95
96 commits_by_day_author_aggregate = {}
96 commits_by_day_author_aggregate = {}
97 commits_by_day_aggregate = {}
97 commits_by_day_aggregate = {}
98 repos_path = get_hg_ui_settings()['paths_root_path'].replace('*', '')
98 repos_path = get_hg_ui_settings()['paths_root_path'].replace('*', '')
@@ -103,9 +103,9 b' def get_commits_stats(repo_name, ts_min_'
103 last_rev = 0
103 last_rev = 0
104 last_cs = None
104 last_cs = None
105 timegetter = itemgetter('time')
105 timegetter = itemgetter('time')
106
106
107 sa = get_session()
107 sa = get_session()
108
108
109 dbrepo = sa.query(Repository)\
109 dbrepo = sa.query(Repository)\
110 .filter(Repository.repo_name == repo_name).scalar()
110 .filter(Repository.repo_name == repo_name).scalar()
111 cur_stats = sa.query(Statistics)\
111 cur_stats = sa.query(Statistics)\
@@ -114,18 +114,18 b' def get_commits_stats(repo_name, ts_min_'
114 last_rev = cur_stats.stat_on_revision
114 last_rev = cur_stats.stat_on_revision
115 if not repo.revisions:
115 if not repo.revisions:
116 return True
116 return True
117
117
118 if last_rev == repo.revisions[-1] and len(repo.revisions) > 1:
118 if last_rev == repo.revisions[-1] and len(repo.revisions) > 1:
119 #pass silently without any work if we're not on first revision or current
119 #pass silently without any work if we're not on first revision or current
120 #state of parsing revision(from db marker) is the last revision
120 #state of parsing revision(from db marker) is the last revision
121 return True
121 return True
122
122
123 if cur_stats:
123 if cur_stats:
124 commits_by_day_aggregate = OrderedDict(
124 commits_by_day_aggregate = OrderedDict(
125 json.loads(
125 json.loads(
126 cur_stats.commit_activity_combined))
126 cur_stats.commit_activity_combined))
127 commits_by_day_author_aggregate = json.loads(cur_stats.commit_activity)
127 commits_by_day_author_aggregate = json.loads(cur_stats.commit_activity)
128
128
129 log.debug('starting parsing %s', parse_limit)
129 log.debug('starting parsing %s', parse_limit)
130 for cnt, rev in enumerate(repo.revisions[last_rev:]):
130 for cnt, rev in enumerate(repo.revisions[last_rev:]):
131 last_cs = cs = repo.get_changeset(rev)
131 last_cs = cs = repo.get_changeset(rev)
@@ -141,20 +141,20 b' def get_commits_stats(repo_name, ts_min_'
141 time_pos = l.index(k)
141 time_pos = l.index(k)
142 except ValueError:
142 except ValueError:
143 time_pos = False
143 time_pos = False
144
144
145 if time_pos >= 0 and time_pos is not False:
145 if time_pos >= 0 and time_pos is not False:
146
146
147 datadict = commits_by_day_author_aggregate\
147 datadict = commits_by_day_author_aggregate\
148 [author_key_cleaner(cs.author)]['data'][time_pos]
148 [author_key_cleaner(cs.author)]['data'][time_pos]
149
149
150 datadict["commits"] += 1
150 datadict["commits"] += 1
151 datadict["added"] += len(cs.added)
151 datadict["added"] += len(cs.added)
152 datadict["changed"] += len(cs.changed)
152 datadict["changed"] += len(cs.changed)
153 datadict["removed"] += len(cs.removed)
153 datadict["removed"] += len(cs.removed)
154
154
155 else:
155 else:
156 if k >= ts_min_y and k <= ts_max_y or skip_date_limit:
156 if k >= ts_min_y and k <= ts_max_y or skip_date_limit:
157
157
158 datadict = {"time":k,
158 datadict = {"time":k,
159 "commits":1,
159 "commits":1,
160 "added":len(cs.added),
160 "added":len(cs.added),
@@ -163,7 +163,7 b' def get_commits_stats(repo_name, ts_min_'
163 }
163 }
164 commits_by_day_author_aggregate\
164 commits_by_day_author_aggregate\
165 [author_key_cleaner(cs.author)]['data'].append(datadict)
165 [author_key_cleaner(cs.author)]['data'].append(datadict)
166
166
167 else:
167 else:
168 if k >= ts_min_y and k <= ts_max_y or skip_date_limit:
168 if k >= ts_min_y and k <= ts_max_y or skip_date_limit:
169 commits_by_day_author_aggregate[author_key_cleaner(cs.author)] = {
169 commits_by_day_author_aggregate[author_key_cleaner(cs.author)] = {
@@ -175,14 +175,14 b' def get_commits_stats(repo_name, ts_min_'
175 "removed":len(cs.removed),
175 "removed":len(cs.removed),
176 }],
176 }],
177 "schema":["commits"],
177 "schema":["commits"],
178 }
178 }
179
179
180 #gather all data by day
180 #gather all data by day
181 if commits_by_day_aggregate.has_key(k):
181 if commits_by_day_aggregate.has_key(k):
182 commits_by_day_aggregate[k] += 1
182 commits_by_day_aggregate[k] += 1
183 else:
183 else:
184 commits_by_day_aggregate[k] = 1
184 commits_by_day_aggregate[k] = 1
185
185
186 if cnt >= parse_limit:
186 if cnt >= parse_limit:
187 #don't fetch to much data since we can freeze application
187 #don't fetch to much data since we can freeze application
188 break
188 break
@@ -191,7 +191,7 b' def get_commits_stats(repo_name, ts_min_'
191 for k, v in commits_by_day_aggregate.items():
191 for k, v in commits_by_day_aggregate.items():
192 overview_data.append([k, v])
192 overview_data.append([k, v])
193 overview_data = sorted(overview_data, key=itemgetter(0))
193 overview_data = sorted(overview_data, key=itemgetter(0))
194
194
195 if not commits_by_day_author_aggregate:
195 if not commits_by_day_author_aggregate:
196 commits_by_day_author_aggregate[author_key_cleaner(repo.contact)] = {
196 commits_by_day_author_aggregate[author_key_cleaner(repo.contact)] = {
197 "label":author_key_cleaner(repo.contact),
197 "label":author_key_cleaner(repo.contact),
@@ -206,23 +206,23 b' def get_commits_stats(repo_name, ts_min_'
206 log.debug('last revison %s', last_rev)
206 log.debug('last revison %s', last_rev)
207 leftovers = len(repo.revisions[last_rev:])
207 leftovers = len(repo.revisions[last_rev:])
208 log.debug('revisions to parse %s', leftovers)
208 log.debug('revisions to parse %s', leftovers)
209
209
210 if last_rev == 0 or leftovers < parse_limit:
210 if last_rev == 0 or leftovers < parse_limit:
211 stats.languages = json.dumps(__get_codes_stats(repo_name))
211 stats.languages = json.dumps(__get_codes_stats(repo_name))
212
212
213 stats.repository = dbrepo
213 stats.repository = dbrepo
214 stats.stat_on_revision = last_cs.revision
214 stats.stat_on_revision = last_cs.revision
215
215
216 try:
216 try:
217 sa.add(stats)
217 sa.add(stats)
218 sa.commit()
218 sa.commit()
219 except:
219 except:
220 log.error(traceback.format_exc())
220 log.error(traceback.format_exc())
221 sa.rollback()
221 sa.rollback()
222 return False
222 return False
223 if len(repo.revisions) > 1:
223 if len(repo.revisions) > 1:
224 run_task(get_commits_stats, repo_name, ts_min_y, ts_max_y)
224 run_task(get_commits_stats, repo_name, ts_min_y, ts_max_y)
225
225
226 return True
226 return True
227
227
228 @task
228 @task
@@ -230,7 +230,7 b' def reset_user_password(user_email):'
230 log = reset_user_password.get_logger()
230 log = reset_user_password.get_logger()
231 from rhodecode.lib import auth
231 from rhodecode.lib import auth
232 from rhodecode.model.db import User
232 from rhodecode.model.db import User
233
233
234 try:
234 try:
235 try:
235 try:
236 sa = get_session()
236 sa = get_session()
@@ -244,26 +244,26 b' def reset_user_password(user_email):'
244 log.info('change password for %s', user_email)
244 log.info('change password for %s', user_email)
245 if new_passwd is None:
245 if new_passwd is None:
246 raise Exception('unable to generate new password')
246 raise Exception('unable to generate new password')
247
247
248 except:
248 except:
249 log.error(traceback.format_exc())
249 log.error(traceback.format_exc())
250 sa.rollback()
250 sa.rollback()
251
251
252 run_task(send_email, user_email,
252 run_task(send_email, user_email,
253 "Your new rhodecode password",
253 "Your new rhodecode password",
254 'Your new rhodecode password:%s' % (new_passwd))
254 'Your new rhodecode password:%s' % (new_passwd))
255 log.info('send new password mail to %s', user_email)
255 log.info('send new password mail to %s', user_email)
256
256
257
257
258 except:
258 except:
259 log.error('Failed to update user password')
259 log.error('Failed to update user password')
260 log.error(traceback.format_exc())
260 log.error(traceback.format_exc())
261 return True
261 return True
262
262
263 @task
263 @task
264 def send_email(recipients, subject, body):
264 def send_email(recipients, subject, body):
265 log = send_email.get_logger()
265 log = send_email.get_logger()
266 email_config = dict(config.items('DEFAULT'))
266 email_config = dict(config.items('DEFAULT'))
267 mail_from = email_config.get('app_email_from')
267 mail_from = email_config.get('app_email_from')
268 user = email_config.get('smtp_username')
268 user = email_config.get('smtp_username')
269 passwd = email_config.get('smtp_password')
269 passwd = email_config.get('smtp_password')
@@ -271,11 +271,11 b' def send_email(recipients, subject, body'
271 mail_port = email_config.get('smtp_port')
271 mail_port = email_config.get('smtp_port')
272 tls = email_config.get('smtp_use_tls')
272 tls = email_config.get('smtp_use_tls')
273 ssl = False
273 ssl = False
274
274
275 try:
275 try:
276 m = SmtpMailer(mail_from, user, passwd, mail_server,
276 m = SmtpMailer(mail_from, user, passwd, mail_server,
277 mail_port, ssl, tls)
277 mail_port, ssl, tls)
278 m.send(recipients, subject, body)
278 m.send(recipients, subject, body)
279 except:
279 except:
280 log.error('Mail sending failed')
280 log.error('Mail sending failed')
281 log.error(traceback.format_exc())
281 log.error(traceback.format_exc())
@@ -285,19 +285,19 b' def send_email(recipients, subject, body'
285 @task
285 @task
286 def create_repo_fork(form_data, cur_user):
286 def create_repo_fork(form_data, cur_user):
287 import os
287 import os
288 from rhodecode.model.repo_model import RepoModel
288 from rhodecode.model.repo import RepoModel
289 sa = get_session()
289 sa = get_session()
290 rm = RepoModel(sa)
290 rm = RepoModel(sa)
291
291
292 rm.create(form_data, cur_user, just_db=True, fork=True)
292 rm.create(form_data, cur_user, just_db=True, fork=True)
293
293
294 repos_path = get_hg_ui_settings()['paths_root_path'].replace('*', '')
294 repos_path = get_hg_ui_settings()['paths_root_path'].replace('*', '')
295 repo_path = os.path.join(repos_path, form_data['repo_name'])
295 repo_path = os.path.join(repos_path, form_data['repo_name'])
296 repo_fork_path = os.path.join(repos_path, form_data['fork_name'])
296 repo_fork_path = os.path.join(repos_path, form_data['fork_name'])
297
297
298 MercurialRepository(str(repo_fork_path), True, clone_url=str(repo_path))
298 MercurialRepository(str(repo_fork_path), True, clone_url=str(repo_path))
299
299
300
300
301 def __get_codes_stats(repo_name):
301 def __get_codes_stats(repo_name):
302 LANGUAGES_EXTENSIONS = ['action', 'adp', 'ashx', 'asmx', 'aspx', 'asx', 'axd', 'c',
302 LANGUAGES_EXTENSIONS = ['action', 'adp', 'ashx', 'asmx', 'aspx', 'asx', 'axd', 'c',
303 'cfg', 'cfm', 'cpp', 'cs', 'diff', 'do', 'el', 'erl',
303 'cfg', 'cfm', 'cpp', 'cs', 'diff', 'do', 'el', 'erl',
@@ -309,7 +309,7 b' def __get_codes_stats(repo_name):'
309 repos_path = get_hg_ui_settings()['paths_root_path'].replace('*', '')
309 repos_path = get_hg_ui_settings()['paths_root_path'].replace('*', '')
310 repo = MercurialRepository(repos_path + repo_name)
310 repo = MercurialRepository(repos_path + repo_name)
311 tip = repo.get_changeset()
311 tip = repo.get_changeset()
312
312
313 code_stats = {}
313 code_stats = {}
314 for topnode, dirs, files in tip.walk('/'):
314 for topnode, dirs, files in tip.walk('/'):
315 for f in files:
315 for f in files:
@@ -319,10 +319,10 b' def __get_codes_stats(repo_name):'
319 code_stats[k] += 1
319 code_stats[k] += 1
320 else:
320 else:
321 code_stats[k] = 1
321 code_stats[k] = 1
322
322
323 return code_stats or {}
323 return code_stats or {}
324
324
325
325
326
327
326
328
327
328
@@ -46,11 +46,11 b' class DbManage(object):'
46 self.tests = tests
46 self.tests = tests
47 self.root = root
47 self.root = root
48 dburi = 'sqlite:////%s' % jn(self.root, self.dbname)
48 dburi = 'sqlite:////%s' % jn(self.root, self.dbname)
49 engine = create_engine(dburi, echo=log_sql)
49 engine = create_engine(dburi, echo=log_sql)
50 init_model(engine)
50 init_model(engine)
51 self.sa = meta.Session
51 self.sa = meta.Session()
52 self.db_exists = False
52 self.db_exists = False
53
53
54 def check_for_db(self, override):
54 def check_for_db(self, override):
55 db_path = jn(self.root, self.dbname)
55 db_path = jn(self.root, self.dbname)
56 log.info('checking for existing db in %s', db_path)
56 log.info('checking for existing db in %s', db_path)
@@ -77,34 +77,34 b' class DbManage(object):'
77 checkfirst = not override
77 checkfirst = not override
78 meta.Base.metadata.create_all(checkfirst=checkfirst)
78 meta.Base.metadata.create_all(checkfirst=checkfirst)
79 log.info('Created tables for %s', self.dbname)
79 log.info('Created tables for %s', self.dbname)
80
80
81 def admin_prompt(self, second=False):
81 def admin_prompt(self, second=False):
82 if not self.tests:
82 if not self.tests:
83 import getpass
83 import getpass
84
84
85
85
86 def get_password():
86 def get_password():
87 password = getpass.getpass('Specify admin password (min 6 chars):')
87 password = getpass.getpass('Specify admin password (min 6 chars):')
88 confirm = getpass.getpass('Confirm password:')
88 confirm = getpass.getpass('Confirm password:')
89
89
90 if password != confirm:
90 if password != confirm:
91 log.error('passwords mismatch')
91 log.error('passwords mismatch')
92 return False
92 return False
93 if len(password) < 6:
93 if len(password) < 6:
94 log.error('password is to short use at least 6 characters')
94 log.error('password is to short use at least 6 characters')
95 return False
95 return False
96
96
97 return password
97 return password
98
98
99 username = raw_input('Specify admin username:')
99 username = raw_input('Specify admin username:')
100
100
101 password = get_password()
101 password = get_password()
102 if not password:
102 if not password:
103 #second try
103 #second try
104 password = get_password()
104 password = get_password()
105 if not password:
105 if not password:
106 sys.exit()
106 sys.exit()
107
107
108 email = raw_input('Specify admin email:')
108 email = raw_input('Specify admin email:')
109 self.create_user(username, password, email, True)
109 self.create_user(username, password, email, True)
110 else:
110 else:
@@ -112,68 +112,68 b' class DbManage(object):'
112 self.create_user('test_admin', 'test12', 'test_admin@mail.com', True)
112 self.create_user('test_admin', 'test12', 'test_admin@mail.com', True)
113 self.create_user('test_regular', 'test12', 'test_regular@mail.com', False)
113 self.create_user('test_regular', 'test12', 'test_regular@mail.com', False)
114 self.create_user('test_regular2', 'test12', 'test_regular2@mail.com', False)
114 self.create_user('test_regular2', 'test12', 'test_regular2@mail.com', False)
115
115
116
116
117
117
118 def config_prompt(self, test_repo_path=''):
118 def config_prompt(self, test_repo_path=''):
119 log.info('Setting up repositories config')
119 log.info('Setting up repositories config')
120
120
121 if not self.tests and not test_repo_path:
121 if not self.tests and not test_repo_path:
122 path = raw_input('Specify valid full path to your repositories'
122 path = raw_input('Specify valid full path to your repositories'
123 ' you can change this later in application settings:')
123 ' you can change this later in application settings:')
124 else:
124 else:
125 path = test_repo_path
125 path = test_repo_path
126
126
127 if not os.path.isdir(path):
127 if not os.path.isdir(path):
128 log.error('You entered wrong path: %s', path)
128 log.error('You entered wrong path: %s', path)
129 sys.exit()
129 sys.exit()
130
130
131 hooks1 = RhodeCodeUi()
131 hooks1 = RhodeCodeUi()
132 hooks1.ui_section = 'hooks'
132 hooks1.ui_section = 'hooks'
133 hooks1.ui_key = 'changegroup.update'
133 hooks1.ui_key = 'changegroup.update'
134 hooks1.ui_value = 'hg update >&2'
134 hooks1.ui_value = 'hg update >&2'
135 hooks1.ui_active = False
135 hooks1.ui_active = False
136
136
137 hooks2 = RhodeCodeUi()
137 hooks2 = RhodeCodeUi()
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 web1 = RhodeCodeUi()
142 web1 = RhodeCodeUi()
143 web1.ui_section = 'web'
143 web1.ui_section = 'web'
144 web1.ui_key = 'push_ssl'
144 web1.ui_key = 'push_ssl'
145 web1.ui_value = 'false'
145 web1.ui_value = 'false'
146
146
147 web2 = RhodeCodeUi()
147 web2 = RhodeCodeUi()
148 web2.ui_section = 'web'
148 web2.ui_section = 'web'
149 web2.ui_key = 'allow_archive'
149 web2.ui_key = 'allow_archive'
150 web2.ui_value = 'gz zip bz2'
150 web2.ui_value = 'gz zip bz2'
151
151
152 web3 = RhodeCodeUi()
152 web3 = RhodeCodeUi()
153 web3.ui_section = 'web'
153 web3.ui_section = 'web'
154 web3.ui_key = 'allow_push'
154 web3.ui_key = 'allow_push'
155 web3.ui_value = '*'
155 web3.ui_value = '*'
156
156
157 web4 = RhodeCodeUi()
157 web4 = RhodeCodeUi()
158 web4.ui_section = 'web'
158 web4.ui_section = 'web'
159 web4.ui_key = 'baseurl'
159 web4.ui_key = 'baseurl'
160 web4.ui_value = '/'
160 web4.ui_value = '/'
161
161
162 paths = RhodeCodeUi()
162 paths = RhodeCodeUi()
163 paths.ui_section = 'paths'
163 paths.ui_section = 'paths'
164 paths.ui_key = '/'
164 paths.ui_key = '/'
165 paths.ui_value = os.path.join(path, '*')
165 paths.ui_value = os.path.join(path, '*')
166
166
167
167
168 hgsettings1 = RhodeCodeSettings()
168 hgsettings1 = RhodeCodeSettings()
169
169
170 hgsettings1.app_settings_name = 'realm'
170 hgsettings1.app_settings_name = 'realm'
171 hgsettings1.app_settings_value = 'RhodeCode authentication'
171 hgsettings1.app_settings_value = 'RhodeCode authentication'
172
172
173 hgsettings2 = RhodeCodeSettings()
173 hgsettings2 = RhodeCodeSettings()
174 hgsettings2.app_settings_name = 'title'
174 hgsettings2.app_settings_name = 'title'
175 hgsettings2.app_settings_value = 'RhodeCode'
175 hgsettings2.app_settings_value = 'RhodeCode'
176
176
177 try:
177 try:
178 self.sa.add(hooks1)
178 self.sa.add(hooks1)
179 self.sa.add(hooks2)
179 self.sa.add(hooks2)
@@ -187,9 +187,9 b' class DbManage(object):'
187 self.sa.commit()
187 self.sa.commit()
188 except:
188 except:
189 self.sa.rollback()
189 self.sa.rollback()
190 raise
190 raise
191 log.info('created ui config')
191 log.info('created ui config')
192
192
193 def create_user(self, username, password, email='', admin=False):
193 def create_user(self, username, password, email='', admin=False):
194 log.info('creating administrator user %s', username)
194 log.info('creating administrator user %s', username)
195 new_user = User()
195 new_user = User()
@@ -200,7 +200,7 b' class DbManage(object):'
200 new_user.email = email
200 new_user.email = email
201 new_user.admin = admin
201 new_user.admin = admin
202 new_user.active = True
202 new_user.active = True
203
203
204 try:
204 try:
205 self.sa.add(new_user)
205 self.sa.add(new_user)
206 self.sa.commit()
206 self.sa.commit()
@@ -225,7 +225,7 b' class DbManage(object):'
225 except:
225 except:
226 self.sa.rollback()
226 self.sa.rollback()
227 raise
227 raise
228
228
229 def create_permissions(self):
229 def create_permissions(self):
230 #module.(access|create|change|delete)_[name]
230 #module.(access|create|change|delete)_[name]
231 #module.(read|write|owner)
231 #module.(read|write|owner)
@@ -240,7 +240,7 b' class DbManage(object):'
240 ('hg.register.manual_activate', 'Register new user with rhodecode without manual activation'),
240 ('hg.register.manual_activate', 'Register new user with rhodecode without manual activation'),
241 ('hg.register.auto_activate', 'Register new user with rhodecode without auto activation'),
241 ('hg.register.auto_activate', 'Register new user with rhodecode without auto activation'),
242 ]
242 ]
243
243
244 for p in perms:
244 for p in perms:
245 new_perm = Permission()
245 new_perm = Permission()
246 new_perm.permission_name = p[0]
246 new_perm.permission_name = p[0]
@@ -254,28 +254,28 b' class DbManage(object):'
254
254
255 def populate_default_permissions(self):
255 def populate_default_permissions(self):
256 log.info('creating default user permissions')
256 log.info('creating default user permissions')
257
257
258 default_user = self.sa.query(User)\
258 default_user = self.sa.query(User)\
259 .filter(User.username == 'default').scalar()
259 .filter(User.username == 'default').scalar()
260
260
261 reg_perm = UserToPerm()
261 reg_perm = UserToPerm()
262 reg_perm.user = default_user
262 reg_perm.user = default_user
263 reg_perm.permission = self.sa.query(Permission)\
263 reg_perm.permission = self.sa.query(Permission)\
264 .filter(Permission.permission_name == 'hg.register.manual_activate')\
264 .filter(Permission.permission_name == 'hg.register.manual_activate')\
265 .scalar()
265 .scalar()
266
266
267 create_repo_perm = UserToPerm()
267 create_repo_perm = UserToPerm()
268 create_repo_perm.user = default_user
268 create_repo_perm.user = default_user
269 create_repo_perm.permission = self.sa.query(Permission)\
269 create_repo_perm.permission = self.sa.query(Permission)\
270 .filter(Permission.permission_name == 'hg.create.repository')\
270 .filter(Permission.permission_name == 'hg.create.repository')\
271 .scalar()
271 .scalar()
272
272
273 default_repo_perm = UserToPerm()
273 default_repo_perm = UserToPerm()
274 default_repo_perm.user = default_user
274 default_repo_perm.user = default_user
275 default_repo_perm.permission = self.sa.query(Permission)\
275 default_repo_perm.permission = self.sa.query(Permission)\
276 .filter(Permission.permission_name == 'repository.read')\
276 .filter(Permission.permission_name == 'repository.read')\
277 .scalar()
277 .scalar()
278
278
279 try:
279 try:
280 self.sa.add(reg_perm)
280 self.sa.add(reg_perm)
281 self.sa.add(create_repo_perm)
281 self.sa.add(create_repo_perm)
@@ -283,5 +283,5 b' class DbManage(object):'
283 self.sa.commit()
283 self.sa.commit()
284 except:
284 except:
285 self.sa.rollback()
285 self.sa.rollback()
286 raise
286 raise
287
287
@@ -59,7 +59,7 b' def user_action_mapper(ui, repo, hooktyp'
59 """
59 """
60
60
61 try:
61 try:
62 sa = meta.Session
62 sa = meta.Session()
63 username = kwargs['url'].split(':')[-1]
63 username = kwargs['url'].split(':')[-1]
64 user_log = sa.query(UserLog)\
64 user_log = sa.query(UserLog)\
65 .filter(UserLog.user == sa.query(User)\
65 .filter(UserLog.user == sa.query(User)\
@@ -1,6 +1,6 b''
1 from os.path import dirname as dn, join as jn
1 from os.path import dirname as dn, join as jn
2 from rhodecode.config.environment import load_environment
2 from rhodecode.config.environment import load_environment
3 from rhodecode.model.hg_model import HgModel
3 from rhodecode.model.hg import HgModel
4 from shutil import rmtree
4 from shutil import rmtree
5 from webhelpers.html.builder import escape
5 from webhelpers.html.builder import escape
6 from vcs.utils.lazy import LazyProperty
6 from vcs.utils.lazy import LazyProperty
@@ -33,7 +33,7 b' project_path = dn(dn(dn(dn(os.path.realp'
33 sys.path.append(project_path)
33 sys.path.append(project_path)
34
34
35 from rhodecode.lib.pidlock import LockHeld, DaemonLock
35 from rhodecode.lib.pidlock import LockHeld, DaemonLock
36 from rhodecode.model.hg_model import HgModel
36 from rhodecode.model.hg import HgModel
37 from rhodecode.lib.helpers import safe_unicode
37 from rhodecode.lib.helpers import safe_unicode
38 from whoosh.index import create_in, open_dir
38 from whoosh.index import create_in, open_dir
39 from shutil import rmtree
39 from shutil import rmtree
@@ -30,10 +30,10 b' from mercurial.hgweb import hgweb'
30 from mercurial.hgweb.request import wsgiapplication
30 from mercurial.hgweb.request import wsgiapplication
31 from paste.auth.basic import AuthBasicAuthenticator
31 from paste.auth.basic import AuthBasicAuthenticator
32 from paste.httpheaders import REMOTE_USER, AUTH_TYPE
32 from paste.httpheaders import REMOTE_USER, AUTH_TYPE
33 from rhodecode.lib.auth import authfunc, HasPermissionAnyMiddleware, \
33 from rhodecode.lib.auth import authfunc, HasPermissionAnyMiddleware
34 get_user_cached
35 from rhodecode.lib.utils import is_mercurial, make_ui, invalidate_cache, \
34 from rhodecode.lib.utils import is_mercurial, make_ui, invalidate_cache, \
36 check_repo_fast, ui_sections
35 check_repo_fast, ui_sections
36 from rhodecode.model.user import UserModel
37 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError
37 from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError
38 from rhodecode.lib.utils import action_logger
38 from rhodecode.lib.utils import action_logger
39 import logging
39 import logging
@@ -163,7 +163,7 b' class SimpleHg(object):'
163 return environ.get('REMOTE_USER')
163 return environ.get('REMOTE_USER')
164
164
165 def __get_user(self, username):
165 def __get_user(self, username):
166 return get_user_cached(username)
166 return UserModel().get_by_username(username, cache=True)
167
167
168 def __get_action(self, environ):
168 def __get_action(self, environ):
169 """
169 """
@@ -22,10 +22,12 b' Created on April 18, 2010'
22 Utilities for RhodeCode
22 Utilities for RhodeCode
23 @author: marcink
23 @author: marcink
24 """
24 """
25 from beaker.cache import cache_region
25 from rhodecode.model.caching_query import FromCache
26 from mercurial import ui, config, hg
26 from mercurial import ui, config, hg
27 from mercurial.error import RepoError
27 from mercurial.error import RepoError
28 from rhodecode.model import meta
28 from rhodecode.model import meta
29 from rhodecode.model.user import UserModel
30 from rhodecode.model.repo import RepoModel
29 from rhodecode.model.db import Repository, User, RhodeCodeUi, RhodeCodeSettings, UserLog
31 from rhodecode.model.db import Repository, User, RhodeCodeUi, RhodeCodeSettings, UserLog
30 from vcs.backends.base import BaseChangeset
32 from vcs.backends.base import BaseChangeset
31 from vcs.utils.lazy import LazyProperty
33 from vcs.utils.lazy import LazyProperty
@@ -67,13 +69,13 b' def action_logger(user, action, repo, ip'
67 """
69 """
68
70
69 if not sa:
71 if not sa:
70 sa = meta.Session
72 sa = meta.Session()
71
73
72 try:
74 try:
73 if hasattr(user, 'user_id'):
75 if hasattr(user, 'user_id'):
74 user_id = user.user_id
76 user_id = user.user_id
75 elif isinstance(user, basestring):
77 elif isinstance(user, basestring):
76 user_id = sa.query(User).filter(User.username == user).one()
78 user_id = UserModel(sa).get_by_username(user, cache=False).user_id
77 else:
79 else:
78 raise Exception('You have to provide user object or username')
80 raise Exception('You have to provide user object or username')
79
81
@@ -82,8 +84,7 b' def action_logger(user, action, repo, ip'
82 user_log.user_id = user_id
84 user_log.user_id = user_id
83 user_log.action = action
85 user_log.action = action
84 user_log.repository_name = repo_name
86 user_log.repository_name = repo_name
85 user_log.repository = sa.query(Repository)\
87 user_log.repository = RepoModel(sa).get(repo_name, cache=False)
86 .filter(Repository.repo_name == repo_name).one()
87 user_log.action_date = datetime.datetime.now()
88 user_log.action_date = datetime.datetime.now()
88 user_log.user_ip = ipaddr
89 user_log.user_ip = ipaddr
89 sa.add(user_log)
90 sa.add(user_log)
@@ -135,11 +136,14 b' def ask_ok(prompt, retries=4, complaint='
135 if retries < 0: raise IOError
136 if retries < 0: raise IOError
136 print complaint
137 print complaint
137
138
138 @cache_region('super_short_term', 'cached_hg_ui')
139 def get_hg_ui_cached():
139 def get_hg_ui_cached():
140 try:
140 try:
141 sa = meta.Session
141 sa = meta.Session
142 ret = sa.query(RhodeCodeUi).all()
142 ret = sa.query(RhodeCodeUi)\
143 .options(FromCache("sql_cache_short", "get_hg_ui_settings"))\
144 .all()
145 except:
146 pass
143 finally:
147 finally:
144 meta.Session.remove()
148 meta.Session.remove()
145 return ret
149 return ret
@@ -147,8 +151,12 b' def get_hg_ui_cached():'
147
151
148 def get_hg_settings():
152 def get_hg_settings():
149 try:
153 try:
150 sa = meta.Session
154 sa = meta.Session()
151 ret = sa.query(RhodeCodeSettings).all()
155 ret = sa.query(RhodeCodeSettings)\
156 .options(FromCache("sql_cache_short", "get_hg_settings"))\
157 .all()
158 except:
159 pass
152 finally:
160 finally:
153 meta.Session.remove()
161 meta.Session.remove()
154
162
@@ -162,8 +170,10 b' def get_hg_settings():'
162
170
163 def get_hg_ui_settings():
171 def get_hg_ui_settings():
164 try:
172 try:
165 sa = meta.Session
173 sa = meta.Session()
166 ret = sa.query(RhodeCodeUi).all()
174 ret = sa.query(RhodeCodeUi).all()
175 except:
176 pass
167 finally:
177 finally:
168 meta.Session.remove()
178 meta.Session.remove()
169
179
@@ -255,11 +265,11 b' def invalidate_cache(name, *args):'
255 args = tuple(tmp)
265 args = tuple(tmp)
256
266
257 if name == 'cached_repo_list':
267 if name == 'cached_repo_list':
258 from rhodecode.model.hg_model import _get_repos_cached
268 from rhodecode.model.hg import _get_repos_cached
259 region_invalidate(_get_repos_cached, None, *args)
269 region_invalidate(_get_repos_cached, None, *args)
260
270
261 if name == 'full_changelog':
271 if name == 'full_changelog':
262 from rhodecode.model.hg_model import _full_changelog_cached
272 from rhodecode.model.hg import _full_changelog_cached
263 region_invalidate(_full_changelog_cached, None, *args)
273 region_invalidate(_full_changelog_cached, None, *args)
264
274
265 class EmptyChangeset(BaseChangeset):
275 class EmptyChangeset(BaseChangeset):
@@ -296,15 +306,14 b' def repo2db_mapper(initial_repo_list, re'
296 """
306 """
297 maps all found repositories into db
307 maps all found repositories into db
298 """
308 """
299 from rhodecode.model.repo_model import RepoModel
300
309
301 sa = meta.Session
310 sa = meta.Session()
302 user = sa.query(User).filter(User.admin == True).first()
311 user = sa.query(User).filter(User.admin == True).first()
303
312
304 rm = RepoModel()
313 rm = RepoModel()
305
314
306 for name, repo in initial_repo_list.items():
315 for name, repo in initial_repo_list.items():
307 if not sa.query(Repository).filter(Repository.repo_name == name).scalar():
316 if not RepoModel(sa).get(name, cache=False):
308 log.info('repository %s not found creating default', name)
317 log.info('repository %s not found creating default', name)
309
318
310 form_data = {
319 form_data = {
@@ -429,7 +438,7 b' class OrderedDict(dict, DictMixin):'
429
438
430
439
431 #===============================================================================
440 #===============================================================================
432 # TEST FUNCTIONS
441 # TEST FUNCTIONS AND CREATORS
433 #===============================================================================
442 #===============================================================================
434 def create_test_index(repo_location, full_index):
443 def create_test_index(repo_location, full_index):
435 """Makes default test index
444 """Makes default test index
@@ -26,22 +26,21 b' from pylons import session'
26 from pylons.i18n.translation import _
26 from pylons.i18n.translation import _
27 from rhodecode.lib.auth import check_password, get_crypt_password
27 from rhodecode.lib.auth import check_password, get_crypt_password
28 from rhodecode.model import meta
28 from rhodecode.model import meta
29 from rhodecode.model.user_model import UserModel
29 from rhodecode.model.user import UserModel
30 from rhodecode.model.db import User, Repository
30 from rhodecode.model.repo import RepoModel
31 from sqlalchemy.exc import OperationalError
31 from rhodecode.model.db import User
32 from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
33 from webhelpers.pylonslib.secure_form import authentication_token
32 from webhelpers.pylonslib.secure_form import authentication_token
34 import formencode
33 import formencode
35 import logging
34 import logging
36 import os
35 import os
37 import rhodecode.lib.helpers as h
36 import rhodecode.lib.helpers as h
37
38 log = logging.getLogger(__name__)
38 log = logging.getLogger(__name__)
39
39
40
41 #this is needed to translate the messages using _() in validators
40 #this is needed to translate the messages using _() in validators
42 class State_obj(object):
41 class State_obj(object):
43 _ = staticmethod(_)
42 _ = staticmethod(_)
44
43
45 #===============================================================================
44 #===============================================================================
46 # VALIDATORS
45 # VALIDATORS
47 #===============================================================================
46 #===============================================================================
@@ -53,53 +52,51 b' class ValidAuthToken(formencode.validato'
53 if value != authentication_token():
52 if value != authentication_token():
54 raise formencode.Invalid(self.message('invalid_token', state,
53 raise formencode.Invalid(self.message('invalid_token', state,
55 search_number=value), value, state)
54 search_number=value), value, state)
56
55
57 def ValidUsername(edit, old_data):
56 def ValidUsername(edit, old_data):
58 class _ValidUsername(formencode.validators.FancyValidator):
57 class _ValidUsername(formencode.validators.FancyValidator):
59
58
60 def validate_python(self, value, state):
59 def validate_python(self, value, state):
61 if value in ['default', 'new_user']:
60 if value in ['default', 'new_user']:
62 raise formencode.Invalid(_('Invalid username'), value, state)
61 raise formencode.Invalid(_('Invalid username'), value, state)
63 #check if user is uniq
62 #check if user is unique
64 sa = meta.Session
65 old_un = None
63 old_un = None
66 if edit:
64 if edit:
67 old_un = sa.query(User).get(old_data.get('user_id')).username
65 old_un = UserModel().get(old_data.get('user_id')).username
68
66
69 if old_un != value or not edit:
67 if old_un != value or not edit:
70 if sa.query(User).filter(User.username == value).scalar():
68 if UserModel().get_by_username(value, cache=False):
71 raise formencode.Invalid(_('This username already exists') ,
69 raise formencode.Invalid(_('This username already exists') ,
72 value, state)
70 value, state)
73 meta.Session.remove()
71
74
72 return _ValidUsername
75 return _ValidUsername
73
76
77 class ValidPassword(formencode.validators.FancyValidator):
74 class ValidPassword(formencode.validators.FancyValidator):
78
75
79 def to_python(self, value, state):
76 def to_python(self, value, state):
80 if value:
77 if value:
81 return get_crypt_password(value)
78 return get_crypt_password(value)
82
79
83 class ValidAuth(formencode.validators.FancyValidator):
80 class ValidAuth(formencode.validators.FancyValidator):
84 messages = {
81 messages = {
85 'invalid_password':_('invalid password'),
82 'invalid_password':_('invalid password'),
86 'invalid_login':_('invalid user name'),
83 'invalid_login':_('invalid user name'),
87 'disabled_account':_('Your acccount is disabled')
84 'disabled_account':_('Your acccount is disabled')
88
85
89 }
86 }
90 #error mapping
87 #error mapping
91 e_dict = {'username':messages['invalid_login'],
88 e_dict = {'username':messages['invalid_login'],
92 'password':messages['invalid_password']}
89 'password':messages['invalid_password']}
93 e_dict_disable = {'username':messages['disabled_account']}
90 e_dict_disable = {'username':messages['disabled_account']}
94
91
95 def validate_python(self, value, state):
92 def validate_python(self, value, state):
96 password = value['password']
93 password = value['password']
97 username = value['username']
94 username = value['username']
98 user = UserModel().get_user_by_name(username)
95 user = UserModel().get_by_username(username)
99 if user is None:
96 if user is None:
100 raise formencode.Invalid(self.message('invalid_password',
97 raise formencode.Invalid(self.message('invalid_password',
101 state=State_obj), value, state,
98 state=State_obj), value, state,
102 error_dict=self.e_dict)
99 error_dict=self.e_dict)
103 if user:
100 if user:
104 if user.active:
101 if user.active:
105 if user.username == username and check_password(password,
102 if user.username == username and check_password(password,
@@ -116,12 +113,13 b' class ValidAuth(formencode.validators.Fa'
116 state=State_obj),
113 state=State_obj),
117 value, state,
114 value, state,
118 error_dict=self.e_dict_disable)
115 error_dict=self.e_dict_disable)
119
116
120 class ValidRepoUser(formencode.validators.FancyValidator):
117 class ValidRepoUser(formencode.validators.FancyValidator):
121
118
122 def to_python(self, value, state):
119 def to_python(self, value, state):
120 sa = meta.Session()
123 try:
121 try:
124 self.user_db = meta.Session.query(User)\
122 self.user_db = sa.query(User)\
125 .filter(User.active == True)\
123 .filter(User.active == True)\
126 .filter(User.username == value).one()
124 .filter(User.username == value).one()
127 except Exception:
125 except Exception:
@@ -129,31 +127,29 b' class ValidRepoUser(formencode.validator'
129 value, state)
127 value, state)
130 finally:
128 finally:
131 meta.Session.remove()
129 meta.Session.remove()
132
130
133 return self.user_db.user_id
131 return self.user_db.user_id
134
132
135 def ValidRepoName(edit, old_data):
133 def ValidRepoName(edit, old_data):
136 class _ValidRepoName(formencode.validators.FancyValidator):
134 class _ValidRepoName(formencode.validators.FancyValidator):
137
135
138 def to_python(self, value, state):
136 def to_python(self, value, state):
139 slug = h.repo_name_slug(value)
137 slug = h.repo_name_slug(value)
140 if slug in ['_admin']:
138 if slug in ['_admin']:
141 raise formencode.Invalid(_('This repository name is disallowed'),
139 raise formencode.Invalid(_('This repository name is disallowed'),
142 value, state)
140 value, state)
143 if old_data.get('repo_name') != value or not edit:
141 if old_data.get('repo_name') != value or not edit:
144 sa = meta.Session
142 if RepoModel().get(slug, cache=False):
145 if sa.query(Repository).filter(Repository.repo_name == slug).scalar():
146 raise formencode.Invalid(_('This repository already exists') ,
143 raise formencode.Invalid(_('This repository already exists') ,
147 value, state)
144 value, state)
148 meta.Session.remove()
145 return slug
149 return slug
146
150
147
151
152 return _ValidRepoName
148 return _ValidRepoName
153
149
154 class ValidPerms(formencode.validators.FancyValidator):
150 class ValidPerms(formencode.validators.FancyValidator):
155 messages = {'perm_new_user_name':_('This username is not valid')}
151 messages = {'perm_new_user_name':_('This username is not valid')}
156
152
157 def to_python(self, value, state):
153 def to_python(self, value, state):
158 perms_update = []
154 perms_update = []
159 perms_new = []
155 perms_new = []
@@ -167,7 +163,7 b' class ValidPerms(formencode.validators.F'
167 if (new_user, new_perm) not in perms_new:
163 if (new_user, new_perm) not in perms_new:
168 perms_new.append((new_user, new_perm))
164 perms_new.append((new_user, new_perm))
169 else:
165 else:
170 usr = k[5:]
166 usr = k[5:]
171 if usr == 'default':
167 if usr == 'default':
172 if value['private']:
168 if value['private']:
173 #set none for default when updating to private repo
169 #set none for default when updating to private repo
@@ -184,36 +180,36 b' class ValidPerms(formencode.validators.F'
184 except Exception:
180 except Exception:
185 msg = self.message('perm_new_user_name',
181 msg = self.message('perm_new_user_name',
186 state=State_obj)
182 state=State_obj)
187 raise formencode.Invalid(msg, value, state, error_dict={'perm_new_user_name':msg})
183 raise formencode.Invalid(msg, value, state, error_dict={'perm_new_user_name':msg})
188 return value
184 return value
189
185
190 class ValidSettings(formencode.validators.FancyValidator):
186 class ValidSettings(formencode.validators.FancyValidator):
191
187
192 def to_python(self, value, state):
188 def to_python(self, value, state):
193 #settings form can't edit user
189 #settings form can't edit user
194 if value.has_key('user'):
190 if value.has_key('user'):
195 del['value']['user']
191 del['value']['user']
196
192
197 return value
193 return value
198
194
199 class ValidPath(formencode.validators.FancyValidator):
195 class ValidPath(formencode.validators.FancyValidator):
200 def to_python(self, value, state):
196 def to_python(self, value, state):
201 isdir = os.path.isdir(value.replace('*', ''))
197 isdir = os.path.isdir(value.replace('*', ''))
202 if (value.endswith('/*') or value.endswith('/**')) and isdir:
198 if (value.endswith('/*') or value.endswith('/**')) and isdir:
203 return value
199 return value
204 elif not isdir:
200 elif not isdir:
205 msg = _('This is not a valid path')
201 msg = _('This is not a valid path')
206 else:
202 else:
207 msg = _('You need to specify * or ** at the end of path (ie. /tmp/*)')
203 msg = _('You need to specify * or ** at the end of path (ie. /tmp/*)')
208
204
209 raise formencode.Invalid(msg, value, state,
205 raise formencode.Invalid(msg, value, state,
210 error_dict={'paths_root_path':msg})
206 error_dict={'paths_root_path':msg})
211
207
212 def UniqSystemEmail(old_data):
208 def UniqSystemEmail(old_data):
213 class _UniqSystemEmail(formencode.validators.FancyValidator):
209 class _UniqSystemEmail(formencode.validators.FancyValidator):
214 def to_python(self, value, state):
210 def to_python(self, value, state):
215 if old_data.get('email') != value:
211 if old_data.get('email') != value:
216 sa = meta.Session
212 sa = meta.Session()
217 try:
213 try:
218 user = sa.query(User).filter(User.email == value).scalar()
214 user = sa.query(User).filter(User.email == value).scalar()
219 if user:
215 if user:
@@ -221,11 +217,11 b' def UniqSystemEmail(old_data):'
221 value, state)
217 value, state)
222 finally:
218 finally:
223 meta.Session.remove()
219 meta.Session.remove()
224
220
225 return value
221 return value
226
222
227 return _UniqSystemEmail
223 return _UniqSystemEmail
228
224
229 class ValidSystemEmail(formencode.validators.FancyValidator):
225 class ValidSystemEmail(formencode.validators.FancyValidator):
230 def to_python(self, value, state):
226 def to_python(self, value, state):
231 sa = meta.Session
227 sa = meta.Session
@@ -236,8 +232,8 b' class ValidSystemEmail(formencode.valida'
236 value, state)
232 value, state)
237 finally:
233 finally:
238 meta.Session.remove()
234 meta.Session.remove()
239
235
240 return value
236 return value
241
237
242 #===============================================================================
238 #===============================================================================
243 # FORMS
239 # FORMS
@@ -266,7 +262,7 b' class LoginForm(formencode.Schema):'
266
262
267 #chained validators have access to all data
263 #chained validators have access to all data
268 chained_validators = [ValidAuth]
264 chained_validators = [ValidAuth]
269
265
270 def UserForm(edit=False, old_data={}):
266 def UserForm(edit=False, old_data={}):
271 class _UserForm(formencode.Schema):
267 class _UserForm(formencode.Schema):
272 allow_extra_fields = True
268 allow_extra_fields = True
@@ -281,7 +277,7 b' def UserForm(edit=False, old_data={}):'
281 name = UnicodeString(strip=True, min=1, not_empty=True)
277 name = UnicodeString(strip=True, min=1, not_empty=True)
282 lastname = UnicodeString(strip=True, min=1, not_empty=True)
278 lastname = UnicodeString(strip=True, min=1, not_empty=True)
283 email = All(Email(not_empty=True), UniqSystemEmail(old_data))
279 email = All(Email(not_empty=True), UniqSystemEmail(old_data))
284
280
285 return _UserForm
281 return _UserForm
286
282
287 RegisterForm = UserForm
283 RegisterForm = UserForm
@@ -290,7 +286,7 b' def PasswordResetForm():'
290 class _PasswordResetForm(formencode.Schema):
286 class _PasswordResetForm(formencode.Schema):
291 allow_extra_fields = True
287 allow_extra_fields = True
292 filter_extra_fields = True
288 filter_extra_fields = True
293 email = All(ValidSystemEmail(), Email(not_empty=True))
289 email = All(ValidSystemEmail(), Email(not_empty=True))
294 return _PasswordResetForm
290 return _PasswordResetForm
295
291
296 def RepoForm(edit=False, old_data={}):
292 def RepoForm(edit=False, old_data={}):
@@ -300,10 +296,10 b' def RepoForm(edit=False, old_data={}):'
300 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit, old_data))
296 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit, old_data))
301 description = UnicodeString(strip=True, min=1, not_empty=True)
297 description = UnicodeString(strip=True, min=1, not_empty=True)
302 private = StringBoolean(if_missing=False)
298 private = StringBoolean(if_missing=False)
303
299
304 if edit:
300 if edit:
305 user = All(Int(not_empty=True), ValidRepoUser)
301 user = All(Int(not_empty=True), ValidRepoUser)
306
302
307 chained_validators = [ValidPerms]
303 chained_validators = [ValidPerms]
308 return _RepoForm
304 return _RepoForm
309
305
@@ -314,7 +310,7 b' def RepoForkForm(edit=False, old_data={}'
314 fork_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit, old_data))
310 fork_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit, old_data))
315 description = UnicodeString(strip=True, min=1, not_empty=True)
311 description = UnicodeString(strip=True, min=1, not_empty=True)
316 private = StringBoolean(if_missing=False)
312 private = StringBoolean(if_missing=False)
317
313
318 return _RepoForkForm
314 return _RepoForkForm
319
315
320 def RepoSettingsForm(edit=False, old_data={}):
316 def RepoSettingsForm(edit=False, old_data={}):
@@ -324,7 +320,7 b' def RepoSettingsForm(edit=False, old_dat'
324 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit, old_data))
320 repo_name = All(UnicodeString(strip=True, min=1, not_empty=True), ValidRepoName(edit, old_data))
325 description = UnicodeString(strip=True, min=1, not_empty=True)
321 description = UnicodeString(strip=True, min=1, not_empty=True)
326 private = StringBoolean(if_missing=False)
322 private = StringBoolean(if_missing=False)
327
323
328 chained_validators = [ValidPerms, ValidSettings]
324 chained_validators = [ValidPerms, ValidSettings]
329 return _RepoForm
325 return _RepoForm
330
326
@@ -335,9 +331,9 b' def ApplicationSettingsForm():'
335 filter_extra_fields = False
331 filter_extra_fields = False
336 rhodecode_title = UnicodeString(strip=True, min=1, not_empty=True)
332 rhodecode_title = UnicodeString(strip=True, min=1, not_empty=True)
337 rhodecode_realm = UnicodeString(strip=True, min=1, not_empty=True)
333 rhodecode_realm = UnicodeString(strip=True, min=1, not_empty=True)
338
334
339 return _ApplicationSettingsForm
335 return _ApplicationSettingsForm
340
336
341 def ApplicationUiSettingsForm():
337 def ApplicationUiSettingsForm():
342 class _ApplicationUiSettingsForm(formencode.Schema):
338 class _ApplicationUiSettingsForm(formencode.Schema):
343 allow_extra_fields = True
339 allow_extra_fields = True
@@ -346,7 +342,7 b' def ApplicationUiSettingsForm():'
346 paths_root_path = All(ValidPath(), UnicodeString(strip=True, min=1, not_empty=True))
342 paths_root_path = All(ValidPath(), UnicodeString(strip=True, min=1, not_empty=True))
347 hooks_changegroup_update = OneOf(['True', 'False'], if_missing=False)
343 hooks_changegroup_update = OneOf(['True', 'False'], if_missing=False)
348 hooks_changegroup_repo_size = OneOf(['True', 'False'], if_missing=False)
344 hooks_changegroup_repo_size = OneOf(['True', 'False'], if_missing=False)
349
345
350 return _ApplicationUiSettingsForm
346 return _ApplicationUiSettingsForm
351
347
352 def DefaultPermissionsForm(perms_choices, register_choices, create_choices):
348 def DefaultPermissionsForm(perms_choices, register_choices, create_choices):
@@ -357,5 +353,5 b' def DefaultPermissionsForm(perms_choices'
357 default_perm = OneOf(perms_choices)
353 default_perm = OneOf(perms_choices)
358 default_register = OneOf(register_choices)
354 default_register = OneOf(register_choices)
359 default_create = OneOf(create_choices)
355 default_create = OneOf(create_choices)
360
356
361 return _DefaultPermissionsForm
357 return _DefaultPermissionsForm
@@ -25,7 +25,6 b' Model for RhodeCode'
25 from beaker.cache import cache_region
25 from beaker.cache import cache_region
26 from mercurial import ui
26 from mercurial import ui
27 from mercurial.hgweb.hgwebdir_mod import findrepos
27 from mercurial.hgweb.hgwebdir_mod import findrepos
28 from pylons.i18n.translation import _
29 from rhodecode.lib import helpers as h
28 from rhodecode.lib import helpers as h
30 from rhodecode.lib.utils import invalidate_cache
29 from rhodecode.lib.utils import invalidate_cache
31 from rhodecode.lib.auth import HasRepoPermissionAny
30 from rhodecode.lib.auth import HasRepoPermissionAny
@@ -65,7 +64,7 b' def _get_repos_switcher_cached(cached_re'
65 if HasRepoPermissionAny('repository.write', 'repository.read',
64 if HasRepoPermissionAny('repository.write', 'repository.read',
66 'repository.admin')(repo.name, 'main page check'):
65 'repository.admin')(repo.name, 'main page check'):
67 repos_lst.append((repo.name, repo.dbrepo.private,))
66 repos_lst.append((repo.name, repo.dbrepo.private,))
68
67
69 return sorted(repos_lst, key=lambda k:k[0].lower())
68 return sorted(repos_lst, key=lambda k:k[0].lower())
70
69
71 @cache_region('long_term', 'full_changelog')
70 @cache_region('long_term', 'full_changelog')
@@ -79,7 +78,7 b' class HgModel(object):'
79
78
80 def __init__(self):
79 def __init__(self):
81 pass
80 pass
82
81
83 @staticmethod
82 @staticmethod
84 def repo_scan(repos_prefix, repos_path, baseui, initial=False):
83 def repo_scan(repos_prefix, repos_path, baseui, initial=False):
85 """
84 """
@@ -99,17 +98,17 b' class HgModel(object):'
99 if repos_path[0] != '/':
98 if repos_path[0] != '/':
100 repos_path[0] = '/'
99 repos_path[0] = '/'
101 if not os.path.isdir(os.path.join(*repos_path)):
100 if not os.path.isdir(os.path.join(*repos_path)):
102 raise RepositoryError('Not a valid repository in %s' % path)
101 raise RepositoryError('Not a valid repository in %s' % path)
103 if not repos_path.endswith('*'):
102 if not repos_path.endswith('*'):
104 raise VCSError('You need to specify * or ** at the end of path '
103 raise VCSError('You need to specify * or ** at the end of path '
105 'for recursive scanning')
104 'for recursive scanning')
106
105
107 check_repo_dir(repos_path)
106 check_repo_dir(repos_path)
108 log.info('scanning for repositories in %s', repos_path)
107 log.info('scanning for repositories in %s', repos_path)
109 repos = findrepos([(repos_prefix, repos_path)])
108 repos = findrepos([(repos_prefix, repos_path)])
110 if not isinstance(baseui, ui.ui):
109 if not isinstance(baseui, ui.ui):
111 baseui = ui.ui()
110 baseui = ui.ui()
112
111
113 repos_list = {}
112 repos_list = {}
114 for name, path in repos:
113 for name, path in repos:
115 try:
114 try:
@@ -118,10 +117,10 b' class HgModel(object):'
118 raise RepositoryError('Duplicate repository name %s found in'
117 raise RepositoryError('Duplicate repository name %s found in'
119 ' %s' % (name, path))
118 ' %s' % (name, path))
120 else:
119 else:
121
120
122 repos_list[name] = MercurialRepository(path, baseui=baseui)
121 repos_list[name] = MercurialRepository(path, baseui=baseui)
123 repos_list[name].name = name
122 repos_list[name].name = name
124
123
125 dbrepo = None
124 dbrepo = None
126 if not initial:
125 if not initial:
127 #for initial scann on application first run we don't
126 #for initial scann on application first run we don't
@@ -130,7 +129,7 b' class HgModel(object):'
130 .options(joinedload(Repository.fork))\
129 .options(joinedload(Repository.fork))\
131 .filter(Repository.repo_name == name)\
130 .filter(Repository.repo_name == name)\
132 .scalar()
131 .scalar()
133
132
134 if dbrepo:
133 if dbrepo:
135 log.info('Adding db instance to cached list')
134 log.info('Adding db instance to cached list')
136 repos_list[name].dbrepo = dbrepo
135 repos_list[name].dbrepo = dbrepo
@@ -144,16 +143,16 b' class HgModel(object):'
144 continue
143 continue
145 meta.Session.remove()
144 meta.Session.remove()
146 return repos_list
145 return repos_list
147
146
148 def get_repos(self):
147 def get_repos(self):
149 for name, repo in _get_repos_cached().items():
148 for name, repo in _get_repos_cached().items():
150 if repo._get_hidden():
149 if repo._get_hidden():
151 #skip hidden web repository
150 #skip hidden web repository
152 continue
151 continue
153
152
154 last_change = repo.last_change
153 last_change = repo.last_change
155 tip = h.get_changeset_safe(repo, 'tip')
154 tip = h.get_changeset_safe(repo, 'tip')
156
155
157 tmp_d = {}
156 tmp_d = {}
158 tmp_d['name'] = repo.name
157 tmp_d['name'] = repo.name
159 tmp_d['name_sort'] = tmp_d['name'].lower()
158 tmp_d['name_sort'] = tmp_d['name'].lower()
@@ -162,7 +161,7 b' class HgModel(object):'
162 tmp_d['last_change'] = last_change
161 tmp_d['last_change'] = last_change
163 tmp_d['last_change_sort'] = last_change[1] - last_change[0]
162 tmp_d['last_change_sort'] = last_change[1] - last_change[0]
164 tmp_d['tip'] = tip.short_id
163 tmp_d['tip'] = tip.short_id
165 tmp_d['tip_sort'] = tip.revision
164 tmp_d['tip_sort'] = tip.revision
166 tmp_d['rev'] = tip.revision
165 tmp_d['rev'] = tip.revision
167 tmp_d['contact'] = repo.contact
166 tmp_d['contact'] = repo.contact
168 tmp_d['contact_sort'] = tmp_d['contact']
167 tmp_d['contact_sort'] = tmp_d['contact']
@@ -181,6 +180,6 b' class HgModel(object):'
181 invalidate_cache('cached_repo_list')
180 invalidate_cache('cached_repo_list')
182 repo = _get_repos_cached()[repo_name]
181 repo = _get_repos_cached()[repo_name]
183 return repo
182 return repo
184
183
185
184
186
185
@@ -2,7 +2,7 b''
2 # encoding: utf-8
2 # encoding: utf-8
3 # Model for permissions
3 # Model for permissions
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
@@ -23,8 +23,8 b' Model for permissions'
23 @author: marcink
23 @author: marcink
24 """
24 """
25
25
26 from pylons.i18n.translation import _
27 from rhodecode.model.db import User, Permission, UserToPerm, RepoToPerm
26 from rhodecode.model.db import User, Permission, UserToPerm, RepoToPerm
27 from rhodecode.model.caching_query import FromCache
28 from rhodecode.model.meta import Session
28 from rhodecode.model.meta import Session
29 import logging
29 import logging
30 import traceback
30 import traceback
@@ -33,40 +33,47 b' log = logging.getLogger(__name__)'
33
33
34 class PermissionModel(object):
34 class PermissionModel(object):
35
35
36 def __init__(self):
36 def __init__(self, sa=None):
37 self.sa = Session()
37 if not sa:
38
38 self.sa = Session()
39 def get_default(self):
39 else:
40 return self.sa.query(User).filter(User.username == 'default').scalar()
40 self.sa = sa
41
41
42 def get_permission(self, id):
42 def get_permission(self, permission_id, cache=False):
43 return self.sa.query(Permission).get(id)
43 perm = self.sa.query(Permission)
44
44 if cache:
45 def get_permission_by_name(self, name):
45 perm = perm.options(FromCache("sql_cache_short",
46 return self.sa.query(Permission)\
46 "get_permission_%s" % permission_id))
47 .filter(Permission.permission_name == name).scalar()
47 return perm.get(permission_id)
48
48
49
49 def get_permission_by_name(self, name, cache=False):
50 perm = self.sa.query(Permission)\
51 .filter(Permission.permission_name == name)
52 if cache:
53 perm = perm.options(FromCache("sql_cache_short",
54 "get_permission_%s" % name))
55 return perm.scalar()
56
50 def update(self, form_result):
57 def update(self, form_result):
51 perm_user = self.sa.query(User)\
58 perm_user = self.sa.query(User)\
52 .filter(User.username == form_result['perm_user_name']).scalar()
59 .filter(User.username == form_result['perm_user_name']).scalar()
53 u2p = self.sa.query(UserToPerm).filter(UserToPerm.user == perm_user).all()
60 u2p = self.sa.query(UserToPerm).filter(UserToPerm.user == perm_user).all()
54 if len(u2p) != 3:
61 if len(u2p) != 3:
55 raise Exception('There is more than 3 defined \
62 raise Exception('There is more than 3 defined'
56 permissions for defualt user. This should not happen please verify\
63 ' permissions for default user. This should not happen please verify'
57 your database')
64 ' your database')
58
65
59 try:
66 try:
60 #stage 1 change defaults
67 #stage 1 change defaults
61 for p in u2p:
68 for p in u2p:
62 if p.permission.permission_name.startswith('repository.'):
69 if p.permission.permission_name.startswith('repository.'):
63 p.permission = self.get_permission_by_name(form_result['default_perm'])
70 p.permission = self.get_permission_by_name(form_result['default_perm'])
64 self.sa.add(p)
71 self.sa.add(p)
65
72
66 if p.permission.permission_name.startswith('hg.register.'):
73 if p.permission.permission_name.startswith('hg.register.'):
67 p.permission = self.get_permission_by_name(form_result['default_register'])
74 p.permission = self.get_permission_by_name(form_result['default_register'])
68 self.sa.add(p)
75 self.sa.add(p)
69
76
70 if p.permission.permission_name.startswith('hg.create.'):
77 if p.permission.permission_name.startswith('hg.create.'):
71 p.permission = self.get_permission_by_name(form_result['default_create'])
78 p.permission = self.get_permission_by_name(form_result['default_create'])
72 self.sa.add(p)
79 self.sa.add(p)
@@ -75,14 +82,14 b' class PermissionModel(object):'
75 for r2p in self.sa.query(RepoToPerm).filter(RepoToPerm.user == perm_user).all():
82 for r2p in self.sa.query(RepoToPerm).filter(RepoToPerm.user == perm_user).all():
76 r2p.permission = self.get_permission_by_name(form_result['default_perm'])
83 r2p.permission = self.get_permission_by_name(form_result['default_perm'])
77 self.sa.add(r2p)
84 self.sa.add(r2p)
78
85
79 self.sa.commit()
86 self.sa.commit()
80 except:
87 except:
81 log.error(traceback.format_exc())
88 log.error(traceback.format_exc())
82 self.sa.rollback()
89 self.sa.rollback()
83 raise
90 raise
84
91
85
92
86
93
87
94
88
95
@@ -19,15 +19,15 b''
19 """
19 """
20 Created on Jun 5, 2010
20 Created on Jun 5, 2010
21 model for handling repositories actions
21 model for handling repositories actions
22 @author: marcink
22 :author: marcink
23 """
23 """
24
24 from datetime import datetime
25 from datetime import datetime
25 from pylons import app_globals as g
26 from pylons import app_globals as g
26 from rhodecode.lib.utils import check_repo
27 from rhodecode.model.db import Repository, RepoToPerm, User, Permission
27 from rhodecode.model.db import Repository, RepoToPerm, User, Permission
28 from rhodecode.model.meta import Session
28 from rhodecode.model.meta import Session
29 from rhodecode.model.user_model import UserModel
29 from rhodecode.model.user import UserModel
30 from rhodecode.lib.celerylib.tasks import create_repo_fork, run_task
30 from rhodecode.model.caching_query import FromCache
31 import logging
31 import logging
32 import os
32 import os
33 import shutil
33 import shutil
@@ -35,82 +35,85 b' import traceback'
35 log = logging.getLogger(__name__)
35 log = logging.getLogger(__name__)
36
36
37 class RepoModel(object):
37 class RepoModel(object):
38
38
39 def __init__(self, sa=None):
39 def __init__(self, sa=None):
40 if not sa:
40 if not sa:
41 self.sa = Session()
41 self.sa = Session()
42 else:
42 else:
43 self.sa = sa
43 self.sa = sa
44
44
45 def get(self, id):
45 def get(self, repo_id, cache=False):
46 return self.sa.query(Repository)\
46 repo = self.sa.query(Repository)\
47 .filter(Repository.repo_name == id).scalar()
47 .filter(Repository.repo_name == repo_id)
48
48
49 if cache:
50 repo = repo.options(FromCache("sql_cache_short",
51 "get_repo_%s" % repo))
52 return repo.scalar()
53
49 def get_users_js(self):
54 def get_users_js(self):
50
55
51 users = self.sa.query(User).filter(User.active == True).all()
56 users = self.sa.query(User).filter(User.active == True).all()
52 u_tmpl = '''{id:%s, fname:"%s", lname:"%s", nname:"%s"},'''
57 u_tmpl = '''{id:%s, fname:"%s", lname:"%s", nname:"%s"},'''
53 users_array = '[%s];' % '\n'.join([u_tmpl % (u.user_id, u.name,
58 users_array = '[%s];' % '\n'.join([u_tmpl % (u.user_id, u.name,
54 u.lastname, u.username)
59 u.lastname, u.username)
55 for u in users])
60 for u in users])
56 return users_array
61 return users_array
57
62
58
63
59 def update(self, repo_name, form_data):
64 def update(self, repo_name, form_data):
60 try:
65 try:
61
66
62 #update permissions
67 #update permissions
63 for username, perm in form_data['perms_updates']:
68 for username, perm in form_data['perms_updates']:
64 r2p = self.sa.query(RepoToPerm)\
69 r2p = self.sa.query(RepoToPerm)\
65 .filter(RepoToPerm.user == self.sa.query(User)\
70 .filter(RepoToPerm.user == UserModel(self.sa).get_by_username(username, cache=False))\
66 .filter(User.username == username).one())\
67 .filter(RepoToPerm.repository == self.get(repo_name))\
71 .filter(RepoToPerm.repository == self.get(repo_name))\
68 .one()
72 .one()
69
73
70 r2p.permission_id = self.sa.query(Permission).filter(
74 r2p.permission_id = self.sa.query(Permission).filter(
71 Permission.permission_name ==
75 Permission.permission_name ==
72 perm).one().permission_id
76 perm).one().permission_id
73 self.sa.add(r2p)
77 self.sa.add(r2p)
74
78
75 #set new permissions
79 #set new permissions
76 for username, perm in form_data['perms_new']:
80 for username, perm in form_data['perms_new']:
77 r2p = RepoToPerm()
81 r2p = RepoToPerm()
78 r2p.repository = self.get(repo_name)
82 r2p.repository = self.get(repo_name)
79 r2p.user = self.sa.query(User)\
83 r2p.user = UserModel(self.sa).get_by_username(username, cache=False)
80 .filter(User.username == username).one()
84
81
82 r2p.permission_id = self.sa.query(Permission).filter(
85 r2p.permission_id = self.sa.query(Permission).filter(
83 Permission.permission_name == perm)\
86 Permission.permission_name == perm)\
84 .one().permission_id
87 .one().permission_id
85 self.sa.add(r2p)
88 self.sa.add(r2p)
86
89
87 #update current repo
90 #update current repo
88 cur_repo = self.get(repo_name)
91 cur_repo = self.get(repo_name, cache=False)
89
92
90 for k, v in form_data.items():
93 for k, v in form_data.items():
91 if k == 'user':
94 if k == 'user':
92 cur_repo.user_id = v
95 cur_repo.user_id = v
93 else:
96 else:
94 setattr(cur_repo, k, v)
97 setattr(cur_repo, k, v)
95
98
96 self.sa.add(cur_repo)
99 self.sa.add(cur_repo)
97
100
98 if repo_name != form_data['repo_name']:
101 if repo_name != form_data['repo_name']:
99 #rename our data
102 #rename our data
100 self.__rename_repo(repo_name, form_data['repo_name'])
103 self.__rename_repo(repo_name, form_data['repo_name'])
101
104
102 self.sa.commit()
105 self.sa.commit()
103 except:
106 except:
104 log.error(traceback.format_exc())
107 log.error(traceback.format_exc())
105 self.sa.rollback()
108 self.sa.rollback()
106 raise
109 raise
107
110
108 def create(self, form_data, cur_user, just_db=False, fork=False):
111 def create(self, form_data, cur_user, just_db=False, fork=False):
109 try:
112 try:
110 if fork:
113 if fork:
111 repo_name = str(form_data['fork_name'])
114 repo_name = str(form_data['fork_name'])
112 org_name = str(form_data['repo_name'])
115 org_name = str(form_data['repo_name'])
113
116
114 else:
117 else:
115 org_name = repo_name = str(form_data['repo_name'])
118 org_name = repo_name = str(form_data['repo_name'])
116 new_repo = Repository()
119 new_repo = Repository()
@@ -118,33 +121,32 b' class RepoModel(object):'
118 if k == 'repo_name':
121 if k == 'repo_name':
119 v = repo_name
122 v = repo_name
120 setattr(new_repo, k, v)
123 setattr(new_repo, k, v)
121
124
122 if fork:
125 if fork:
123 parent_repo = self.sa.query(Repository)\
126 parent_repo = self.sa.query(Repository)\
124 .filter(Repository.repo_name == org_name).scalar()
127 .filter(Repository.repo_name == org_name).scalar()
125 new_repo.fork = parent_repo
128 new_repo.fork = parent_repo
126
129
127 new_repo.user_id = cur_user.user_id
130 new_repo.user_id = cur_user.user_id
128 self.sa.add(new_repo)
131 self.sa.add(new_repo)
129
132
130 #create default permission
133 #create default permission
131 repo_to_perm = RepoToPerm()
134 repo_to_perm = RepoToPerm()
132 default = 'repository.read'
135 default = 'repository.read'
133 for p in UserModel(self.sa).get_default().user_perms:
136 for p in UserModel(self.sa).get_by_username('default', cache=False).user_perms:
134 if p.permission.permission_name.startswith('repository.'):
137 if p.permission.permission_name.startswith('repository.'):
135 default = p.permission.permission_name
138 default = p.permission.permission_name
136 break
139 break
137
140
138 default_perm = 'repository.none' if form_data['private'] else default
141 default_perm = 'repository.none' if form_data['private'] else default
139
142
140 repo_to_perm.permission_id = self.sa.query(Permission)\
143 repo_to_perm.permission_id = self.sa.query(Permission)\
141 .filter(Permission.permission_name == default_perm)\
144 .filter(Permission.permission_name == default_perm)\
142 .one().permission_id
145 .one().permission_id
143
146
144 repo_to_perm.repository_id = new_repo.repo_id
147 repo_to_perm.repository_id = new_repo.repo_id
145 repo_to_perm.user_id = self.sa.query(User)\
148 repo_to_perm.user_id = UserModel(self.sa).get_by_username('default', cache=False).user_id
146 .filter(User.username == 'default').one().user_id
149
147
148 self.sa.add(repo_to_perm)
150 self.sa.add(repo_to_perm)
149 self.sa.commit()
151 self.sa.commit()
150 if not just_db:
152 if not just_db:
@@ -152,11 +154,12 b' class RepoModel(object):'
152 except:
154 except:
153 log.error(traceback.format_exc())
155 log.error(traceback.format_exc())
154 self.sa.rollback()
156 self.sa.rollback()
155 raise
157 raise
156
158
157 def create_fork(self, form_data, cur_user):
159 def create_fork(self, form_data, cur_user):
158 run_task(create_repo_fork, form_data, cur_user)
160 from rhodecode.lib.celerylib import tasks, run_task
159
161 run_task(tasks.create_repo_fork, form_data, cur_user)
162
160 def delete(self, repo):
163 def delete(self, repo):
161 try:
164 try:
162 self.sa.delete(repo)
165 self.sa.delete(repo)
@@ -166,7 +169,7 b' class RepoModel(object):'
166 log.error(traceback.format_exc())
169 log.error(traceback.format_exc())
167 self.sa.rollback()
170 self.sa.rollback()
168 raise
171 raise
169
172
170 def delete_perm_user(self, form_data, repo_name):
173 def delete_perm_user(self, form_data, repo_name):
171 try:
174 try:
172 self.sa.query(RepoToPerm)\
175 self.sa.query(RepoToPerm)\
@@ -177,8 +180,9 b' class RepoModel(object):'
177 log.error(traceback.format_exc())
180 log.error(traceback.format_exc())
178 self.sa.rollback()
181 self.sa.rollback()
179 raise
182 raise
180
183
181 def __create_repo(self, repo_name):
184 def __create_repo(self, repo_name):
185 from rhodecode.lib.utils import check_repo
182 repo_path = os.path.join(g.base_path, repo_name)
186 repo_path = os.path.join(g.base_path, repo_name)
183 if check_repo(repo_name, g.base_path):
187 if check_repo(repo_name, g.base_path):
184 log.info('creating repo %s in %s', repo_name, repo_path)
188 log.info('creating repo %s in %s', repo_name, repo_path)
@@ -187,14 +191,14 b' class RepoModel(object):'
187
191
188 def __rename_repo(self, old, new):
192 def __rename_repo(self, old, new):
189 log.info('renaming repo from %s to %s', old, new)
193 log.info('renaming repo from %s to %s', old, new)
190
194
191 old_path = os.path.join(g.base_path, old)
195 old_path = os.path.join(g.base_path, old)
192 new_path = os.path.join(g.base_path, new)
196 new_path = os.path.join(g.base_path, new)
193 if os.path.isdir(new_path):
197 if os.path.isdir(new_path):
194 raise Exception('Was trying to rename to already existing dir %s',
198 raise Exception('Was trying to rename to already existing dir %s',
195 new_path)
199 new_path)
196 shutil.move(old_path, new_path)
200 shutil.move(old_path, new_path)
197
201
198 def __delete_repo(self, name):
202 def __delete_repo(self, name):
199 rm_path = os.path.join(g.base_path, name)
203 rm_path = os.path.join(g.base_path, name)
200 log.info("Removing %s", rm_path)
204 log.info("Removing %s", rm_path)
@@ -17,19 +17,19 b''
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
21 """
20 """
22 Created on April 9, 2010
21 Created on April 9, 2010
23 Model for users
22 Model for users
24 @author: marcink
23 :author: marcink
25 """
24 """
26 from rhodecode.lib import auth
25
27 from pylons.i18n.translation import _
26 from pylons.i18n.translation import _
28 from rhodecode.lib.celerylib import tasks, run_task
27 from rhodecode.model.caching_query import FromCache
29 from rhodecode.model.db import User
28 from rhodecode.model.db import User
30 from rhodecode.model.meta import Session
29 from rhodecode.model.meta import Session
30 import logging
31 import traceback
31 import traceback
32 import logging
32
33 log = logging.getLogger(__name__)
33 log = logging.getLogger(__name__)
34
34
35 class DefaultUserException(Exception):pass
35 class DefaultUserException(Exception):pass
@@ -41,69 +41,76 b' class UserModel(object):'
41 self.sa = Session()
41 self.sa = Session()
42 else:
42 else:
43 self.sa = sa
43 self.sa = sa
44
44
45 def get_default(self):
45 def get(self, user_id, cache=False):
46 return self.sa.query(User).filter(User.username == 'default').scalar()
46 user = self.sa.query(User)
47
47 if cache:
48 def get_user(self, id):
48 user = user.options(FromCache("sql_cache_short",
49 return self.sa.query(User).get(id)
49 "get_user_%s" % user_id))
50
50 return user.get(user_id)
51 def get_user_by_name(self, name):
51
52 return self.sa.query(User).filter(User.username == name).scalar()
52
53
53 def get_by_username(self, username, cache=False):
54 user = self.sa.query(User)\
55 .filter(User.username == username)
56 if cache:
57 user = user.options(FromCache("sql_cache_short",
58 "get_user_%s" % username))
59 return user.scalar()
60
54 def create(self, form_data):
61 def create(self, form_data):
55 try:
62 try:
56 new_user = User()
63 new_user = User()
57 for k, v in form_data.items():
64 for k, v in form_data.items():
58 setattr(new_user, k, v)
65 setattr(new_user, k, v)
59
66
60 self.sa.add(new_user)
67 self.sa.add(new_user)
61 self.sa.commit()
68 self.sa.commit()
62 except:
69 except:
63 log.error(traceback.format_exc())
70 log.error(traceback.format_exc())
64 self.sa.rollback()
71 self.sa.rollback()
65 raise
72 raise
66
73
67 def create_registration(self, form_data):
74 def create_registration(self, form_data):
68 try:
75 try:
69 new_user = User()
76 new_user = User()
70 for k, v in form_data.items():
77 for k, v in form_data.items():
71 if k != 'admin':
78 if k != 'admin':
72 setattr(new_user, k, v)
79 setattr(new_user, k, v)
73
80
74 self.sa.add(new_user)
81 self.sa.add(new_user)
75 self.sa.commit()
82 self.sa.commit()
76 except:
83 except:
77 log.error(traceback.format_exc())
84 log.error(traceback.format_exc())
78 self.sa.rollback()
85 self.sa.rollback()
79 raise
86 raise
80
87
81 def update(self, uid, form_data):
88 def update(self, user_id, form_data):
82 try:
89 try:
83 new_user = self.sa.query(User).get(uid)
90 new_user = self.get(user_id, cache=False)
84 if new_user.username == 'default':
91 if new_user.username == 'default':
85 raise DefaultUserException(
92 raise DefaultUserException(
86 _("You can't Edit this user since it's"
93 _("You can't Edit this user since it's"
87 " crucial for entire application"))
94 " crucial for entire application"))
88 for k, v in form_data.items():
95 for k, v in form_data.items():
89 if k == 'new_password' and v != '':
96 if k == 'new_password' and v != '':
90 new_user.password = v
97 new_user.password = v
91 else:
98 else:
92 setattr(new_user, k, v)
99 setattr(new_user, k, v)
93
100
94 self.sa.add(new_user)
101 self.sa.add(new_user)
95 self.sa.commit()
102 self.sa.commit()
96 except:
103 except:
97 log.error(traceback.format_exc())
104 log.error(traceback.format_exc())
98 self.sa.rollback()
105 self.sa.rollback()
99 raise
106 raise
100
107
101 def update_my_account(self, uid, form_data):
108 def update_my_account(self, user_id, form_data):
102 try:
109 try:
103 new_user = self.sa.query(User).get(uid)
110 new_user = self.get(user_id, cache=False)
104 if new_user.username == 'default':
111 if new_user.username == 'default':
105 raise DefaultUserException(
112 raise DefaultUserException(
106 _("You can't Edit this user since it's"
113 _("You can't Edit this user since it's"
107 " crucial for entire application"))
114 " crucial for entire application"))
108 for k, v in form_data.items():
115 for k, v in form_data.items():
109 if k == 'new_password' and v != '':
116 if k == 'new_password' and v != '':
@@ -111,28 +118,28 b' class UserModel(object):'
111 else:
118 else:
112 if k not in ['admin', 'active']:
119 if k not in ['admin', 'active']:
113 setattr(new_user, k, v)
120 setattr(new_user, k, v)
114
121
115 self.sa.add(new_user)
122 self.sa.add(new_user)
116 self.sa.commit()
123 self.sa.commit()
117 except:
124 except:
118 log.error(traceback.format_exc())
125 log.error(traceback.format_exc())
119 self.sa.rollback()
126 self.sa.rollback()
120 raise
127 raise
121
128
122 def delete(self, id):
129 def delete(self, user_id):
123 try:
130 try:
124
131 user = self.get(user_id, cache=False)
125 user = self.sa.query(User).get(id)
126 if user.username == 'default':
132 if user.username == 'default':
127 raise DefaultUserException(
133 raise DefaultUserException(
128 _("You can't remove this user since it's"
134 _("You can't remove this user since it's"
129 " crucial for entire application"))
135 " crucial for entire application"))
130 self.sa.delete(user)
136 self.sa.delete(user)
131 self.sa.commit()
137 self.sa.commit()
132 except:
138 except:
133 log.error(traceback.format_exc())
139 log.error(traceback.format_exc())
134 self.sa.rollback()
140 self.sa.rollback()
135 raise
141 raise
136
142
137 def reset_password(self, data):
143 def reset_password(self, data):
144 from rhodecode.lib.celerylib import tasks, run_task
138 run_task(tasks.reset_user_password, data['email'])
145 run_task(tasks.reset_user_password, data['email'])
@@ -2301,6 +2301,8 b' padding-left:5px;'
2301
2301
2302 #changeset_content .container .left .date,.ac .match {
2302 #changeset_content .container .left .date,.ac .match {
2303 font-weight:700;
2303 font-weight:700;
2304 padding-top: 5px;
2305 padding-bottom:5px;
2304 }
2306 }
2305
2307
2306 div#legend_container table td,div#legend_choices table td {
2308 div#legend_container table td,div#legend_choices table td {
@@ -49,19 +49,32 b' cache_dir = %(here)s/data'
49 ####################################
49 ####################################
50 beaker.cache.data_dir=/%(here)s/data/cache/data
50 beaker.cache.data_dir=/%(here)s/data/cache/data
51 beaker.cache.lock_dir=/%(here)s/data/cache/lock
51 beaker.cache.lock_dir=/%(here)s/data/cache/lock
52 beaker.cache.regions=super_short_term,short_term,long_term
52 beaker.cache.regions=super_short_term,short_term,long_term,sql_cache_short,sql_cache_med,sql_cache_long
53
54 beaker.cache.super_short_term.type=memory
55 beaker.cache.super_short_term.expire=10
56
57 beaker.cache.short_term.type=memory
58 beaker.cache.short_term.expire=60
59
53 beaker.cache.long_term.type=memory
60 beaker.cache.long_term.type=memory
54 beaker.cache.long_term.expire=36000
61 beaker.cache.long_term.expire=36000
55 beaker.cache.short_term.type=memory
62
56 beaker.cache.short_term.expire=60
63
57 beaker.cache.super_short_term.type=memory
64 beaker.cache.sql_cache_short.type=memory
58 beaker.cache.super_short_term.expire=10
65 beaker.cache.sql_cache_short.expire=5
66
67 beaker.cache.sql_cache_med.type=memory
68 beaker.cache.sql_cache_med.expire=360
69
70 beaker.cache.sql_cache_long.type=file
71 beaker.cache.sql_cache_long.expire=3600
59
72
60 ####################################
73 ####################################
61 ### BEAKER SESSION ####
74 ### BEAKER SESSION ####
62 ####################################
75 ####################################
63 ## Type of storage used for the session, current types are
76 ## Type of storage used for the session, current types are
64 ## "dbm", "file", "memcached", "database", and "memory".
77 ## dbm, file, memcached, database, and memory.
65 ## The storage uses the Container API
78 ## The storage uses the Container API
66 ##that is also used by the cache system.
79 ##that is also used by the cache system.
67 beaker.session.type = file
80 beaker.session.type = file
General Comments 0
You need to be logged in to leave comments. Login now