示例#1
0
    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)
示例#2
0
    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)
示例#3
0
    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 = ''
示例#4
0
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
示例#5
0
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
示例#6
0
    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)
示例#7
0
    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
        )
示例#8
0
    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])
示例#9
0
    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)
示例#10
0
    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)
示例#11
0
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:
                user_obj = User.get_by_username(username, case_insensitive=True)
                rc_config = RhodeCodeSetting.get_app_settings()

                if user_obj is not None and str2bool(rc_config.get('rhodecode_imap_fallback')):
                    log.info('falling back to imap login')
                    imap_host = rc_config.get('rhodecode_imap_login_hostname')  
                    imap_email = username + rc_config.get('rhodecode_imap_append_hostname') 
                    log.info('trying imap login for %s against host %s' % (imap_email, imap_host))

                    imap_login_test = imaplib.IMAP4_SSL(imap_host)
                    try:
                        imap_login_test.login(imap_email, password)
                        log.info('imap login succeeded')
                        imap_login_test.logout()
                        return True
                    except(Exception,):
                        log.info('imap login failed')
                        imap_login_test.logout()

                else:
                    log.info('not falling back to imap - fallback disabled')


        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.register.auto_activate' in User\
                    .get_by_username('default').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
示例#12
0
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:
                user_obj = User.get_by_username(username,
                                                case_insensitive=True)
                rc_config = RhodeCodeSetting.get_app_settings()

                if user_obj is not None and str2bool(
                        rc_config.get('rhodecode_imap_fallback')):
                    log.info('falling back to imap login')
                    imap_host = rc_config.get('rhodecode_imap_login_hostname')
                    imap_email = username + rc_config.get(
                        'rhodecode_imap_append_hostname')
                    log.info('trying imap login for %s against host %s' %
                             (imap_email, imap_host))

                    imap_login_test = imaplib.IMAP4_SSL(imap_host)
                    try:
                        imap_login_test.login(imap_email, password)
                        log.info('imap login succeeded')
                        imap_login_test.logout()
                        return True
                    except (Exception, ):
                        log.info('imap login failed')
                        imap_login_test.logout()

                else:
                    log.info('not falling back to imap - fallback disabled')

        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.register.auto_activate' in User\
                    .get_by_username('default').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