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])() try: form_result = _form.to_python(dict(request.POST)) try: for k, v in form_result.items(): if k.startswith('ldap_'): setting = RhodeCodeSettings.get_by_name(k) setting.app_settings_value = v self.sa.add(setting) self.sa.commit() h.flash(_('Ldap settings updated successfully'), category='success') except (DatabaseError,): raise except LdapImportError: h.flash(_('Unable to activate ldap. The "python-ldap" library ' 'is missing.'), category='warning') 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_ldap_save_settings(self): self.log_user() 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 = RhodeCodeSettings.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 set_rhodecode_config(config): """Updates pylons config with new settings from database :param config: """ hgsettings = RhodeCodeSettings.get_app_settings() for k, v in hgsettings.items(): config[k] = v
def index(self): defaults = RhodeCodeSettings.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 = RhodeCodeSettings.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_ldap_options(self,skip_existing=False): """Creates ldap settings""" try: 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 RhodeCodeSettings.get_by_name(k) != None: log.debug('Skipping option %s' % k) continue setting = RhodeCodeSettings(k, v) self.sa.add(setting) self.sa.commit() except: self.sa.rollback() raise
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 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 = RhodeCodeSettings.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'), } if user_model.create_ldap(username, password, user_dn, user_attrs): log.info('created new ldap user %s', username) return True except (LdapUsernameError, LdapPasswordError,): pass except (Exception,): log.error(traceback.format_exc()) pass return False
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_model.get_by_username(username, cache=False) 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 is disabled", username) else: log.debug("Regular authentication failed") user_obj = user_model.get_by_username(username, cache=False, 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 = RhodeCodeSettings.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"), } if user_model.create_ldap(username, password, user_dn, user_attrs): log.info("created new ldap user %s", username) return True except (LdapUsernameError, LdapPasswordError): pass except (Exception,): log.error(traceback.format_exc()) pass return False
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 = RhodeCodeSettings.get_by_name('title') hgsettings1.app_settings_value = \ form_result['rhodecode_title'] hgsettings2 = RhodeCodeSettings.get_by_name('realm') hgsettings2.app_settings_value = \ form_result['rhodecode_realm'] hgsettings3 = RhodeCodeSettings.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")