##// END OF EJS Templates
User usermodel instead of db model to manage accounts...
marcink -
r1634:1d904d97 beta
parent child Browse files
Show More
@@ -33,7 +33,7 b' from os.path import dirname as dn, join '
33 from rhodecode import __dbversion__
33 from rhodecode import __dbversion__
34 from rhodecode.model import meta
34 from rhodecode.model import meta
35
35
36 from rhodecode.lib.auth import get_crypt_password, generate_api_key
36 from rhodecode.model.user import UserModel
37 from rhodecode.lib.utils import ask_ok
37 from rhodecode.lib.utils import ask_ok
38 from rhodecode.model import init_model
38 from rhodecode.model import init_model
39 from rhodecode.model.db import User, Permission, RhodeCodeUi, \
39 from rhodecode.model.db import User, Permission, RhodeCodeUi, \
@@ -415,30 +415,18 b' class DbManage(object):'
415 log.info('created ui config')
415 log.info('created ui config')
416
416
417 def create_user(self, username, password, email='', admin=False):
417 def create_user(self, username, password, email='', admin=False):
418 log.info('creating administrator user %s', username)
418 log.info('creating user %s', username)
419
419 UserModel().create_or_update(username, password, email,
420 form_data = dict(username=username,
420 name='RhodeCode', lastname='Admin',
421 password=password,
421 active=True, admin=admin)
422 active=True,
423 admin=admin,
424 name='RhodeCode',
425 lastname='Admin',
426 email=email)
427 User.create(form_data)
428
429
422
430 def create_default_user(self):
423 def create_default_user(self):
431 log.info('creating default user')
424 log.info('creating default user')
432 #create default user for handling default permissions.
425 # create default user for handling default permissions.
433
426 UserModel().create_or_update(username='default',
434 form_data = dict(username='default',
427 password=str(uuid.uuid1())[:8],
435 password=str(uuid.uuid1())[:8],
428 email='anonymous@rhodecode.org',
436 active=False,
429 name='Anonymous', lastname='User')
437 admin=False,
438 name='Anonymous',
439 lastname='User',
440 email='anonymous@rhodecode.org')
441 User.create(form_data)
442
430
443 def create_permissions(self):
431 def create_permissions(self):
444 #module.(access|create|change|delete)_[name]
432 #module.(access|create|change|delete)_[name]
@@ -47,15 +47,14 b' from rhodecode.model import meta'
47 from rhodecode.model.caching_query import FromCache
47 from rhodecode.model.caching_query import FromCache
48 from rhodecode.model.db import Repository, User, RhodeCodeUi, UserLog, RepoGroup, \
48 from rhodecode.model.db import Repository, User, RhodeCodeUi, UserLog, RepoGroup, \
49 RhodeCodeSetting
49 RhodeCodeSetting
50 from rhodecode.model.repo import RepoModel
51
50
52 log = logging.getLogger(__name__)
51 log = logging.getLogger(__name__)
53
52
54
53
55 def recursive_replace(str, replace=' '):
54 def recursive_replace(str_, replace=' '):
56 """Recursive replace of given sign to just one instance
55 """Recursive replace of given sign to just one instance
57
56
58 :param str: given string
57 :param str_: given string
59 :param replace: char to find and replace multiple instances
58 :param replace: char to find and replace multiple instances
60
59
61 Examples::
60 Examples::
@@ -63,11 +62,11 b" def recursive_replace(str, replace=' '):"
63 'Mighty-Mighty-Bo-sstones'
62 'Mighty-Mighty-Bo-sstones'
64 """
63 """
65
64
66 if str.find(replace * 2) == -1:
65 if str_.find(replace * 2) == -1:
67 return str
66 return str_
68 else:
67 else:
69 str = str.replace(replace * 2, replace)
68 str_ = str_.replace(replace * 2, replace)
70 return recursive_replace(str, replace)
69 return recursive_replace(str_, replace)
71
70
72
71
73 def repo_name_slug(value):
72 def repo_name_slug(value):
@@ -116,13 +115,12 b' def action_logger(user, action, repo, ip'
116 else:
115 else:
117 raise Exception('You have to provide user object or username')
116 raise Exception('You have to provide user object or username')
118
117
119 rm = RepoModel()
120 if hasattr(repo, 'repo_id'):
118 if hasattr(repo, 'repo_id'):
121 repo_obj = rm.get(repo.repo_id, cache=False)
119 repo_obj = Repository.get(repo.repo_id)
122 repo_name = repo_obj.repo_name
120 repo_name = repo_obj.repo_name
123 elif isinstance(repo, basestring):
121 elif isinstance(repo, basestring):
124 repo_name = repo.lstrip('/')
122 repo_name = repo.lstrip('/')
125 repo_obj = rm.get_by_repo_name(repo_name, cache=False)
123 repo_obj = Repository.get_by_repo_name(repo_name)
126 else:
124 else:
127 raise Exception('You have to provide repository to action logger')
125 raise Exception('You have to provide repository to action logger')
128
126
@@ -151,8 +149,6 b' def get_repos(path, recursive=False):'
151 :param path: path to scann for repositories
149 :param path: path to scann for repositories
152 :param recursive: recursive search and return names with subdirs in front
150 :param recursive: recursive search and return names with subdirs in front
153 """
151 """
154 from vcs.utils.helpers import get_scm
155 from vcs.exceptions import VCSError
156
152
157 if path.endswith(os.sep):
153 if path.endswith(os.sep):
158 #remove ending slash for better results
154 #remove ending slash for better results
@@ -377,17 +373,20 b' def map_groups(groups):'
377
373
378
374
379 def repo2db_mapper(initial_repo_list, remove_obsolete=False):
375 def repo2db_mapper(initial_repo_list, remove_obsolete=False):
380 """maps all repos given in initial_repo_list, non existing repositories
376 """
377 maps all repos given in initial_repo_list, non existing repositories
381 are created, if remove_obsolete is True it also check for db entries
378 are created, if remove_obsolete is True it also check for db entries
382 that are not in initial_repo_list and removes them.
379 that are not in initial_repo_list and removes them.
383
380
384 :param initial_repo_list: list of repositories found by scanning methods
381 :param initial_repo_list: list of repositories found by scanning methods
385 :param remove_obsolete: check for obsolete entries in database
382 :param remove_obsolete: check for obsolete entries in database
386 """
383 """
387
384 from rhodecode.model.repo import RepoModel
388 sa = meta.Session()
385 sa = meta.Session()
389 rm = RepoModel()
386 rm = RepoModel()
390 user = sa.query(User).filter(User.admin == True).first()
387 user = sa.query(User).filter(User.admin == True).first()
388 if user is None:
389 raise Exception('Missing administrative account !')
391 added = []
390 added = []
392 # fixup groups paths to new format on the fly
391 # fixup groups paths to new format on the fly
393 # TODO: remove this in future
392 # TODO: remove this in future
@@ -30,6 +30,7 b' import traceback'
30 from datetime import date
30 from datetime import date
31
31
32 from sqlalchemy import *
32 from sqlalchemy import *
33 from sqlalchemy.exc import DatabaseError
33 from sqlalchemy.ext.hybrid import hybrid_property
34 from sqlalchemy.ext.hybrid import hybrid_property
34 from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
35 from sqlalchemy.orm import relationship, joinedload, class_mapper, validates
35 from beaker.cache import cache_region, region_invalidate
36 from beaker.cache import cache_region, region_invalidate
@@ -322,26 +323,6 b' class User(Base, BaseModel):'
322 Session.commit()
323 Session.commit()
323 log.debug('updated user %s lastlogin', self.username)
324 log.debug('updated user %s lastlogin', self.username)
324
325
325 @classmethod
326 def create(cls, form_data):
327 from rhodecode.lib.auth import get_crypt_password
328
329 try:
330 new_user = cls()
331 for k, v in form_data.items():
332 if k == 'password':
333 v = get_crypt_password(v)
334 setattr(new_user, k, v)
335
336 new_user.api_key = generate_api_key(form_data['username'])
337 Session.add(new_user)
338 Session.commit()
339 return new_user
340 except:
341 log.error(traceback.format_exc())
342 Session.rollback()
343 raise
344
345 class UserLog(Base, BaseModel):
326 class UserLog(Base, BaseModel):
346 __tablename__ = 'user_logs'
327 __tablename__ = 'user_logs'
347 __table_args__ = {'extend_existing':True}
328 __table_args__ = {'extend_existing':True}
@@ -92,6 +92,54 b' class UserModel(BaseModel):'
92 self.sa.rollback()
92 self.sa.rollback()
93 raise
93 raise
94
94
95
96 def create_or_update(self, username, password, email, name, lastname,
97 active=True, admin=False, ldap_dn=None):
98 """
99 Creates a new instance if not found, or updates current one
100
101 :param username:
102 :param password:
103 :param email:
104 :param active:
105 :param name:
106 :param lastname:
107 :param active:
108 :param admin:
109 :param ldap_dn:
110 """
111
112 from rhodecode.lib.auth import get_crypt_password
113
114 log.debug('Checking for %s account in RhodeCode database', username)
115 user = User.get_by_username(username, case_insensitive=True)
116 if user is None:
117 log.debug('creating new user %s', username)
118 new_user = User()
119 else:
120 log.debug('updating user %s', username)
121 new_user = user
122
123 try:
124 new_user.username = username
125 new_user.admin = admin
126 new_user.password = get_crypt_password(password)
127 new_user.api_key = generate_api_key(username)
128 new_user.email = email
129 new_user.active = active
130 new_user.ldap_dn = safe_unicode(ldap_dn) if ldap_dn else None
131 new_user.name = name
132 new_user.lastname = lastname
133
134 self.sa.add(new_user)
135 self.sa.commit()
136 return new_user
137 except (DatabaseError,):
138 log.error(traceback.format_exc())
139 self.sa.rollback()
140 raise
141
142
95 def create_for_container_auth(self, username, attrs):
143 def create_for_container_auth(self, username, attrs):
96 """
144 """
97 Creates the given user if it's not already in the database
145 Creates the given user if it's not already in the database
General Comments 0
You need to be logged in to leave comments. Login now