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