##// END OF EJS Templates
fixed import problems
marcink -
r841:78b3d2d7 beta
parent child Browse files
Show More
@@ -1,475 +1,476 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 rhodecode.lib.db_manage
3 rhodecode.lib.db_manage
4 ~~~~~~~~~~~~~~~~~~~~~~~
4 ~~~~~~~~~~~~~~~~~~~~~~~
5
5
6 Database creation, and setup module for RhodeCode. Used for creation
6 Database creation, and setup module for RhodeCode. Used for creation
7 of database as well as for migration operations
7 of database as well as for migration operations
8
8
9 :created_on: Apr 10, 2010
9 :created_on: Apr 10, 2010
10 :author: marcink
10 :author: marcink
11 :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
11 :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
12 :license: GPLv3, see COPYING for more details.
12 :license: GPLv3, see COPYING for more details.
13 """
13 """
14 # This program is free software; you can redistribute it and/or
14 # This program is free software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation; version 2
16 # as published by the Free Software Foundation; version 2
17 # of the License or (at your opinion) any later version of the license.
17 # of the License or (at your opinion) any later version of the license.
18 #
18 #
19 # This program is distributed in the hope that it will be useful,
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
22 # GNU General Public License for more details.
23 #
23 #
24 # You should have received a copy of the GNU General Public License
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
26 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
27 # MA 02110-1301, USA.
27 # MA 02110-1301, USA.
28
28
29 import os
29 import os
30 import sys
30 import sys
31 import uuid
31 import uuid
32 import logging
32 import logging
33 from os.path import dirname as dn, join as jn
33 from os.path import dirname as dn, join as jn
34
34
35 from rhodecode import __dbversion__
35 from rhodecode import __dbversion__
36 from rhodecode.model import meta
36 from rhodecode.model import meta
37
37
38 from rhodecode.lib.auth import get_crypt_password
38 from rhodecode.lib.auth import get_crypt_password
39 from rhodecode.lib.utils import ask_ok
39 from rhodecode.lib.utils import ask_ok
40 from rhodecode.model import init_model
40 from rhodecode.model import init_model
41 from rhodecode.model.db import User, Permission, RhodeCodeUi, RhodeCodeSettings, \
41 from rhodecode.model.db import User, Permission, RhodeCodeUi, RhodeCodeSettings, \
42 UserToPerm, DbMigrateVersion
42 UserToPerm, DbMigrateVersion
43
43
44 from sqlalchemy.engine import create_engine
44 from sqlalchemy.engine import create_engine
45
45
46 from rhodecode.lib.dbmigrate.migrate.versioning import api
47 from rhodecode.lib.dbmigrate.migrate.exceptions import \
48 DatabaseNotControlledError
49
50 log = logging.getLogger(__name__)
46 log = logging.getLogger(__name__)
51
47
52 class DbManage(object):
48 class DbManage(object):
53 def __init__(self, log_sql, dbconf, root, tests=False):
49 def __init__(self, log_sql, dbconf, root, tests=False):
54 self.dbname = dbconf.split('/')[-1]
50 self.dbname = dbconf.split('/')[-1]
55 self.tests = tests
51 self.tests = tests
56 self.root = root
52 self.root = root
57 self.dburi = dbconf
53 self.dburi = dbconf
58 engine = create_engine(self.dburi, echo=log_sql)
54 engine = create_engine(self.dburi, echo=log_sql)
59 init_model(engine)
55 init_model(engine)
60 self.sa = meta.Session()
56 self.sa = meta.Session()
61 self.db_exists = False
57 self.db_exists = False
62
58
63 def check_for_db(self, override):
59 def check_for_db(self, override):
64 db_path = jn(self.root, self.dbname)
60 db_path = jn(self.root, self.dbname)
65 if self.dburi.startswith('sqlite'):
61 if self.dburi.startswith('sqlite'):
66 log.info('checking for existing db in %s', db_path)
62 log.info('checking for existing db in %s', db_path)
67 if os.path.isfile(db_path):
63 if os.path.isfile(db_path):
68
64
69 self.db_exists = True
65 self.db_exists = True
70 if not override:
66 if not override:
71 raise Exception('database already exists')
67 raise Exception('database already exists')
72
68
73 def create_tables(self, override=False):
69 def create_tables(self, override=False):
74 """Create a auth database
70 """Create a auth database
75 """
71 """
76
72
77 self.check_for_db(override)
73 self.check_for_db(override)
78 if self.db_exists:
74 if self.db_exists:
79 log.info("database exist and it's going to be destroyed")
75 log.info("database exist and it's going to be destroyed")
80 if self.tests:
76 if self.tests:
81 destroy = True
77 destroy = True
82 else:
78 else:
83 destroy = ask_ok('Are you sure to destroy old database ? [y/n]')
79 destroy = ask_ok('Are you sure to destroy old database ? [y/n]')
84 if not destroy:
80 if not destroy:
85 sys.exit()
81 sys.exit()
86 if self.db_exists and destroy:
82 if self.db_exists and destroy:
87 os.remove(jn(self.root, self.dbname))
83 os.remove(jn(self.root, self.dbname))
88 checkfirst = not override
84 checkfirst = not override
89 meta.Base.metadata.create_all(checkfirst=checkfirst)
85 meta.Base.metadata.create_all(checkfirst=checkfirst)
90 log.info('Created tables for %s', self.dbname)
86 log.info('Created tables for %s', self.dbname)
91
87
92
88
93
89
94 def set_db_version(self):
90 def set_db_version(self):
95 try:
91 try:
96 ver = DbMigrateVersion()
92 ver = DbMigrateVersion()
97 ver.version = __dbversion__
93 ver.version = __dbversion__
98 ver.repository_id = 'rhodecode_db_migrations'
94 ver.repository_id = 'rhodecode_db_migrations'
99 ver.repository_path = 'versions'
95 ver.repository_path = 'versions'
100 self.sa.add(ver)
96 self.sa.add(ver)
101 self.sa.commit()
97 self.sa.commit()
102 except:
98 except:
103 self.sa.rollback()
99 self.sa.rollback()
104 raise
100 raise
105 log.info('db version set to: %s', __dbversion__)
101 log.info('db version set to: %s', __dbversion__)
106
102
107
103
108 def upgrade(self):
104 def upgrade(self):
109 """Upgrades given database schema to given revision following
105 """Upgrades given database schema to given revision following
110 all needed steps,
106 all needed steps,
111
107
112 :param revision: revision to upgrade to
108 :param revision: revision to upgrade to
113 """
109 """
110
111 from rhodecode.lib.dbmigrate.migrate.versioning import api
112 from rhodecode.lib.dbmigrate.migrate.exceptions import \
113 DatabaseNotControlledError
114
114 upgrade = ask_ok('You are about to perform database upgrade, make '
115 upgrade = ask_ok('You are about to perform database upgrade, make '
115 'sure You backed up your database before. '
116 'sure You backed up your database before. '
116 'Continue ? [y/n]')
117 'Continue ? [y/n]')
117 if not upgrade:
118 if not upgrade:
118 sys.exit('Nothing done')
119 sys.exit('Nothing done')
119
120
120 repository_path = 'rhodecode/lib/dbmigrate'
121 repository_path = 'rhodecode/lib/dbmigrate'
121 db_uri = self.dburi
122 db_uri = self.dburi
122
123
123 try:
124 try:
124 curr_version = api.db_version(db_uri, repository_path)
125 curr_version = api.db_version(db_uri, repository_path)
125 msg = ('Found current database under version'
126 msg = ('Found current database under version'
126 ' control with version %s' % curr_version)
127 ' control with version %s' % curr_version)
127
128
128 except (RuntimeError, DatabaseNotControlledError), e:
129 except (RuntimeError, DatabaseNotControlledError), e:
129 curr_version = 1
130 curr_version = 1
130 msg = ('Current database is not under version control. Setting'
131 msg = ('Current database is not under version control. Setting'
131 ' as version %s' % curr_version)
132 ' as version %s' % curr_version)
132 api.version_control(db_uri, repository_path, curr_version)
133 api.version_control(db_uri, repository_path, curr_version)
133
134
134 print (msg)
135 print (msg)
135
136
136 if curr_version == __dbversion__:
137 if curr_version == __dbversion__:
137 sys.exit('This database is already at the newest version')
138 sys.exit('This database is already at the newest version')
138
139
139 #======================================================================
140 #======================================================================
140 # UPGRADE STEPS
141 # UPGRADE STEPS
141 #======================================================================
142 #======================================================================
142 class UpgradeSteps(object):
143 class UpgradeSteps(object):
143
144
144 def __init__(self, klass):
145 def __init__(self, klass):
145 self.klass = klass
146 self.klass = klass
146
147
147 def step_0(self):
148 def step_0(self):
148 #step 0 is the schema upgrade, and than follow proper upgrades
149 #step 0 is the schema upgrade, and than follow proper upgrades
149 print ('attempting to do database upgrade to version %s' \
150 print ('attempting to do database upgrade to version %s' \
150 % __dbversion__)
151 % __dbversion__)
151 api.upgrade(db_uri, repository_path, __dbversion__)
152 api.upgrade(db_uri, repository_path, __dbversion__)
152 print ('Schema upgrade completed')
153 print ('Schema upgrade completed')
153
154
154 def step_1(self):
155 def step_1(self):
155 pass
156 pass
156
157
157 def step_2(self):
158 def step_2(self):
158 print ('Patching repo paths for newer version of RhodeCode')
159 print ('Patching repo paths for newer version of RhodeCode')
159 self.klass.fix_repo_paths()
160 self.klass.fix_repo_paths()
160
161
161 print ('Patching default user of RhodeCode')
162 print ('Patching default user of RhodeCode')
162 self.klass.fix_default_user()
163 self.klass.fix_default_user()
163
164
164 log.info('Changing ui settings')
165 log.info('Changing ui settings')
165 self.klass.create_ui_settings()
166 self.klass.create_ui_settings()
166
167
167
168
168 upgrade_steps = [0] + range(curr_version + 1, __dbversion__ + 1)
169 upgrade_steps = [0] + range(curr_version + 1, __dbversion__ + 1)
169
170
170 #CALL THE PROPER ORDER OF STEPS TO PERFORM FULL UPGRADE
171 #CALL THE PROPER ORDER OF STEPS TO PERFORM FULL UPGRADE
171 for step in upgrade_steps:
172 for step in upgrade_steps:
172 print ('performing upgrade step %s' % step)
173 print ('performing upgrade step %s' % step)
173 callable = getattr(UpgradeSteps(self), 'step_%s' % step)()
174 callable = getattr(UpgradeSteps(self), 'step_%s' % step)()
174
175
175
176
176
177
177 def fix_repo_paths(self):
178 def fix_repo_paths(self):
178 """Fixes a old rhodecode version path into new one without a '*'
179 """Fixes a old rhodecode version path into new one without a '*'
179 """
180 """
180
181
181 paths = self.sa.query(RhodeCodeUi)\
182 paths = self.sa.query(RhodeCodeUi)\
182 .filter(RhodeCodeUi.ui_key == '/')\
183 .filter(RhodeCodeUi.ui_key == '/')\
183 .scalar()
184 .scalar()
184
185
185 paths.ui_value = paths.ui_value.replace('*', '')
186 paths.ui_value = paths.ui_value.replace('*', '')
186
187
187 try:
188 try:
188 self.sa.add(paths)
189 self.sa.add(paths)
189 self.sa.commit()
190 self.sa.commit()
190 except:
191 except:
191 self.sa.rollback()
192 self.sa.rollback()
192 raise
193 raise
193
194
194 def fix_default_user(self):
195 def fix_default_user(self):
195 """Fixes a old default user with some 'nicer' default values,
196 """Fixes a old default user with some 'nicer' default values,
196 used mostly for anonymous access
197 used mostly for anonymous access
197 """
198 """
198 def_user = self.sa.query(User)\
199 def_user = self.sa.query(User)\
199 .filter(User.username == 'default')\
200 .filter(User.username == 'default')\
200 .one()
201 .one()
201
202
202 def_user.name = 'Anonymous'
203 def_user.name = 'Anonymous'
203 def_user.lastname = 'User'
204 def_user.lastname = 'User'
204 def_user.email = 'anonymous@rhodecode.org'
205 def_user.email = 'anonymous@rhodecode.org'
205
206
206 try:
207 try:
207 self.sa.add(def_user)
208 self.sa.add(def_user)
208 self.sa.commit()
209 self.sa.commit()
209 except:
210 except:
210 self.sa.rollback()
211 self.sa.rollback()
211 raise
212 raise
212
213
213
214
214
215
215 def admin_prompt(self, second=False):
216 def admin_prompt(self, second=False):
216 if not self.tests:
217 if not self.tests:
217 import getpass
218 import getpass
218
219
219
220
220 def get_password():
221 def get_password():
221 password = getpass.getpass('Specify admin password (min 6 chars):')
222 password = getpass.getpass('Specify admin password (min 6 chars):')
222 confirm = getpass.getpass('Confirm password:')
223 confirm = getpass.getpass('Confirm password:')
223
224
224 if password != confirm:
225 if password != confirm:
225 log.error('passwords mismatch')
226 log.error('passwords mismatch')
226 return False
227 return False
227 if len(password) < 6:
228 if len(password) < 6:
228 log.error('password is to short use at least 6 characters')
229 log.error('password is to short use at least 6 characters')
229 return False
230 return False
230
231
231 return password
232 return password
232
233
233 username = raw_input('Specify admin username:')
234 username = raw_input('Specify admin username:')
234
235
235 password = get_password()
236 password = get_password()
236 if not password:
237 if not password:
237 #second try
238 #second try
238 password = get_password()
239 password = get_password()
239 if not password:
240 if not password:
240 sys.exit()
241 sys.exit()
241
242
242 email = raw_input('Specify admin email:')
243 email = raw_input('Specify admin email:')
243 self.create_user(username, password, email, True)
244 self.create_user(username, password, email, True)
244 else:
245 else:
245 log.info('creating admin and regular test users')
246 log.info('creating admin and regular test users')
246 self.create_user('test_admin', 'test12', 'test_admin@mail.com', True)
247 self.create_user('test_admin', 'test12', 'test_admin@mail.com', True)
247 self.create_user('test_regular', 'test12', 'test_regular@mail.com', False)
248 self.create_user('test_regular', 'test12', 'test_regular@mail.com', False)
248 self.create_user('test_regular2', 'test12', 'test_regular2@mail.com', False)
249 self.create_user('test_regular2', 'test12', 'test_regular2@mail.com', False)
249
250
250 def create_ui_settings(self):
251 def create_ui_settings(self):
251 """Creates ui settings, fills out hooks
252 """Creates ui settings, fills out hooks
252 and disables dotencode
253 and disables dotencode
253
254
254 """
255 """
255 #HOOKS
256 #HOOKS
256 hooks1_key = 'changegroup.update'
257 hooks1_key = 'changegroup.update'
257 hooks1_ = self.sa.query(RhodeCodeUi)\
258 hooks1_ = self.sa.query(RhodeCodeUi)\
258 .filter(RhodeCodeUi.ui_key == hooks1_key).scalar()
259 .filter(RhodeCodeUi.ui_key == hooks1_key).scalar()
259
260
260 hooks1 = RhodeCodeUi() if hooks1_ is None else hooks1_
261 hooks1 = RhodeCodeUi() if hooks1_ is None else hooks1_
261 hooks1.ui_section = 'hooks'
262 hooks1.ui_section = 'hooks'
262 hooks1.ui_key = hooks1_key
263 hooks1.ui_key = hooks1_key
263 hooks1.ui_value = 'hg update >&2'
264 hooks1.ui_value = 'hg update >&2'
264 hooks1.ui_active = False
265 hooks1.ui_active = False
265
266
266 hooks2_key = 'changegroup.repo_size'
267 hooks2_key = 'changegroup.repo_size'
267 hooks2_ = self.sa.query(RhodeCodeUi)\
268 hooks2_ = self.sa.query(RhodeCodeUi)\
268 .filter(RhodeCodeUi.ui_key == hooks2_key).scalar()
269 .filter(RhodeCodeUi.ui_key == hooks2_key).scalar()
269
270
270 hooks2 = RhodeCodeUi() if hooks2_ is None else hooks2_
271 hooks2 = RhodeCodeUi() if hooks2_ is None else hooks2_
271 hooks2.ui_section = 'hooks'
272 hooks2.ui_section = 'hooks'
272 hooks2.ui_key = hooks2_key
273 hooks2.ui_key = hooks2_key
273 hooks2.ui_value = 'python:rhodecode.lib.hooks.repo_size'
274 hooks2.ui_value = 'python:rhodecode.lib.hooks.repo_size'
274
275
275 hooks3 = RhodeCodeUi()
276 hooks3 = RhodeCodeUi()
276 hooks3.ui_section = 'hooks'
277 hooks3.ui_section = 'hooks'
277 hooks3.ui_key = 'pretxnchangegroup.push_logger'
278 hooks3.ui_key = 'pretxnchangegroup.push_logger'
278 hooks3.ui_value = 'python:rhodecode.lib.hooks.log_push_action'
279 hooks3.ui_value = 'python:rhodecode.lib.hooks.log_push_action'
279
280
280 hooks4 = RhodeCodeUi()
281 hooks4 = RhodeCodeUi()
281 hooks4.ui_section = 'hooks'
282 hooks4.ui_section = 'hooks'
282 hooks4.ui_key = 'preoutgoing.pull_logger'
283 hooks4.ui_key = 'preoutgoing.pull_logger'
283 hooks4.ui_value = 'python:rhodecode.lib.hooks.log_pull_action'
284 hooks4.ui_value = 'python:rhodecode.lib.hooks.log_pull_action'
284
285
285 #For mercurial 1.7 set backward comapatibility with format
286 #For mercurial 1.7 set backward comapatibility with format
286 dotencode_disable = RhodeCodeUi()
287 dotencode_disable = RhodeCodeUi()
287 dotencode_disable.ui_section = 'format'
288 dotencode_disable.ui_section = 'format'
288 dotencode_disable.ui_key = 'dotencode'
289 dotencode_disable.ui_key = 'dotencode'
289 dotencode_disable.ui_value = 'false'
290 dotencode_disable.ui_value = 'false'
290
291
291 try:
292 try:
292 self.sa.add(hooks1)
293 self.sa.add(hooks1)
293 self.sa.add(hooks2)
294 self.sa.add(hooks2)
294 self.sa.add(hooks3)
295 self.sa.add(hooks3)
295 self.sa.add(hooks4)
296 self.sa.add(hooks4)
296 self.sa.add(dotencode_disable)
297 self.sa.add(dotencode_disable)
297 self.sa.commit()
298 self.sa.commit()
298 except:
299 except:
299 self.sa.rollback()
300 self.sa.rollback()
300 raise
301 raise
301
302
302
303
303 def create_ldap_options(self):
304 def create_ldap_options(self):
304 """Creates ldap settings"""
305 """Creates ldap settings"""
305
306
306 try:
307 try:
307 for k in ['ldap_active', 'ldap_host', 'ldap_port', 'ldap_ldaps',
308 for k in ['ldap_active', 'ldap_host', 'ldap_port', 'ldap_ldaps',
308 'ldap_dn_user', 'ldap_dn_pass', 'ldap_base_dn']:
309 'ldap_dn_user', 'ldap_dn_pass', 'ldap_base_dn']:
309
310
310 setting = RhodeCodeSettings(k, '')
311 setting = RhodeCodeSettings(k, '')
311 self.sa.add(setting)
312 self.sa.add(setting)
312 self.sa.commit()
313 self.sa.commit()
313 except:
314 except:
314 self.sa.rollback()
315 self.sa.rollback()
315 raise
316 raise
316
317
317 def config_prompt(self, test_repo_path=''):
318 def config_prompt(self, test_repo_path=''):
318 log.info('Setting up repositories config')
319 log.info('Setting up repositories config')
319
320
320 if not self.tests and not test_repo_path:
321 if not self.tests and not test_repo_path:
321 path = raw_input('Specify valid full path to your repositories'
322 path = raw_input('Specify valid full path to your repositories'
322 ' you can change this later in application settings:')
323 ' you can change this later in application settings:')
323 else:
324 else:
324 path = test_repo_path
325 path = test_repo_path
325
326
326 if not os.path.isdir(path):
327 if not os.path.isdir(path):
327 log.error('You entered wrong path: %s', path)
328 log.error('You entered wrong path: %s', path)
328 sys.exit()
329 sys.exit()
329
330
330 self.create_ui_settings()
331 self.create_ui_settings()
331
332
332 #HG UI OPTIONS
333 #HG UI OPTIONS
333 web1 = RhodeCodeUi()
334 web1 = RhodeCodeUi()
334 web1.ui_section = 'web'
335 web1.ui_section = 'web'
335 web1.ui_key = 'push_ssl'
336 web1.ui_key = 'push_ssl'
336 web1.ui_value = 'false'
337 web1.ui_value = 'false'
337
338
338 web2 = RhodeCodeUi()
339 web2 = RhodeCodeUi()
339 web2.ui_section = 'web'
340 web2.ui_section = 'web'
340 web2.ui_key = 'allow_archive'
341 web2.ui_key = 'allow_archive'
341 web2.ui_value = 'gz zip bz2'
342 web2.ui_value = 'gz zip bz2'
342
343
343 web3 = RhodeCodeUi()
344 web3 = RhodeCodeUi()
344 web3.ui_section = 'web'
345 web3.ui_section = 'web'
345 web3.ui_key = 'allow_push'
346 web3.ui_key = 'allow_push'
346 web3.ui_value = '*'
347 web3.ui_value = '*'
347
348
348 web4 = RhodeCodeUi()
349 web4 = RhodeCodeUi()
349 web4.ui_section = 'web'
350 web4.ui_section = 'web'
350 web4.ui_key = 'baseurl'
351 web4.ui_key = 'baseurl'
351 web4.ui_value = '/'
352 web4.ui_value = '/'
352
353
353 paths = RhodeCodeUi()
354 paths = RhodeCodeUi()
354 paths.ui_section = 'paths'
355 paths.ui_section = 'paths'
355 paths.ui_key = '/'
356 paths.ui_key = '/'
356 paths.ui_value = path
357 paths.ui_value = path
357
358
358
359
359 hgsettings1 = RhodeCodeSettings('realm', 'RhodeCode authentication')
360 hgsettings1 = RhodeCodeSettings('realm', 'RhodeCode authentication')
360 hgsettings2 = RhodeCodeSettings('title', 'RhodeCode')
361 hgsettings2 = RhodeCodeSettings('title', 'RhodeCode')
361
362
362
363
363 try:
364 try:
364 self.sa.add(web1)
365 self.sa.add(web1)
365 self.sa.add(web2)
366 self.sa.add(web2)
366 self.sa.add(web3)
367 self.sa.add(web3)
367 self.sa.add(web4)
368 self.sa.add(web4)
368 self.sa.add(paths)
369 self.sa.add(paths)
369 self.sa.add(hgsettings1)
370 self.sa.add(hgsettings1)
370 self.sa.add(hgsettings2)
371 self.sa.add(hgsettings2)
371
372
372 self.sa.commit()
373 self.sa.commit()
373 except:
374 except:
374 self.sa.rollback()
375 self.sa.rollback()
375 raise
376 raise
376
377
377 self.create_ldap_options()
378 self.create_ldap_options()
378
379
379 log.info('created ui config')
380 log.info('created ui config')
380
381
381 def create_user(self, username, password, email='', admin=False):
382 def create_user(self, username, password, email='', admin=False):
382 log.info('creating administrator user %s', username)
383 log.info('creating administrator user %s', username)
383 new_user = User()
384 new_user = User()
384 new_user.username = username
385 new_user.username = username
385 new_user.password = get_crypt_password(password)
386 new_user.password = get_crypt_password(password)
386 new_user.name = 'RhodeCode'
387 new_user.name = 'RhodeCode'
387 new_user.lastname = 'Admin'
388 new_user.lastname = 'Admin'
388 new_user.email = email
389 new_user.email = email
389 new_user.admin = admin
390 new_user.admin = admin
390 new_user.active = True
391 new_user.active = True
391
392
392 try:
393 try:
393 self.sa.add(new_user)
394 self.sa.add(new_user)
394 self.sa.commit()
395 self.sa.commit()
395 except:
396 except:
396 self.sa.rollback()
397 self.sa.rollback()
397 raise
398 raise
398
399
399 def create_default_user(self):
400 def create_default_user(self):
400 log.info('creating default user')
401 log.info('creating default user')
401 #create default user for handling default permissions.
402 #create default user for handling default permissions.
402 def_user = User()
403 def_user = User()
403 def_user.username = 'default'
404 def_user.username = 'default'
404 def_user.password = get_crypt_password(str(uuid.uuid1())[:8])
405 def_user.password = get_crypt_password(str(uuid.uuid1())[:8])
405 def_user.name = 'Anonymous'
406 def_user.name = 'Anonymous'
406 def_user.lastname = 'User'
407 def_user.lastname = 'User'
407 def_user.email = 'anonymous@rhodecode.org'
408 def_user.email = 'anonymous@rhodecode.org'
408 def_user.admin = False
409 def_user.admin = False
409 def_user.active = False
410 def_user.active = False
410 try:
411 try:
411 self.sa.add(def_user)
412 self.sa.add(def_user)
412 self.sa.commit()
413 self.sa.commit()
413 except:
414 except:
414 self.sa.rollback()
415 self.sa.rollback()
415 raise
416 raise
416
417
417 def create_permissions(self):
418 def create_permissions(self):
418 #module.(access|create|change|delete)_[name]
419 #module.(access|create|change|delete)_[name]
419 #module.(read|write|owner)
420 #module.(read|write|owner)
420 perms = [('repository.none', 'Repository no access'),
421 perms = [('repository.none', 'Repository no access'),
421 ('repository.read', 'Repository read access'),
422 ('repository.read', 'Repository read access'),
422 ('repository.write', 'Repository write access'),
423 ('repository.write', 'Repository write access'),
423 ('repository.admin', 'Repository admin access'),
424 ('repository.admin', 'Repository admin access'),
424 ('hg.admin', 'Hg Administrator'),
425 ('hg.admin', 'Hg Administrator'),
425 ('hg.create.repository', 'Repository create'),
426 ('hg.create.repository', 'Repository create'),
426 ('hg.create.none', 'Repository creation disabled'),
427 ('hg.create.none', 'Repository creation disabled'),
427 ('hg.register.none', 'Register disabled'),
428 ('hg.register.none', 'Register disabled'),
428 ('hg.register.manual_activate', 'Register new user with rhodecode without manual activation'),
429 ('hg.register.manual_activate', 'Register new user with rhodecode without manual activation'),
429 ('hg.register.auto_activate', 'Register new user with rhodecode without auto activation'),
430 ('hg.register.auto_activate', 'Register new user with rhodecode without auto activation'),
430 ]
431 ]
431
432
432 for p in perms:
433 for p in perms:
433 new_perm = Permission()
434 new_perm = Permission()
434 new_perm.permission_name = p[0]
435 new_perm.permission_name = p[0]
435 new_perm.permission_longname = p[1]
436 new_perm.permission_longname = p[1]
436 try:
437 try:
437 self.sa.add(new_perm)
438 self.sa.add(new_perm)
438 self.sa.commit()
439 self.sa.commit()
439 except:
440 except:
440 self.sa.rollback()
441 self.sa.rollback()
441 raise
442 raise
442
443
443 def populate_default_permissions(self):
444 def populate_default_permissions(self):
444 log.info('creating default user permissions')
445 log.info('creating default user permissions')
445
446
446 default_user = self.sa.query(User)\
447 default_user = self.sa.query(User)\
447 .filter(User.username == 'default').scalar()
448 .filter(User.username == 'default').scalar()
448
449
449 reg_perm = UserToPerm()
450 reg_perm = UserToPerm()
450 reg_perm.user = default_user
451 reg_perm.user = default_user
451 reg_perm.permission = self.sa.query(Permission)\
452 reg_perm.permission = self.sa.query(Permission)\
452 .filter(Permission.permission_name == 'hg.register.manual_activate')\
453 .filter(Permission.permission_name == 'hg.register.manual_activate')\
453 .scalar()
454 .scalar()
454
455
455 create_repo_perm = UserToPerm()
456 create_repo_perm = UserToPerm()
456 create_repo_perm.user = default_user
457 create_repo_perm.user = default_user
457 create_repo_perm.permission = self.sa.query(Permission)\
458 create_repo_perm.permission = self.sa.query(Permission)\
458 .filter(Permission.permission_name == 'hg.create.repository')\
459 .filter(Permission.permission_name == 'hg.create.repository')\
459 .scalar()
460 .scalar()
460
461
461 default_repo_perm = UserToPerm()
462 default_repo_perm = UserToPerm()
462 default_repo_perm.user = default_user
463 default_repo_perm.user = default_user
463 default_repo_perm.permission = self.sa.query(Permission)\
464 default_repo_perm.permission = self.sa.query(Permission)\
464 .filter(Permission.permission_name == 'repository.read')\
465 .filter(Permission.permission_name == 'repository.read')\
465 .scalar()
466 .scalar()
466
467
467 try:
468 try:
468 self.sa.add(reg_perm)
469 self.sa.add(reg_perm)
469 self.sa.add(create_repo_perm)
470 self.sa.add(create_repo_perm)
470 self.sa.add(default_repo_perm)
471 self.sa.add(default_repo_perm)
471 self.sa.commit()
472 self.sa.commit()
472 except:
473 except:
473 self.sa.rollback()
474 self.sa.rollback()
474 raise
475 raise
475
476
@@ -1,26 +1,54 b''
1 """Setup the rhodecode application"""
1 # -*- coding: utf-8 -*-
2 """
3 rhodecode.websetup
4 ~~~~~~~~~~~~~~~~~~
5
6 Weboperations and setup for rhodecode
7
8 :created_on: Dec 11, 2010
9 :author: marcink
10 :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
11 :license: GPLv3, see COPYING for more details.
12 """
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License
15 # as published by the Free Software Foundation; version 2
16 # of the License or (at your opinion) any later version of the license.
17 #
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
26 # MA 02110-1301, USA.
27
28 import os
29 import logging
30
2 from rhodecode.config.environment import load_environment
31 from rhodecode.config.environment import load_environment
3 from rhodecode.lib.db_manage import DbManage
32 from rhodecode.lib.db_manage import DbManage
4 import logging
33
5 import os
6
34
7 log = logging.getLogger(__name__)
35 log = logging.getLogger(__name__)
8
36
9 def setup_app(command, conf, vars):
37 def setup_app(command, conf, vars):
10 """Place any commands to setup rhodecode here"""
38 """Place any commands to setup rhodecode here"""
11 dbconf = conf['sqlalchemy.db1.url']
39 dbconf = conf['sqlalchemy.db1.url']
12 dbmanage = DbManage(log_sql=True, dbconf=dbconf, root=conf['here'], tests=False)
40 dbmanage = DbManage(log_sql=True, dbconf=dbconf, root=conf['here'], tests=False)
13 dbmanage.create_tables(override=True)
41 dbmanage.create_tables(override=True)
14 dbmanage.set_db_version()
42 dbmanage.set_db_version()
15 dbmanage.config_prompt(None)
43 dbmanage.config_prompt(None)
16 dbmanage.create_default_user()
44 dbmanage.create_default_user()
17 dbmanage.admin_prompt()
45 dbmanage.admin_prompt()
18 dbmanage.create_permissions()
46 dbmanage.create_permissions()
19 dbmanage.populate_default_permissions()
47 dbmanage.populate_default_permissions()
20
48
21 load_environment(conf.global_conf, conf.local_conf, initial=True)
49 load_environment(conf.global_conf, conf.local_conf, initial=True)
22
50
23
51
24
52
25
53
26
54
General Comments 0
You need to be logged in to leave comments. Login now