def test_update(self): self.log_user() params = { 'default_repo_enable_locking': True, 'default_repo_enable_downloads': True, 'default_repo_enable_statistics': True, 'default_repo_private': True, 'default_repo_type': 'hg', } response = self.app.put(url('default', id='default'), params=params) self.checkSessionFlash(response, 'Default settings updated successfully') defs = RhodeCodeSetting.get_default_repo_settings() self.assertEqual(params, defs) params = { 'default_repo_enable_locking': False, 'default_repo_enable_downloads': False, 'default_repo_enable_statistics': False, 'default_repo_private': False, 'default_repo_type': 'git', } response = self.app.put(url('default', id='default'), params=params) self.checkSessionFlash(response, 'Default settings updated successfully') defs = RhodeCodeSetting.get_default_repo_settings() self.assertEqual(params, defs)
def create_default_options(self, skip_existing=False): """Creates default settings""" for k, v in [('default_repo_enable_locking', False), ('default_repo_enable_downloads', False), ('default_repo_enable_statistics', False), ('default_repo_private', False), ('default_repo_type', 'hg')]: if skip_existing and RhodeCodeSetting.get_by_name(k) is not None: log.debug('Skipping option %s' % k) continue setting = RhodeCodeSetting(k, v) self.sa.add(setting)
def create_ldap_options(self, skip_existing=False): """Creates ldap settings""" for k, v in [('ldap_active', 'false'), ('ldap_host', ''), ('ldap_port', '389'), ('ldap_tls_kind', 'PLAIN'), ('ldap_tls_reqcert', ''), ('ldap_dn_user', ''), ('ldap_dn_pass', ''), ('ldap_base_dn', ''), ('ldap_filter', ''), ('ldap_search_scope', ''), ('ldap_attr_login', ''), ('ldap_attr_firstname', ''), ('ldap_attr_lastname', ''), ('ldap_attr_email', '')]: if skip_existing and RhodeCodeSetting.get_by_name(k) is not None: log.debug('Skipping option %s' % k) continue setting = RhodeCodeSetting(k, v) self.sa.add(setting)
def update(self, id): """PUT /defaults/id: Update an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="PUT" /> # Or using helpers: # h.form(url('default', id=ID), # method='put') # url('default', id=ID) _form = DefaultsForm()() try: form_result = _form.to_python(dict(request.POST)) for k, v in form_result.iteritems(): setting = RhodeCodeSetting.get_by_name_or_create(k) setting.app_settings_value = v Session().add(setting) Session().commit() h.flash(_('Default settings updated successfully'), category='success') except formencode.Invalid, errors: defaults = errors.value return htmlfill.render( render('admin/defaults/defaults.html'), defaults=defaults, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8")
def create_settings(self, path): self.create_ui_settings() ui_config = [ ('web', 'push_ssl', 'false'), ('web', 'allow_archive', 'gz zip bz2'), ('web', 'allow_push', '*'), ('web', 'baseurl', '/'), ('paths', '/', path), #('phases', 'publish', 'false') ] for section, key, value in ui_config: ui_conf = RhodeCodeUi() setattr(ui_conf, 'ui_section', section) setattr(ui_conf, 'ui_key', key) setattr(ui_conf, 'ui_value', value) self.sa.add(ui_conf) settings = [('realm', 'RhodeCode authentication', unicode), ('title', 'RhodeCode', unicode), ('ga_code', '', unicode), ('show_public_icon', True, bool), ('show_private_icon', True, bool), ('stylify_metatags', False, bool), ('dashboard_items', 100, int), ('show_version', True, bool)] for key, val, type_ in settings: sett = RhodeCodeSetting(key, val) self.sa.add(sett) self.create_ldap_options() self.create_default_options() log.info('created ui config')
def __before__(self): """ __before__ is called before controller methods and after __call__ """ c.rhodecode_version = __version__ c.rhodecode_instanceid = config.get('instance_id') c.rhodecode_name = config.get('rhodecode_title') c.rhodecode_bugtracker = config.get('bugtracker', 'http://bitbucket.org/marcinkuzminski/rhodecode/issues') c.use_gravatar = str2bool(config.get('use_gravatar')) c.ga_code = config.get('rhodecode_ga_code') # Visual options c.visual = AttributeDict({}) rc_config = RhodeCodeSetting.get_app_settings() ## DB stored c.visual.show_public_icon = str2bool(rc_config.get('rhodecode_show_public_icon')) c.visual.show_private_icon = str2bool(rc_config.get('rhodecode_show_private_icon')) c.visual.stylify_metatags = str2bool(rc_config.get('rhodecode_stylify_metatags')) c.visual.dashboard_items = safe_int(rc_config.get('rhodecode_dashboard_items', 100)) c.visual.repository_fields = str2bool(rc_config.get('rhodecode_repository_fields')) c.visual.show_version = str2bool(rc_config.get('rhodecode_show_version')) ## INI stored self.cut_off_limit = int(config.get('cut_off_limit')) c.visual.allow_repo_location_change = str2bool(config.get('allow_repo_location_change', True)) c.visual.allow_custom_hooks_settings = str2bool(config.get('allow_custom_hooks_settings', True)) c.repo_name = get_repo_slug(request) # can be empty c.backends = BACKENDS.keys() c.unread_notifications = NotificationModel()\ .get_unread_cnt_for_user(c.rhodecode_user.user_id) self.sa = meta.Session self.scm_model = ScmModel(self.sa)
def __before__(self): c.rhodecode_version = __version__ c.rhodecode_instanceid = config.get('instance_id') c.rhodecode_name = config.get('rhodecode_title') c.use_gravatar = str2bool(config.get('use_gravatar')) c.ga_code = config.get('rhodecode_ga_code') # Visual options c.visual = AttributeDict({}) rc_config = RhodeCodeSetting.get_app_settings() c.visual.show_public_icon = str2bool(rc_config.get('rhodecode_show_public_icon')) c.visual.show_private_icon = str2bool(rc_config.get('rhodecode_show_private_icon')) c.visual.stylify_metatags = str2bool(rc_config.get('rhodecode_stylify_metatags')) c.visual.lightweight_dashboard = str2bool(rc_config.get('rhodecode_lightweight_dashboard')) c.visual.lightweight_dashboard_items = safe_int(config.get('dashboard_items', 100)) c.repo_name = get_repo_slug(request) c.backends = BACKENDS.keys() c.unread_notifications = NotificationModel()\ .get_unread_cnt_for_user(c.rhodecode_user.user_id) self.cut_off_limit = int(config.get('cut_off_limit')) self.sa = meta.Session self.scm_model = ScmModel(self.sa) self.ip_addr = ''
def __before__(self): """ __before__ is called before controller methods and after __call__ """ c.rhodecode_version = __version__ c.rhodecode_instanceid = config.get('instance_id') c.rhodecode_name = config.get('rhodecode_title') c.use_gravatar = str2bool(config.get('use_gravatar')) c.ga_code = config.get('rhodecode_ga_code') # Visual options c.visual = AttributeDict({}) rc_config = RhodeCodeSetting.get_app_settings() ## DB stored c.visual.show_public_icon = str2bool(rc_config.get('rhodecode_show_public_icon')) c.visual.show_private_icon = str2bool(rc_config.get('rhodecode_show_private_icon')) c.visual.stylify_metatags = str2bool(rc_config.get('rhodecode_stylify_metatags')) c.visual.dashboard_items = safe_int(rc_config.get('rhodecode_dashboard_items', 100)) c.visual.repository_fields = str2bool(rc_config.get('rhodecode_repository_fields')) c.visual.show_version = str2bool(rc_config.get('rhodecode_show_version')) ## INI stored self.cut_off_limit = int(config.get('cut_off_limit')) c.visual.allow_repo_location_change = str2bool(config.get('allow_repo_location_change', True)) c.repo_name = get_repo_slug(request) # can be empty c.backends = BACKENDS.keys() c.unread_notifications = NotificationModel()\ .get_unread_cnt_for_user(c.rhodecode_user.user_id) self.sa = meta.Session self.scm_model = ScmModel(self.sa)
def test_ldap_save_settings(self): self.log_user() if skip_ldap_test: raise SkipTest('skipping due to missing ldap lib') test_url = url(controller='admin/ldap_settings', action='ldap_settings') response = self.app.post(url=test_url, params={'ldap_host' : u'dc.example.com', 'ldap_port' : '999', 'ldap_tls_kind' : 'PLAIN', 'ldap_tls_reqcert' : 'NEVER', 'ldap_dn_user':'******', 'ldap_dn_pass':'******', 'ldap_base_dn':'test_base_dn', 'ldap_filter':'test_filter', 'ldap_search_scope':'BASE', 'ldap_attr_login':'******', 'ldap_attr_firstname':'ima', 'ldap_attr_lastname':'tester', 'ldap_attr_email':'*****@*****.**' }) new_settings = RhodeCodeSetting.get_ldap_settings() self.assertEqual(new_settings['ldap_host'], u'dc.example.com', 'fail db write compare') self.checkSessionFlash(response, 'Ldap settings updated successfully')
def create(self, form_data, cur_user, just_db=False, fork=None): """ Backward compatibility function, just a wrapper on top of create_repo :param form_data: :param cur_user: :param just_db: :param fork: """ owner = cur_user repo_name = form_data['repo_name_full'] repo_type = form_data['repo_type'] description = form_data['repo_description'] private = form_data['repo_private'] clone_uri = form_data.get('clone_uri') repos_group = form_data['repo_group'] landing_rev = form_data['repo_landing_rev'] copy_fork_permissions = form_data.get('copy_permissions') fork_of = form_data.get('fork_parent_id') ## repo creation defaults, private and repo_type are filled in form defs = RhodeCodeSetting.get_default_repo_settings(strip_prefix=True) enable_statistics = defs.get('repo_enable_statistics') enable_locking = defs.get('repo_enable_locking') enable_downloads = defs.get('repo_enable_downloads') return self.create_repo(repo_name, repo_type, description, owner, private, clone_uri, repos_group, landing_rev, just_db, fork_of, copy_fork_permissions, enable_statistics, enable_locking, enable_downloads)
def update(self, id): """PUT /defaults/id: Update an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="PUT" /> # Or using helpers: # h.form(url('default', id=ID), # method='put') # url('default', id=ID) _form = DefaultsForm()() try: form_result = _form.to_python(dict(request.POST)) for k, v in form_result.iteritems(): setting = RhodeCodeSetting.get_by_name_or_create(k) setting.app_settings_value = v Session().add(setting) Session().commit() h.flash(_('Default settings updated successfully'), category='success') except formencode.Invalid, errors: defaults = errors.value return htmlfill.render(render('admin/defaults/defaults.html'), defaults=defaults, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8")
def create_repository(self): """GET /_admin/create_repository: Form to create a new item""" new_repo = request.GET.get('repo', '') parent_group = request.GET.get('parent_group') if not HasPermissionAny('hg.admin', 'hg.create.repository')(): #you're not super admin nor have global create permissions, #but maybe you have at least write permission to a parent group ? _gr = RepoGroup.get(parent_group) gr_name = _gr.group_name if _gr else None if not HasReposGroupPermissionAny('group.admin', 'group.write')(group_name=gr_name): raise HTTPForbidden acl_groups = GroupList(RepoGroup.query().all(), perm_set=['group.write', 'group.admin']) c.repo_groups = RepoGroup.groups_choices(groups=acl_groups) c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups) choices, c.landing_revs = ScmModel().get_repo_landing_revs() c.new_repo = repo_name_slug(new_repo) ## apply the defaults from defaults page defaults = RhodeCodeSetting.get_default_repo_settings(strip_prefix=True) if parent_group: defaults.update({'repo_group': parent_group}) return htmlfill.render( render('admin/repos/repo_add.html'), defaults=defaults, errors={}, prefix_error=False, encoding="UTF-8" )
def create_ldap_options(self, skip_existing=False): """Creates ldap settings""" for k, v in [ ("ldap_active", "false"), ("ldap_host", ""), ("ldap_port", "389"), ("ldap_tls_kind", "PLAIN"), ("ldap_tls_reqcert", ""), ("ldap_dn_user", ""), ("ldap_dn_pass", ""), ("ldap_base_dn", ""), ("ldap_filter", ""), ("ldap_search_scope", ""), ("ldap_attr_login", ""), ("ldap_attr_firstname", ""), ("ldap_attr_lastname", ""), ("ldap_attr_email", ""), ]: if skip_existing and RhodeCodeSetting.get_by_name(k) != None: log.debug("Skipping option %s" % k) continue setting = RhodeCodeSetting(k, v) self.sa.add(setting)
def test_ldap_save_settings(self): self.log_user() if skip_ldap_test: raise SkipTest("skipping due to missing ldap lib") test_url = url(controller="admin/ldap_settings", action="ldap_settings") response = self.app.post( url=test_url, params={ "ldap_host": u"dc.example.com", "ldap_port": "999", "ldap_tls_kind": "PLAIN", "ldap_tls_reqcert": "NEVER", "ldap_dn_user": "******", "ldap_dn_pass": "******", "ldap_base_dn": "test_base_dn", "ldap_filter": "test_filter", "ldap_search_scope": "BASE", "ldap_attr_login": "******", "ldap_attr_firstname": "ima", "ldap_attr_lastname": "tester", "ldap_attr_email": "*****@*****.**", }, ) new_settings = RhodeCodeSetting.get_ldap_settings() print new_settings self.assertEqual(new_settings["ldap_host"], u"dc.example.com", "fail db write compare") self.checkSessionFlash(response, "Ldap settings updated successfully")
def test_ldap_save_settings(self): self.log_user() if ldap_lib_installed: raise SkipTest('skipping due to missing ldap lib') test_url = url(controller='admin/ldap_settings', action='ldap_settings') response = self.app.post(url=test_url, params={ 'ldap_host': u'dc.example.com', 'ldap_port': '999', 'ldap_tls_kind': 'PLAIN', 'ldap_tls_reqcert': 'NEVER', 'ldap_dn_user': '******', 'ldap_dn_pass': '******', 'ldap_base_dn': 'test_base_dn', 'ldap_filter': 'test_filter', 'ldap_search_scope': 'BASE', 'ldap_attr_login': '******', 'ldap_attr_firstname': 'ima', 'ldap_attr_lastname': 'tester', 'ldap_attr_email': '*****@*****.**' }) new_settings = RhodeCodeSetting.get_ldap_settings() self.assertEqual(new_settings['ldap_host'], u'dc.example.com', 'fail db write compare') self.checkSessionFlash(response, 'LDAP settings updated successfully')
def create(self, form_data, cur_user, just_db=False, fork=None): """ Backward compatibility function, just a wrapper on top of create_repo :param form_data: :param cur_user: :param just_db: :param fork: """ owner = cur_user repo_name = form_data['repo_name_full'] repo_type = form_data['repo_type'] description = form_data['repo_description'] private = form_data['repo_private'] clone_uri = form_data.get('clone_uri') repos_group = form_data['repo_group'] landing_rev = form_data['repo_landing_rev'] copy_fork_permissions = form_data.get('copy_permissions') fork_of = form_data.get('fork_parent_id') ## repo creation defaults, private and repo_type are filled in form defs = RhodeCodeSetting.get_default_repo_settings(strip_prefix=True) enable_statistics = defs.get('repo_enable_statistics') enable_locking = defs.get('repo_enable_locking') enable_downloads = defs.get('repo_enable_downloads') return self.create_repo( repo_name, repo_type, description, owner, private, clone_uri, repos_group, landing_rev, just_db, fork_of, copy_fork_permissions, enable_statistics, enable_locking, enable_downloads )
def create_repository(self): """GET /_admin/create_repository: Form to create a new item""" new_repo = request.GET.get('repo', '') parent_group = request.GET.get('parent_group') if not HasPermissionAny('hg.admin', 'hg.create.repository')(): #you're not super admin nor have global create permissions, #but maybe you have at least write permission to a parent group ? _gr = RepoGroup.get(parent_group) gr_name = _gr.group_name if _gr else None if not HasReposGroupPermissionAny( 'group.admin', 'group.write')(group_name=gr_name): raise HTTPForbidden acl_groups = GroupList(RepoGroup.query().all(), perm_set=['group.write', 'group.admin']) c.repo_groups = RepoGroup.groups_choices(groups=acl_groups) c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups) choices, c.landing_revs = ScmModel().get_repo_landing_revs() c.new_repo = repo_name_slug(new_repo) ## apply the defaults from defaults page defaults = RhodeCodeSetting.get_default_repo_settings( strip_prefix=True) if parent_group: defaults.update({'repo_group': parent_group}) return htmlfill.render(render('admin/repos/repo_add.html'), defaults=defaults, errors={}, prefix_error=False, encoding="UTF-8")
def create_settings(self, path): self.create_ui_settings() #HG UI OPTIONS web1 = RhodeCodeUi() web1.ui_section = 'web' web1.ui_key = 'push_ssl' web1.ui_value = 'false' web2 = RhodeCodeUi() web2.ui_section = 'web' web2.ui_key = 'allow_archive' web2.ui_value = 'gz zip bz2' web3 = RhodeCodeUi() web3.ui_section = 'web' web3.ui_key = 'allow_push' web3.ui_value = '*' web4 = RhodeCodeUi() web4.ui_section = 'web' web4.ui_key = 'baseurl' web4.ui_value = '/' paths = RhodeCodeUi() paths.ui_section = 'paths' paths.ui_key = '/' paths.ui_value = path hgsettings1 = RhodeCodeSetting('realm', 'RhodeCode authentication') hgsettings2 = RhodeCodeSetting('title', 'RhodeCode') hgsettings3 = RhodeCodeSetting('ga_code', '') self.sa.add(web1) self.sa.add(web2) self.sa.add(web3) self.sa.add(web4) self.sa.add(paths) self.sa.add(hgsettings1) self.sa.add(hgsettings2) self.sa.add(hgsettings3) self.create_ldap_options() log.info('created ui config')
def set_rhodecode_config(config): """ Updates pylons config with new settings from database :param config: """ hgsettings = RhodeCodeSetting.get_app_settings() for k, v in hgsettings.items(): config[k] = v
def index(self, format='html'): """GET /defaults: All items in the collection""" # url('defaults') c.backends = BACKENDS.keys() defaults = RhodeCodeSetting.get_default_repo_settings() return htmlfill.render(render('admin/defaults/defaults.html'), defaults=defaults, encoding="UTF-8", force_defaults=False)
def index(self, format='html'): """GET /admin/settings: All items in the collection""" # url('admin_settings') defaults = RhodeCodeSetting.get_app_settings() defaults.update(self._get_hg_ui_settings()) return htmlfill.render(render('admin/settings/settings.html'), defaults=defaults, encoding="UTF-8", force_defaults=False)
def index(self): defaults = RhodeCodeSetting.get_ldap_settings() c.search_scope_cur = defaults.get('ldap_search_scope') c.tls_reqcert_cur = defaults.get('ldap_tls_reqcert') c.tls_kind_cur = defaults.get('ldap_tls_kind') return htmlfill.render( render('admin/ldap/ldap.html'), defaults=defaults, encoding="UTF-8", force_defaults=True,)
def index(self, format='html'): """GET /defaults: All items in the collection""" # url('defaults') c.backends = BACKENDS.keys() defaults = RhodeCodeSetting.get_default_repo_settings() return htmlfill.render( render('admin/defaults/defaults.html'), defaults=defaults, encoding="UTF-8", force_defaults=False )
def index(self): defaults = RhodeCodeSetting.get_ldap_settings() c.search_scope_cur = defaults.get('ldap_search_scope') c.tls_reqcert_cur = defaults.get('ldap_tls_reqcert') c.tls_kind_cur = defaults.get('ldap_tls_kind') return htmlfill.render( render('admin/ldap/ldap.html'), defaults=defaults, encoding="UTF-8", force_defaults=True, )
def index(self, format='html'): """GET /admin/settings: All items in the collection""" # url('admin_settings') defaults = RhodeCodeSetting.get_app_settings() defaults.update(self.get_hg_ui_settings()) return htmlfill.render( render('admin/settings/settings.html'), defaults=defaults, encoding="UTF-8", force_defaults=False )
def create_settings(self, path): self.create_ui_settings() #HG UI OPTIONS web1 = RhodeCodeUi() web1.ui_section = 'web' web1.ui_key = 'push_ssl' web1.ui_value = 'false' web2 = RhodeCodeUi() web2.ui_section = 'web' web2.ui_key = 'allow_archive' web2.ui_value = 'gz zip bz2' web3 = RhodeCodeUi() web3.ui_section = 'web' web3.ui_key = 'allow_push' web3.ui_value = '*' web4 = RhodeCodeUi() web4.ui_section = 'web' web4.ui_key = 'baseurl' web4.ui_value = '/' paths = RhodeCodeUi() paths.ui_section = 'paths' paths.ui_key = '/' paths.ui_value = path phases = RhodeCodeUi() phases.ui_section = 'phases' phases.ui_key = 'publish' phases.ui_value = False sett1 = RhodeCodeSetting('realm', 'RhodeCode authentication') sett2 = RhodeCodeSetting('title', 'RhodeCode') sett3 = RhodeCodeSetting('ga_code', '') sett4 = RhodeCodeSetting('show_public_icon', True) sett5 = RhodeCodeSetting('show_private_icon', True) sett6 = RhodeCodeSetting('stylify_metatags', False) self.sa.add(web1) self.sa.add(web2) self.sa.add(web3) self.sa.add(web4) self.sa.add(paths) self.sa.add(sett1) self.sa.add(sett2) self.sa.add(sett3) self.sa.add(sett4) self.sa.add(sett5) self.sa.add(sett6) self.create_ldap_options() self.create_default_options() log.info('created ui config')
def fix_settings(self): """ Fixes rhodecode settings and adds ga_code key for google analytics """ hgsettings3 = RhodeCodeSetting('ga_code', '') try: self.sa.add(hgsettings3) self.sa.commit() except Exception: self.sa.rollback() raise
def new(self, format='html'): """GET /repos/new: Form to create a new item""" new_repo = request.GET.get('repo', '') c.new_repo = repo_name_slug(new_repo) self.__load_defaults() ## apply the defaults from defaults page defaults = RhodeCodeSetting.get_default_repo_settings(strip_prefix=True) return htmlfill.render( render('admin/repos/repo_add.html'), defaults=defaults, errors={}, prefix_error=False, encoding="UTF-8" )
def create_default_options(self, skip_existing=False): """Creates default settings""" for k, v in [ ('default_repo_enable_locking', False), ('default_repo_enable_downloads', False), ('default_repo_enable_statistics', False), ('default_repo_private', False), ('default_repo_type', 'hg')]: if skip_existing and RhodeCodeSetting.get_by_name(k) != None: log.debug('Skipping option %s' % k) continue setting = RhodeCodeSetting(k, v) self.sa.add(setting)
def create_auth_plugin_options(self, skip_existing=False): """ Create default auth plugin settings, and make it active :param skip_existing: """ for k, v, t in [('auth_plugins', 'egg:rhodecode-enterprise-ce#rhodecode', 'list'), ('auth_rhodecode_enabled', 'True', 'bool')]: if (skip_existing and SettingsModel().get_setting_by_name(k) is not None): log.debug('Skipping option %s' % k) continue setting = RhodeCodeSetting(k, v, t) self.sa.add(setting)
def ldap_settings(self): """POST ldap create and store ldap settings""" _form = LdapSettingsForm([x[0] for x in self.tls_reqcert_choices], [x[0] for x in self.search_scope_choices], [x[0] for x in self.tls_kind_choices])() # check the ldap lib ldap_active = False try: import ldap ldap_active = True except ImportError: pass try: form_result = _form.to_python(dict(request.POST)) try: for k, v in form_result.items(): if k.startswith('ldap_'): if k == 'ldap_active': v = ldap_active setting = RhodeCodeSetting.get_by_name(k) setting.app_settings_value = v Session().add(setting) Session().commit() h.flash(_('LDAP settings updated successfully'), category='success') if not ldap_active: #if ldap is missing send an info to user h.flash(_( 'Unable to activate ldap. The "python-ldap" library ' 'is missing.'), category='warning') except (DatabaseError, ): raise except formencode.Invalid, errors: e = errors.error_dict or {} return htmlfill.render(render('admin/ldap/ldap.html'), defaults=errors.value, errors=e, prefix_error=False, encoding="UTF-8")
def create_settings(self, path): self.create_ui_settings(path) ui_config = [ ('web', 'push_ssl', 'false'), ('web', 'allow_archive', 'gz zip bz2'), ('web', 'allow_push', '*'), ('web', 'baseurl', '/'), ('paths', '/', path), ('phases', 'publish', 'true') ] for section, key, value in ui_config: ui_conf = RhodeCodeUi() setattr(ui_conf, 'ui_section', section) setattr(ui_conf, 'ui_key', key) setattr(ui_conf, 'ui_value', value) self.sa.add(ui_conf) # rhodecode app settings settings = [ ('realm', 'RhodeCode', 'unicode'), ('title', '', 'unicode'), ('pre_code', '', 'unicode'), ('post_code', '', 'unicode'), ('show_public_icon', True, 'bool'), ('show_private_icon', True, 'bool'), ('stylify_metatags', False, 'bool'), ('dashboard_items', 100, 'int'), ('admin_grid_items', 25, 'int'), ('show_version', True, 'bool'), ('use_gravatar', False, 'bool'), ('gravatar_url', User.DEFAULT_GRAVATAR_URL, 'unicode'), ('clone_uri_tmpl', Repository.DEFAULT_CLONE_URI, 'unicode'), ('support_url', '', 'unicode'), ('update_url', RhodeCodeSetting.DEFAULT_UPDATE_URL, 'unicode'), ('show_revision_number', True, 'bool'), ('show_sha_length', 12, 'int'), ] for key, val, type_ in settings: sett = RhodeCodeSetting(key, val, type_) self.sa.add(sett) self.create_auth_plugin_options() self.create_default_options() log.info('created ui config')
def create_ldap_options(self, skip_existing=False): """Creates ldap settings""" for k, v in [('ldap_active', 'false'), ('ldap_host', ''), ('ldap_port', '389'), ('ldap_tls_kind', 'PLAIN'), ('ldap_tls_reqcert', ''), ('ldap_dn_user', ''), ('ldap_dn_pass', ''), ('ldap_base_dn', ''), ('ldap_filter', ''), ('ldap_search_scope', ''), ('ldap_attr_login', ''), ('ldap_attr_firstname', ''), ('ldap_attr_lastname', ''), ('ldap_attr_email', '')]: if skip_existing and RhodeCodeSetting.get_by_name(k) != None: log.debug('Skipping option %s' % k) continue setting = RhodeCodeSetting(k, v) self.sa.add(setting)
def create_default_options(self, skip_existing=False): """Creates default settings""" for k, v, t in [ ('default_repo_enable_locking', False, 'bool'), ('default_repo_enable_downloads', False, 'bool'), ('default_repo_enable_statistics', False, 'bool'), ('default_repo_private', False, 'bool'), ('default_repo_type', 'hg', 'unicode')]: if (skip_existing and SettingsModel().get_setting_by_name(k) is not None): log.debug('Skipping option %s' % k) continue setting = RhodeCodeSetting(k, v, t) self.sa.add(setting)
def ldap_settings(self): """POST ldap create and store ldap settings""" _form = LdapSettingsForm([x[0] for x in self.tls_reqcert_choices], [x[0] for x in self.search_scope_choices], [x[0] for x in self.tls_kind_choices])() # check the ldap lib ldap_active = False try: import ldap ldap_active = True except ImportError: pass try: form_result = _form.to_python(dict(request.POST)) try: for k, v in form_result.items(): if k.startswith('ldap_'): if k == 'ldap_active': v = v if ldap_active else False setting = RhodeCodeSetting.get_by_name(k) setting.app_settings_value = v Session().add(setting) Session().commit() h.flash(_('LDAP settings updated successfully'), category='success') if not ldap_active: #if ldap is missing send an info to user h.flash(_('Unable to activate ldap. The "python-ldap" ' 'library is missing.'), category='warning') except (DatabaseError,): raise except formencode.Invalid, errors: e = errors.error_dict or {} return htmlfill.render( render('admin/ldap/ldap.html'), defaults=errors.value, errors=e, prefix_error=False, encoding="UTF-8")
def test_ga_code_inactive(self): self.log_user() old_title = 'RhodeCode' old_realm = 'RhodeCode authentication' new_ga_code = '' response = self.app.post(url('admin_setting', setting_id='global'), params=dict(_method='put', rhodecode_title=old_title, rhodecode_realm=old_realm, rhodecode_ga_code=new_ga_code)) self.checkSessionFlash(response, 'Updated application settings') self.assertEqual( RhodeCodeSetting.get_app_settings()['rhodecode_ga_code'], new_ga_code) response = response.follow() response.mustcontain( no=["_gaq.push(['_setAccount', '%s']);" % new_ga_code])
def create_repository(self): """GET /_admin/create_repository: Form to create a new item""" c.repo_groups = RepoGroup.groups_choices(check_perms=True) c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups) choices, c.landing_revs = ScmModel().get_repo_landing_revs() new_repo = request.GET.get('repo', '') c.new_repo = repo_name_slug(new_repo) ## apply the defaults from defaults page defaults = RhodeCodeSetting.get_default_repo_settings(strip_prefix=True) return htmlfill.render( render('admin/repos/repo_add_create_repository.html'), defaults=defaults, errors={}, prefix_error=False, encoding="UTF-8" )
def test_ga_code_inactive(self): self.log_user() old_title = 'RhodeCode' old_realm = 'RhodeCode authentication' new_ga_code = '' response = self.app.post(url('admin_setting', setting_id='global'), params=dict(_method='put', rhodecode_title=old_title, rhodecode_realm=old_realm, rhodecode_ga_code=new_ga_code)) self.assertTrue( 'Updated application settings' in response.session['flash'][0][1]) self.assertEqual( RhodeCodeSetting.get_app_settings()['rhodecode_ga_code'], new_ga_code) response = response.follow() self.assertTrue("""_gaq.push(['_setAccount', '%s']);""" % new_ga_code not in response.body)
def test_title_change(self): self.log_user() old_title = 'RhodeCode' new_title = old_title + '_changed' old_realm = 'RhodeCode authentication' for new_title in ['Changed', 'Żółwik', old_title]: response = self.app.post(url('admin_setting', setting_id='global'), params=dict(_method='put', rhodecode_title=new_title, rhodecode_realm=old_realm, rhodecode_ga_code='')) self.checkSessionFlash(response, 'Updated application settings') self.assertEqual( RhodeCodeSetting.get_app_settings()['rhodecode_title'], new_title.decode('utf-8')) response = response.follow() response.mustcontain("""<h1><a href="/">%s</a></h1>""" % new_title)
def step_6(self): notify('re-checking permissions') self.klass.create_permissions() notify('installing new UI options') sett4 = RhodeCodeSetting('show_public_icon', True) Session().add(sett4) sett5 = RhodeCodeSetting('show_private_icon', True) Session().add(sett5) sett6 = RhodeCodeSetting('stylify_metatags', False) Session().add(sett6) notify('fixing old PULL hook') _pull = RhodeCodeUi.get_by_key('preoutgoing.pull_logger') if _pull: _pull.ui_key = RhodeCodeUi.HOOK_PULL Session().add(_pull) notify('fixing old PUSH hook') _push = RhodeCodeUi.get_by_key('pretxnchangegroup.push_logger') if _push: _push.ui_key = RhodeCodeUi.HOOK_PUSH Session().add(_push) notify('installing new pre-push hook') hooks4 = RhodeCodeUi() hooks4.ui_section = 'hooks' hooks4.ui_key = RhodeCodeUi.HOOK_PRE_PUSH hooks4.ui_value = 'python:rhodecode.lib.hooks.pre_push' Session().add(hooks4) notify('installing new pre-pull hook') hooks6 = RhodeCodeUi() hooks6.ui_section = 'hooks' hooks6.ui_key = RhodeCodeUi.HOOK_PRE_PULL hooks6.ui_value = 'python:rhodecode.lib.hooks.pre_pull' Session().add(hooks6) notify('installing hgsubversion option') # enable hgsubversion disabled by default hgsubversion = RhodeCodeUi() hgsubversion.ui_section = 'extensions' hgsubversion.ui_key = 'hgsubversion' hgsubversion.ui_value = '' hgsubversion.ui_active = False Session().add(hgsubversion) notify('installing hg git option') # enable hggit disabled by default hggit = RhodeCodeUi() hggit.ui_section = 'extensions' hggit.ui_key = 'hggit' hggit.ui_value = '' hggit.ui_active = False Session().add(hggit) notify('re-check default permissions') default_user = User.get_by_username(User.DEFAULT_USER) perm = Permission.get_by_key('hg.fork.repository') reg_perm = UserToPerm() reg_perm.user = default_user reg_perm.permission = perm Session().add(reg_perm)
def repo2db_mapper(initial_repo_list, remove_obsolete=False, install_git_hook=False): """ maps all repos given in initial_repo_list, non existing repositories are created, if remove_obsolete is True it also check for db entries that are not in initial_repo_list and removes them. :param initial_repo_list: list of repositories found by scanning methods :param remove_obsolete: check for obsolete entries in database :param install_git_hook: if this is True, also check and install githook for a repo if missing """ from rhodecode.model.repo import RepoModel from rhodecode.model.scm import ScmModel sa = meta.Session() rm = RepoModel() user = User.get_first_admin() added = [] ##creation defaults defs = RhodeCodeSetting.get_default_repo_settings(strip_prefix=True) enable_statistics = defs.get('repo_enable_statistics') enable_locking = defs.get('repo_enable_locking') enable_downloads = defs.get('repo_enable_downloads') private = defs.get('repo_private') for name, repo in initial_repo_list.items(): group = map_groups(name) db_repo = rm.get_by_repo_name(name) # found repo that is on filesystem not in RhodeCode database if not db_repo: log.info('repository %s not found, creating now' % name) added.append(name) desc = (repo.description if repo.description != 'unknown' else '%s repository' % name) new_repo = rm.create_repo(repo_name=name, repo_type=repo.alias, description=desc, repos_group=getattr( group, 'group_id', None), owner=user, just_db=True, enable_locking=enable_locking, enable_downloads=enable_downloads, enable_statistics=enable_statistics, private=private) # we added that repo just now, and make sure it has githook # installed if new_repo.repo_type == 'git': ScmModel().install_git_hook(new_repo.scm_instance) new_repo.update_changeset_cache() elif install_git_hook: if db_repo.repo_type == 'git': ScmModel().install_git_hook(db_repo.scm_instance) sa.commit() removed = [] if remove_obsolete: # remove from database those repositories that are not in the filesystem for repo in sa.query(Repository).all(): if repo.repo_name not in initial_repo_list.keys(): log.debug("Removing non-existing repository found in db `%s`" % repo.repo_name) try: removed.append(repo.repo_name) RepoModel(sa).delete(repo, forks='detach', fs_remove=False) sa.commit() except Exception: #don't hold further removals on error log.error(traceback.format_exc()) sa.rollback() return added, removed
def update(self, setting_id): """PUT /admin/settings/setting_id: Update an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="PUT" /> # Or using helpers: # h.form(url('admin_setting', setting_id=ID), # method='put') # url('admin_setting', setting_id=ID) if setting_id == 'mapping': rm_obsolete = request.POST.get('destroy', False) log.debug('Rescanning directories with destroy=%s' % rm_obsolete) initial = ScmModel().repo_scan() log.debug('invalidating all repositories') for repo_name in initial.keys(): invalidate_cache('get_repo_cached_%s' % repo_name) added, removed = repo2db_mapper(initial, rm_obsolete) _repr = lambda l: ', '.join(map(safe_unicode, l)) or '-' h.flash(_('Repositories successfully ' 'rescanned added: %s ; removed: %s') % (_repr(added), _repr(removed)), category='success') if setting_id == 'whoosh': repo_location = self._get_hg_ui_settings()['paths_root_path'] full_index = request.POST.get('full_index', False) run_task(tasks.whoosh_index, repo_location, full_index) h.flash(_('Whoosh reindex task scheduled'), category='success') if setting_id == 'global': application_form = ApplicationSettingsForm()() try: form_result = application_form.to_python(dict(request.POST)) except formencode.Invalid, errors: return htmlfill.render(render('admin/settings/settings.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8") try: sett1 = RhodeCodeSetting.get_by_name_or_create('title') sett1.app_settings_value = form_result['rhodecode_title'] Session().add(sett1) sett2 = RhodeCodeSetting.get_by_name_or_create('realm') sett2.app_settings_value = form_result['rhodecode_realm'] Session().add(sett2) sett3 = RhodeCodeSetting.get_by_name_or_create('ga_code') sett3.app_settings_value = form_result['rhodecode_ga_code'] Session().add(sett3) Session().commit() set_rhodecode_config(config) h.flash(_('Updated application settings'), category='success') except Exception: log.error(traceback.format_exc()) h.flash(_('Error occurred during updating ' 'application settings'), category='error')
def repo2db_mapper(initial_repo_list, remove_obsolete=False, install_git_hook=False): """ maps all repos given in initial_repo_list, non existing repositories are created, if remove_obsolete is True it also check for db entries that are not in initial_repo_list and removes them. :param initial_repo_list: list of repositories found by scanning methods :param remove_obsolete: check for obsolete entries in database :param install_git_hook: if this is True, also check and install githook for a repo if missing """ from rhodecode.model.repo import RepoModel from rhodecode.model.scm import ScmModel sa = meta.Session() rm = RepoModel() user = sa.query(User).filter(User.admin == True).first() if user is None: raise Exception('Missing administrative account!') added = [] ##creation defaults defs = RhodeCodeSetting.get_default_repo_settings(strip_prefix=True) enable_statistics = defs.get('repo_enable_statistics') enable_locking = defs.get('repo_enable_locking') enable_downloads = defs.get('repo_enable_downloads') private = defs.get('repo_private') for name, repo in initial_repo_list.items(): group = map_groups(name) db_repo = rm.get_by_repo_name(name) # found repo that is on filesystem not in RhodeCode database if not db_repo: log.info('repository %s not found, creating now' % name) added.append(name) desc = (repo.description if repo.description != 'unknown' else '%s repository' % name) new_repo = rm.create_repo( repo_name=name, repo_type=repo.alias, description=desc, repos_group=getattr(group, 'group_id', None), owner=user, just_db=True, enable_locking=enable_locking, enable_downloads=enable_downloads, enable_statistics=enable_statistics, private=private ) # we added that repo just now, and make sure it has githook # installed if new_repo.repo_type == 'git': ScmModel().install_git_hook(new_repo.scm_instance) new_repo.update_changeset_cache() elif install_git_hook: if db_repo.repo_type == 'git': ScmModel().install_git_hook(db_repo.scm_instance) # during starting install all cache keys for all repositories in the # system, this will register all repos and multiple instances cache_key = CacheInvalidation._get_cache_key(name) log.debug("Creating invalidation cache key for %s: %s", name, cache_key) CacheInvalidation.invalidate(name) sa.commit() removed = [] if remove_obsolete: # remove from database those repositories that are not in the filesystem for repo in sa.query(Repository).all(): if repo.repo_name not in initial_repo_list.keys(): log.debug("Removing non-existing repository found in db `%s`" % repo.repo_name) try: sa.delete(repo) sa.commit() removed.append(repo.repo_name) except Exception: #don't hold further removals on error log.error(traceback.format_exc()) sa.rollback() return added, removed
class SettingsController(BaseController): """REST Controller styled on the Atom Publishing Protocol""" # To properly map this controller, ensure your config/routing.py # file has a resource setup: # map.resource('setting', 'settings', controller='admin/settings', # path_prefix='/admin', name_prefix='admin_') @LoginRequired() def __before__(self): c.admin_user = session.get('admin_user') c.admin_username = session.get('admin_username') c.modules = sorted([(p.project_name, p.version) for p in pkg_resources.working_set] + [('git', check_git_version())], key=lambda k: k[0].lower()) c.py_version = platform.python_version() c.platform = platform.platform() super(SettingsController, self).__before__() @HasPermissionAllDecorator('hg.admin') def index(self, format='html'): """GET /admin/settings: All items in the collection""" # url('admin_settings') defaults = RhodeCodeSetting.get_app_settings() defaults.update(self._get_hg_ui_settings()) return htmlfill.render(render('admin/settings/settings.html'), defaults=defaults, encoding="UTF-8", force_defaults=False) @HasPermissionAllDecorator('hg.admin') def create(self): """POST /admin/settings: Create a new item""" # url('admin_settings') @HasPermissionAllDecorator('hg.admin') def new(self, format='html'): """GET /admin/settings/new: Form to create a new item""" # url('admin_new_setting') @HasPermissionAllDecorator('hg.admin') def update(self, setting_id): """PUT /admin/settings/setting_id: Update an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="PUT" /> # Or using helpers: # h.form(url('admin_setting', setting_id=ID), # method='put') # url('admin_setting', setting_id=ID) if setting_id == 'mapping': rm_obsolete = request.POST.get('destroy', False) log.debug('Rescanning directories with destroy=%s' % rm_obsolete) initial = ScmModel().repo_scan() log.debug('invalidating all repositories') for repo_name in initial.keys(): invalidate_cache('get_repo_cached_%s' % repo_name) added, removed = repo2db_mapper(initial, rm_obsolete) _repr = lambda l: ', '.join(map(safe_unicode, l)) or '-' h.flash(_('Repositories successfully ' 'rescanned added: %s ; removed: %s') % (_repr(added), _repr(removed)), category='success') if setting_id == 'whoosh': repo_location = self._get_hg_ui_settings()['paths_root_path'] full_index = request.POST.get('full_index', False) run_task(tasks.whoosh_index, repo_location, full_index) h.flash(_('Whoosh reindex task scheduled'), category='success') if setting_id == 'global': application_form = ApplicationSettingsForm()() try: form_result = application_form.to_python(dict(request.POST)) except formencode.Invalid, errors: return htmlfill.render(render('admin/settings/settings.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8") try: sett1 = RhodeCodeSetting.get_by_name_or_create('title') sett1.app_settings_value = form_result['rhodecode_title'] Session().add(sett1) sett2 = RhodeCodeSetting.get_by_name_or_create('realm') sett2.app_settings_value = form_result['rhodecode_realm'] Session().add(sett2) sett3 = RhodeCodeSetting.get_by_name_or_create('ga_code') sett3.app_settings_value = form_result['rhodecode_ga_code'] Session().add(sett3) Session().commit() set_rhodecode_config(config) h.flash(_('Updated application settings'), category='success') except Exception: log.error(traceback.format_exc()) h.flash(_('Error occurred during updating ' 'application settings'), category='error') if setting_id == 'visual': application_form = ApplicationVisualisationForm()() try: form_result = application_form.to_python(dict(request.POST)) except formencode.Invalid, errors: return htmlfill.render(render('admin/settings/settings.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8") try: sett1 = RhodeCodeSetting.get_by_name_or_create( 'show_public_icon') sett1.app_settings_value = \ form_result['rhodecode_show_public_icon'] Session().add(sett1) sett2 = RhodeCodeSetting.get_by_name_or_create( 'show_private_icon') sett2.app_settings_value = \ form_result['rhodecode_show_private_icon'] Session().add(sett2) sett3 = RhodeCodeSetting.get_by_name_or_create( 'stylify_metatags') sett3.app_settings_value = \ form_result['rhodecode_stylify_metatags'] Session().add(sett3) sett4 = RhodeCodeSetting.get_by_name_or_create( 'lightweight_dashboard') sett4.app_settings_value = \ form_result['rhodecode_lightweight_dashboard'] Session().add(sett4) sett4 = RhodeCodeSetting.get_by_name_or_create( 'repository_fields') sett4.app_settings_value = \ form_result['rhodecode_repository_fields'] Session().add(sett4) Session().commit() set_rhodecode_config(config) h.flash(_('Updated visualisation settings'), category='success') except Exception: log.error(traceback.format_exc()) h.flash(_('Error occurred during updating ' 'visualisation settings'), category='error')
def update(self, setting_id): """PUT /admin/settings/setting_id: Update an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="PUT" /> # Or using helpers: # h.form(url('admin_setting', setting_id=ID), # method='put') # url('admin_setting', setting_id=ID) if setting_id == 'mapping': rm_obsolete = request.POST.get('destroy', False) log.debug('Rescanning directories with destroy=%s' % rm_obsolete) initial = ScmModel().repo_scan() log.debug('invalidating all repositories') for repo_name in initial.keys(): invalidate_cache('get_repo_cached_%s' % repo_name) added, removed = repo2db_mapper(initial, rm_obsolete) h.flash(_('Repositories successfully' ' rescanned added: %s,removed: %s') % (added, removed), category='success') if setting_id == 'whoosh': repo_location = self.get_hg_ui_settings()['paths_root_path'] full_index = request.POST.get('full_index', False) run_task(tasks.whoosh_index, repo_location, full_index) h.flash(_('Whoosh reindex task scheduled'), category='success') if setting_id == 'global': application_form = ApplicationSettingsForm()() try: form_result = application_form.to_python(dict(request.POST)) try: hgsettings1 = RhodeCodeSetting.get_by_name('title') hgsettings1.app_settings_value = \ form_result['rhodecode_title'] hgsettings2 = RhodeCodeSetting.get_by_name('realm') hgsettings2.app_settings_value = \ form_result['rhodecode_realm'] hgsettings3 = RhodeCodeSetting.get_by_name('ga_code') hgsettings3.app_settings_value = \ form_result['rhodecode_ga_code'] self.sa.add(hgsettings1) self.sa.add(hgsettings2) self.sa.add(hgsettings3) self.sa.commit() set_rhodecode_config(config) h.flash(_('Updated application settings'), category='success') except Exception: log.error(traceback.format_exc()) h.flash(_('error occurred during updating ' 'application settings'), category='error') self.sa.rollback() except formencode.Invalid, errors: return htmlfill.render( render('admin/settings/settings.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8")
def authenticate(username, password): """ Authentication function used for access control, firstly checks for db authentication then if ldap is enabled for ldap authentication, also creates ldap user if not in database :param username: username :param password: password """ user_model = UserModel() user = User.get_by_username(username) log.debug('Authenticating user using RhodeCode account') if user is not None and not user.ldap_dn: if user.active: if user.username == 'default' and user.active: log.info('user %s authenticated correctly as anonymous user' % username) return True elif user.username == username and check_password(password, user.password): log.info('user %s authenticated correctly' % username) return True else: log.warning('user %s tried auth but is disabled' % username) else: log.debug('Regular authentication failed') user_obj = User.get_by_username(username, case_insensitive=True) if user_obj is not None and not user_obj.ldap_dn: log.debug('this user already exists as non ldap') return False ldap_settings = RhodeCodeSetting.get_ldap_settings() #====================================================================== # FALLBACK TO LDAP AUTH IF ENABLE #====================================================================== if str2bool(ldap_settings.get('ldap_active')): log.debug("Authenticating user using ldap") kwargs = { 'server': ldap_settings.get('ldap_host', ''), 'base_dn': ldap_settings.get('ldap_base_dn', ''), 'port': ldap_settings.get('ldap_port'), 'bind_dn': ldap_settings.get('ldap_dn_user'), 'bind_pass': ldap_settings.get('ldap_dn_pass'), 'tls_kind': ldap_settings.get('ldap_tls_kind'), 'tls_reqcert': ldap_settings.get('ldap_tls_reqcert'), 'ldap_filter': ldap_settings.get('ldap_filter'), 'search_scope': ldap_settings.get('ldap_search_scope'), 'attr_login': ldap_settings.get('ldap_attr_login'), 'ldap_version': 3, } log.debug('Checking for ldap authentication') try: aldap = AuthLdap(**kwargs) (user_dn, ldap_attrs) = aldap.authenticate_ldap(username, password) log.debug('Got ldap DN response %s' % user_dn) get_ldap_attr = lambda k: ldap_attrs.get(ldap_settings\ .get(k), [''])[0] user_attrs = { 'name': safe_unicode(get_ldap_attr('ldap_attr_firstname')), 'lastname': safe_unicode(get_ldap_attr('ldap_attr_lastname')), 'email': get_ldap_attr('ldap_attr_email'), 'active': 'hg.extern_activate.auto' in User.get_default_user()\ .AuthUser.permissions['global'] } # don't store LDAP password since we don't need it. Override # with some random generated password _password = PasswordGenerator().gen_password(length=8) # create this user on the fly if it doesn't exist in rhodecode # database if user_model.create_ldap(username, _password, user_dn, user_attrs): log.info('created new ldap user %s' % username) Session().commit() return True except (LdapUsernameError, LdapPasswordError, LdapImportError): pass except (Exception,): log.error(traceback.format_exc()) pass return False
def create_repo(self, apiuser, repo_name, owner=Optional(OAttr('apiuser')), repo_type=Optional('hg'), description=Optional(''), private=Optional(False), clone_uri=Optional(None), landing_rev=Optional('tip'), enable_statistics=Optional(False), enable_locking=Optional(False), enable_downloads=Optional(False)): """ Create repository, if clone_url is given it makes a remote clone if repo_name is within a group name the groups will be created automatically if they aren't present :param apiuser: :param repo_name: :param onwer: :param repo_type: :param description: :param private: :param clone_uri: :param landing_rev: """ if HasPermissionAnyApi('hg.admin')(user=apiuser) is False: if not isinstance(owner, Optional): #forbid setting owner for non-admins raise JSONRPCError( 'Only RhodeCode admin can specify `owner` param' ) if isinstance(owner, Optional): owner = apiuser.user_id owner = get_user_or_error(owner) if RepoModel().get_by_repo_name(repo_name): raise JSONRPCError("repo `%s` already exist" % repo_name) defs = RhodeCodeSetting.get_default_repo_settings(strip_prefix=True) if isinstance(private, Optional): private = defs.get('repo_private') or Optional.extract(private) if isinstance(repo_type, Optional): repo_type = defs.get('repo_type') if isinstance(enable_statistics, Optional): enable_statistics = defs.get('repo_enable_statistics') if isinstance(enable_locking, Optional): enable_locking = defs.get('repo_enable_locking') if isinstance(enable_downloads, Optional): enable_downloads = defs.get('repo_enable_downloads') clone_uri = Optional.extract(clone_uri) description = Optional.extract(description) landing_rev = Optional.extract(landing_rev) try: # create structure of groups and return the last group group = map_groups(repo_name) repo = RepoModel().create_repo( repo_name=repo_name, repo_type=repo_type, description=description, owner=owner, private=private, clone_uri=clone_uri, repos_group=group, landing_rev=landing_rev, enable_statistics=enable_statistics, enable_downloads=enable_downloads, enable_locking=enable_locking ) Session().commit() return dict( msg="Created new repository `%s`" % (repo.repo_name), repo=repo.get_api_data() ) except Exception: log.error(traceback.format_exc()) raise JSONRPCError('failed to create repository `%s`' % repo_name)
def update(self, setting_id): """PUT /admin/settings/setting_id: Update an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="PUT" /> # Or using helpers: # h.form(url('admin_setting', setting_id=ID), # method='put') # url('admin_setting', setting_id=ID) if setting_id == 'mapping': rm_obsolete = request.POST.get('destroy', False) invalidate_cache = request.POST.get('invalidate', False) log.debug('rescanning repo location with destroy obsolete=%s' % (rm_obsolete,)) if invalidate_cache: log.debug('invalidating all repositories cache') for repo in Repository.get_all(): ScmModel().mark_for_invalidation(repo.repo_name) filesystem_repos = ScmModel().repo_scan() added, removed = repo2db_mapper(filesystem_repos, rm_obsolete) _repr = lambda l: ', '.join(map(safe_unicode, l)) or '-' h.flash(_('Repositories successfully ' 'rescanned added: %s ; removed: %s') % (_repr(added), _repr(removed)), category='success') if setting_id == 'whoosh': repo_location = self._get_hg_ui_settings()['paths_root_path'] full_index = request.POST.get('full_index', False) run_task(tasks.whoosh_index, repo_location, full_index) h.flash(_('Whoosh reindex task scheduled'), category='success') if setting_id == 'global': application_form = ApplicationSettingsForm()() try: form_result = application_form.to_python(dict(request.POST)) except formencode.Invalid, errors: return htmlfill.render( render('admin/settings/settings.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8" ) try: sett1 = RhodeCodeSetting.get_by_name_or_create('title') sett1.app_settings_value = form_result['rhodecode_title'] Session().add(sett1) sett2 = RhodeCodeSetting.get_by_name_or_create('realm') sett2.app_settings_value = form_result['rhodecode_realm'] Session().add(sett2) sett3 = RhodeCodeSetting.get_by_name_or_create('ga_code') sett3.app_settings_value = form_result['rhodecode_ga_code'] Session().add(sett3) Session().commit() set_rhodecode_config(config) h.flash(_('Updated application settings'), category='success') except Exception: log.error(traceback.format_exc()) h.flash(_('Error occurred during updating ' 'application settings'), category='error')
def authenticate(username, password): """ Authentication function used for access control, firstly checks for db authentication then if ldap is enabled for ldap authentication, also creates ldap user if not in database :param username: username :param password: password """ user_model = UserModel() user = User.get_by_username(username) log.debug('Authenticating user using RhodeCode account') if user is not None and not user.ldap_dn: if user.active: if user.username == 'default' and user.active: log.info('user %s authenticated correctly as anonymous user' % username) return True elif user.username == username and check_password( password, user.password): log.info('user %s authenticated correctly' % username) return True else: log.warning('user %s tried auth but is disabled' % username) else: log.debug('Regular authentication failed') user_obj = User.get_by_username(username, case_insensitive=True) if user_obj is not None and not user_obj.ldap_dn: log.debug('this user already exists as non ldap') return False ldap_settings = RhodeCodeSetting.get_ldap_settings() #====================================================================== # FALLBACK TO LDAP AUTH IF ENABLE #====================================================================== if str2bool(ldap_settings.get('ldap_active')): log.debug("Authenticating user using ldap") kwargs = { 'server': ldap_settings.get('ldap_host', ''), 'base_dn': ldap_settings.get('ldap_base_dn', ''), 'port': ldap_settings.get('ldap_port'), 'bind_dn': ldap_settings.get('ldap_dn_user'), 'bind_pass': ldap_settings.get('ldap_dn_pass'), 'tls_kind': ldap_settings.get('ldap_tls_kind'), 'tls_reqcert': ldap_settings.get('ldap_tls_reqcert'), 'ldap_filter': ldap_settings.get('ldap_filter'), 'search_scope': ldap_settings.get('ldap_search_scope'), 'attr_login': ldap_settings.get('ldap_attr_login'), 'ldap_version': 3, } log.debug('Checking for ldap authentication') try: aldap = AuthLdap(**kwargs) (user_dn, ldap_attrs) = aldap.authenticate_ldap(username, password) log.debug('Got ldap DN response %s' % user_dn) get_ldap_attr = lambda k: ldap_attrs.get(ldap_settings\ .get(k), [''])[0] user_attrs = { 'name': safe_unicode(get_ldap_attr('ldap_attr_firstname')), 'lastname': safe_unicode(get_ldap_attr('ldap_attr_lastname')), 'email': get_ldap_attr('ldap_attr_email'), 'active': 'hg.extern_activate.auto' in User.get_default_user()\ .AuthUser.permissions['global'] } # don't store LDAP password since we don't need it. Override # with some random generated password _password = PasswordGenerator().gen_password(length=8) # create this user on the fly if it doesn't exist in rhodecode # database if user_model.create_ldap(username, _password, user_dn, user_attrs): log.info('created new ldap user %s' % username) Session().commit() return True except (LdapUsernameError, LdapPasswordError, LdapImportError): pass except (Exception, ): log.error(traceback.format_exc()) pass return False