Esempio n. 1
0
def configure_karl(config, load_zcml=True):
    # Authorization/Authentication policies
    settings = config.registry.settings
    authentication_policy = MultiAuthenticationPolicy([
        AuthTktAuthenticationPolicy(
            settings['who_secret'],
            callback=group_finder,
            cookie_name=settings['who_cookie']),
        # for b/w compat with bootstrapper
        RepozeWho1AuthenticationPolicy(callback=group_finder),
        BasicAuthenticationPolicy()])
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.set_authentication_policy(authentication_policy)

    # Static tree revisions routing
    static_rev = settings.get('static_rev')
    if not static_rev:
        static_rev = _guess_static_rev()
        settings['static_rev'] = static_rev
    config.add_static_view('/static/%s' % static_rev, 'karl.views:static',
        cache_max_age=60 * 60 * 24 * 365)
    # Add a redirecting static view to all _other_ revisions.
    def _expired_static_predicate(info, request):
        # We add a redirecting route to all static/*,
        # _except_ if it starts with the active revision segment.
        path = info['match']['path']
        return path and path[0] != static_rev
    config.add_route('expired-static', '/static/*path',
        custom_predicates=(_expired_static_predicate, ))

    config.include('bottlecap')
    config.add_renderer('.pt', ux2_metarenderer_factory)
    config.registry.registerUtility(FormishZPTMetaRenderer(), IFormishRenderer)

    if load_zcml:
        config.hook_zca()
        config.include('pyramid_zcml')
        config.load_zcml('standalone.zcml')

    # chatter uses this to display user chatter pages, because
    # there is no container for chatter to hang a view from.
    config.add_view('karl.views.chatter.finder', context=NotFound,
                    renderer="karl.views:templates/errorpage.pt")

    debug = asbool(settings.get('debug', 'false'))
    if not debug:
        config.add_view('karl.errorpage.errorpage', context=Exception,
                        renderer="karl.views:templates/errorpage.pt")

    debugtoolbar = asbool(settings.get('debugtoolbar', 'false'))
    if debugtoolbar and pyramid_debugtoolbar:
        config.include(pyramid_debugtoolbar)

    config.add_subscriber(block_webdav, NewRequest)

    if slowlog is not None:
        config.include(slowlog)

    if perfmetrics is not None:
        config.include(perfmetrics)
Esempio n. 2
0
    def __init__(self, settings):
        self.settings = settings
        ini_file = settings['instances_config']
        here = os.path.dirname(os.path.abspath(ini_file))
        config = ConfigParser.ConfigParser(dict(here=here))
        config.read(ini_file)
        instances = {}
        virtual_hosts = {}
        for section in config.sections():
            if not section.startswith('instance:'):
                continue
            name = section[9:]
            options = {}
            for option in config.options(section):
                value = config.get(section, option)
                if option.endswith('keep_history'):
                    value = asbool(value)
                options[option] = value
            instances[name] = LazyInstance(name, settings, options)
            virtual_host = options.get('virtual_host')
            if virtual_host:
                for host in virtual_host.split():
                    host = host.strip()
                    virtual_hosts[host] = name
            if asbool(options.get('root', 'false')):
                self.root_instance = name

        self.instances = instances
        self.virtual_hosts = virtual_hosts
Esempio n. 3
0
File: login.py Progetto: lslaz1/karl
    def __call__(self):
        if self.request.params.get('form.submitted', None) is not None:
            resp = self.login()
            if resp:
                # if this returned with something, we deal with it
                return resp

        # Log in user seamlessly with kerberos if enabled
        try_kerberos = self.request.GET.get('try_kerberos', None)
        if try_kerberos:
            try_kerberos = asbool(try_kerberos)
        else:
            try_kerberos = asbool(get_config_setting('kerberos', 'False'))
        if try_kerberos:
            from karl.security.kerberos_auth import get_kerberos_userid
            userid = get_kerberos_userid(self.request)
            if userid:
                return remember_login(self.context, self.request, userid, None)

            # Break infinite loop if kerberos authorization fails
            if (self.request.authorization
                    and self.request.authorization[0] == 'Negotiate'):
                try_kerberos = False

        page_title = 'Login to %s' % get_setting(self.context, 'title')
        api = TemplateAPI(self.context, self.request, page_title)

        sso_providers = []
        sso = self.settings.get('sso')
        if sso:
            # importing here rather than in global scope allows to only require
            # velruse be installed for systems using it.
            from velruse import login_url
            for name in sso.split():
                provider = self.settings.get('sso.%s.provider' % name)
                title = self.settings.get('sso.%s.title' % name)
                sso_providers.append({
                    'title': title,
                    'name': name,
                    'url': login_url(self.request, provider)
                })

        api.status_message = self.request.params.get('reason', None)
        response = render_to_response(
            'templates/login.pt',
            dict(api=api,
                 nothing='',
                 try_kerberos=try_kerberos,
                 sso_providers=sso_providers,
                 came_from=self.request.params.get('came_from', ''),
                 app_url=self.request.application_url),
            request=self.request)
        forget_headers = forget(self.request)
        response.headers.extend(forget_headers)
        return response
Esempio n. 4
0
File: login.py Progetto: lslaz1/karl
    def __call__(self):
        if self.request.params.get('form.submitted', None) is not None:
            resp = self.login()
            if resp:
                # if this returned with something, we deal with it
                return resp

        # Log in user seamlessly with kerberos if enabled
        try_kerberos = self.request.GET.get('try_kerberos', None)
        if try_kerberos:
            try_kerberos = asbool(try_kerberos)
        else:
            try_kerberos = asbool(get_config_setting('kerberos', 'False'))
        if try_kerberos:
            from karl.security.kerberos_auth import get_kerberos_userid
            userid = get_kerberos_userid(self.request)
            if userid:
                return remember_login(self.context, self.request, userid, None)

            # Break infinite loop if kerberos authorization fails
            if (self.request.authorization and
                    self.request.authorization[0] == 'Negotiate'):
                try_kerberos = False

        page_title = 'Login to %s' % get_setting(self.context, 'title')
        api = TemplateAPI(self.context, self.request, page_title)

        sso_providers = []
        sso = self.settings.get('sso')
        if sso:
            # importing here rather than in global scope allows to only require
            # velruse be installed for systems using it.
            from velruse import login_url
            for name in sso.split():
                provider = self.settings.get('sso.%s.provider' % name)
                title = self.settings.get('sso.%s.title' % name)
                sso_providers.append({'title': title, 'name': name,
                                      'url': login_url(self.request, provider)})

        api.status_message = self.request.params.get('reason', None)
        response = render_to_response(
            'templates/login.pt',
            dict(
                api=api,
                nothing='',
                try_kerberos=try_kerberos,
                sso_providers=sso_providers,
                came_from=self.request.params.get('came_from', ''),
                app_url=self.request.application_url),
            request=self.request)
        forget_headers = forget(self.request)
        response.headers.extend(forget_headers)
        return response
Esempio n. 5
0
File: admin.py Progetto: zagy/karl
    def __init__(self, context, request, page_title=None):
        super(AdminTemplateAPI, self).__init__(context, request, page_title)
        settings = request.registry.settings
        syslog_view = get_setting(context, 'syslog_view', None)
        self.syslog_view_enabled = syslog_view != None
        self.has_logs = not not get_setting(context, 'logs_view', None)
        self.redislog = asbool(settings.get('redislog', 'False'))
        statistics_folder = get_setting(context, 'statistics_folder', None)
        if statistics_folder is not None and os.path.exists(statistics_folder):
            csv_files = [
                fn for fn in os.listdir(statistics_folder)
                if fn.endswith('.csv')
            ]
            self.statistics_view_enabled = not not csv_files
        else:
            self.statistics_view_enabled = False

        self.quarantine_url = ('%s/po_quarantine.html' %
                               request.application_url)

        site = find_site(context)
        if 'offices' in site:
            self.offices_url = resource_url(site['offices'], request)
        else:
            self.offices_url = None

        self.has_mailin = (get_setting(context, 'zodbconn.uri.postoffice')
                           and get_setting(context, 'postoffice.queue'))
Esempio n. 6
0
File: chatter.py Progetto: zagy/karl
def finder(context, request):
    if IChatterbox.providedBy(request.context):
        userid = request.view_name
        path = request.path_info
        path = path[path.index(userid) + len(userid):]
        parts = path.split('/')
        view_name = ''
        if len(parts) > 1:
            view_name = parts[1]
        adapters = request.registry.adapters
        view_callable = adapters.lookup(
            (IViewClassifier, request.request_iface, providedBy(
                request.context)),
            IView,
            name=view_name,
            default=None)
        if view_callable is not None:
            profiles = find_profiles(request.context)
            profile = profiles.get(userid)
            if profile:
                request.chatter_user_id = userid
                response = view_callable(request.context, request)
                return response
    debug = asbool(request.registry.settings.get('debug', 'false'))
    if not debug:
        response = errorpage(context, request)
        return response
    return HTTPNotFound()
def admin_menu(context, request):
    admin_settings = {}
    site = find_site(context)
    settings = request.registry.settings
    syslog_view = get_setting(context, 'syslog_view', None)
    admin_settings['syslog_view_enabled'] = syslog_view != None
    admin_settings['has_logs'] = not not get_setting(context, 'logs_view', None)
    admin_settings['redislog'] = asbool(settings.get('redislog', 'False'))
    admin_settings['can_administer'] = has_permission('administer', site, request)
    admin_settings['can_email'] = has_permission('email', site, request)
    statistics_folder = get_setting(context, 'statistics_folder', None)
    if statistics_folder is not None and os.path.exists(statistics_folder):
        csv_files = [fn for fn in os.listdir(statistics_folder)
                    if fn.endswith('.csv')]
        admin_settings['statistics_view_enabled'] = not not csv_files
    else:
        admin_settings['statistics_view_enabled'] = False
    admin_settings['quarantine_url'] = ('%s/po_quarantine.html' %
                            request.application_url)
    site = find_site(context)
    if 'offices' in site:
        admin_settings['offices_url'] = resource_url(site['offices'], request)
    else:
        admin_settings['offices_url'] = None
    admin_settings['has_mailin'] = (
        get_setting(context, 'zodbconn.uri.postoffice') and
        get_setting(context, 'postoffice.queue'))
    return admin_settings
Esempio n. 8
0
File: panels.py Progetto: hj91/karl
def admin_menu(context, request):
    admin_settings = {}
    site = find_site(context)
    settings = request.registry.settings
    syslog_view = get_setting(context, 'syslog_view', None)
    admin_settings['syslog_view_enabled'] = syslog_view != None
    admin_settings['has_logs'] = not not get_setting(context, 'logs_view',
                                                     None)
    admin_settings['redislog'] = asbool(settings.get('redislog', 'False'))
    admin_settings['can_administer'] = has_permission('administer', site,
                                                      request)
    admin_settings['can_email'] = has_permission('email', site, request)
    statistics_folder = get_setting(context, 'statistics_folder', None)
    if statistics_folder is not None and os.path.exists(statistics_folder):
        csv_files = [
            fn for fn in os.listdir(statistics_folder) if fn.endswith('.csv')
        ]
        admin_settings['statistics_view_enabled'] = not not csv_files
    else:
        admin_settings['statistics_view_enabled'] = False
    admin_settings['quarantine_url'] = ('%s/po_quarantine.html' %
                                        request.application_url)
    site = find_site(context)
    if 'offices' in site:
        admin_settings['offices_url'] = resource_url(site['offices'], request)
    else:
        admin_settings['offices_url'] = None
    admin_settings['has_mailin'] = (
        get_setting(context, 'zodbconn.uri.postoffice')
        and get_setting(context, 'postoffice.queue'))
    return admin_settings
Esempio n. 9
0
File: chatter.py Progetto: hj91/karl
def finder(context, request):
    if IChatterbox.providedBy(request.context):
        userid = request.view_name
        path = request.path_info
        path = path[path.index(userid)+len(userid):]
        parts = path.split('/')
        view_name = ''
        if len(parts) > 1:
            view_name = parts[1]
        adapters = request.registry.adapters
        view_callable = adapters.lookup(
            (IViewClassifier, request.request_iface,
             providedBy(request.context)), IView, name=view_name,
             default=None)
        if view_callable is not None:
            profiles = find_profiles(request.context)
            profile = profiles.get(userid)
            if profile:
                request.chatter_user_id = userid
                response = view_callable(request.context, request)
                return response
    debug = asbool(request.registry.settings.get('debug', 'false'))
    if not debug:
        response = errorpage(context, request)
        return response
    return HTTPNotFound()
Esempio n. 10
0
    def __init__(self, context, request, page_title=None):
        super(AdminTemplateAPI, self).__init__(context, request, page_title)
        settings = request.registry.settings
        syslog_view = get_setting(context, 'syslog_view', None)
        self.syslog_view_enabled = syslog_view != None
        self.has_logs = not not get_setting(context, 'logs_view', None)
        self.redislog = asbool(settings.get('redislog', 'False'))
        statistics_folder = get_setting(context, 'statistics_folder', None)
        if statistics_folder is not None and os.path.exists(statistics_folder):
            csv_files = [fn for fn in os.listdir(statistics_folder)
                         if fn.endswith('.csv')]
            self.statistics_view_enabled = not not csv_files
        else:
            self.statistics_view_enabled = False

        self.quarantine_url = ('%s/po_quarantine.html' %
                               request.application_url)

        site = find_site(context)
        if 'offices' in site:
            self.offices_url = resource_url(site['offices'], request)
        else:
            self.offices_url = None

        self.has_mailin = (
            get_setting(context, 'zodbconn.uri.postoffice') and
            get_setting(context, 'postoffice.queue'))
Esempio n. 11
0
File: layout.py Progetto: hj91/karl
    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.app_url = request.application_url
        # what if context is not traversable?
        if getattr(context, '__name__', None) is not None:
            self.context_url = request.resource_url(context)
        else:
            self.context_url = request.url
        self.portlets = []
        self.settings = settings = request.registry.settings
        self.app_url = app_url = request.application_url
        if getattr(context, '__name__', '_no_name_') != '_no_name_':
            self.here_url = resource_url(context, request)
            self.site = find_site(context)
            chatter = find_chatter(context)
            self.chatter_url = resource_url(chatter, request)
        self.current_intranet = find_intranet(context)
        self.people_url = app_url + '/' + settings.get('people_path', 'people')
        self.profiles_url = app_url + '/profiles'
        self.project_name = settings.get('system_name', 'KARL')
        self.page_title = getattr(context, 'title', 'Page Title')
        self.userid = authenticated_userid(request)
        self.tinymce_height = 400
        self.tinymce_width = 560
        self.html_id_next = 0
        self.client_components = set()
        self.js_devel_mode = asbool(settings.get('js_devel_mode', 'false'))

        if self.settings:
            self.kaltura_info = dict(
                enabled =  self.settings.get(
                    'kaltura_enabled', False) in ('true', 'True'),
                partner_id = self.settings.get('kaltura_partner_id', ''),
                sub_partner_id = self.settings.get(
                    'kaltura_sub_partner_id', ''),
                admin_secret = self.settings.get('kaltura_admin_secret', ''),
                user_secret = self.settings.get('kaltura_user_secret', ''),
                kcw_uiconf_id = self.settings.get(
                    'kaltura_kcw_uiconf_id', '1000741'),
                player_uiconf_id = self.settings.get(
                    'kaltura_player_uiconf_id', ''),
                player_cache_st = self.settings.get(
                    'kaltura_player_cache_st', ''),
                local_user = self.userid,
            )
            if not self.settings.get(
                'kaltura_client_session', False) in ('true', 'True'):
                # Secrets will not be sent to client, instead session is handled on the server.
                self.kaltura_info['session_url'] = app_url + '/' + 'kaltura_create_session.json'
        else:
            self.kaltura_info = dict(
                enabled = False,
                )
Esempio n. 12
0
File: layout.py Progetto: hj91/karl
    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.app_url = request.application_url
        # what if context is not traversable?
        if getattr(context, '__name__', None) is not None:
            self.context_url = request.resource_url(context)
        else:
            self.context_url = request.url
        self.portlets = []
        self.settings = settings = request.registry.settings
        self.app_url = app_url = request.application_url
        if getattr(context, '__name__', '_no_name_') != '_no_name_':
            self.here_url = resource_url(context, request)
            self.site = find_site(context)
            chatter = find_chatter(context)
            self.chatter_url = resource_url(chatter, request)
        self.current_intranet = find_intranet(context)
        self.people_url = app_url + '/' + settings.get('people_path', 'people')
        self.profiles_url = app_url + '/profiles'
        self.project_name = settings.get('system_name', 'KARL')
        self.page_title = getattr(context, 'title', 'Page Title')
        self.userid = authenticated_userid(request)
        self.tinymce_height = 400
        self.tinymce_width = 560
        self.html_id_next = 0
        self.client_components = set()
        self.js_devel_mode = asbool(settings.get('js_devel_mode', 'false'))

        if self.settings:
            self.kaltura_info = dict(
                enabled=self.settings.get('kaltura_enabled', False)
                in ('true', 'True'),
                partner_id=self.settings.get('kaltura_partner_id', ''),
                sub_partner_id=self.settings.get('kaltura_sub_partner_id', ''),
                admin_secret=self.settings.get('kaltura_admin_secret', ''),
                user_secret=self.settings.get('kaltura_user_secret', ''),
                kcw_uiconf_id=self.settings.get('kaltura_kcw_uiconf_id',
                                                '1000741'),
                player_uiconf_id=self.settings.get('kaltura_player_uiconf_id',
                                                   ''),
                player_cache_st=self.settings.get('kaltura_player_cache_st',
                                                  ''),
                local_user=self.userid,
            )
            if not self.settings.get('kaltura_client_session',
                                     False) in ('true', 'True'):
                # Secrets will not be sent to client, instead session is handled on the server.
                self.kaltura_info[
                    'session_url'] = app_url + '/' + 'kaltura_create_session.json'
        else:
            self.kaltura_info = dict(enabled=False, )
Esempio n. 13
0
File: login.py Progetto: zagy/karl
def logout_view(context, request, reason='Logged out'):
    site = find_site(context)
    site_url = resource_url(site, request)
    query = {'reason': reason, 'came_from': site_url}
    if asbool(get_setting(context, 'kerberos', 'False')):
        # If user explicitly logs out, don't try to log back in immediately
        # using kerberos.
        query['try_kerberos'] = 'False'
    login_url = resource_url(site, request, 'login.html', query=query)

    redirect = HTTPFound(location=login_url)
    redirect.headers.extend(forget(request))
    return redirect
Esempio n. 14
0
File: login.py Progetto: hj91/karl
def logout_view(context, request, reason='Logged out'):
    site = find_site(context)
    site_url = resource_url(site, request)
    query = {'reason': reason, 'came_from': site_url}
    if asbool(get_setting(context, 'kerberos', 'False')):
        # If user explicitly logs out, don't try to log back in immediately
        # using kerberos.
        query['try_kerberos'] = 'False'
    login_url = resource_url(site, request, 'login.html', query=query)

    redirect = HTTPFound(location=login_url)
    redirect.headers.extend(forget(request))
    return redirect
Esempio n. 15
0
    def __init__(self, name, global_config, options):
        self.name = name

        self.config = config = global_config.copy()
        for setting, value in config.items():
            if setting.endswith('blob_cache'):
                config[setting] = os.path.join(value, name)
        self._make_instance_specific(config, 'var_instance')
        if asbool(config.get('redislog', 'False')):
            prefix = config.get('redislog.prefix', 'karl')
            config['redislog.prefix'] = '%s.%s' % (prefix, name)
        config.update(options)
        config['read_only'] = self.mode == 'READONLY'
Esempio n. 16
0
def make_app(global_config, **kw):
    config = global_config.copy()
    config.update(kw)

    # paster app config callback
    zodb_uri = config.get('zodb_uri')
    if zodb_uri is None:
        raise ValueError('zodb_uri must not be None')
    get_root = PersistentApplicationFinder(zodb_uri, appmaker)

    # Coerce a value out of the [app:karl] section in the INI file
    jquery_dev_mode = config.get('jquery_dev_mode', False)
    config['jquery_dev_mode'] = asbool(jquery_dev_mode)
    config['read_only'] = asbool(config.get('read_only', False))

    # Set up logging
    configure_log(**config)
    set_subsystem('karl')

    # Set up logging admin view (coerce instances to list)
    if 'logs_view' in config:
        config['logs_view'] = map(os.path.abspath, config['logs_view'].split())

    for key in ('syslog_view_instances', 'error_monitor_subsystems'):
        if key in config:
            config[key] = config[key].split()

    # Make BFG app
    pkg_name = config.get('package', None)
    if pkg_name is not None:
        __import__(pkg_name)
        package = sys.modules[pkg_name]
        app = bfg_make_app(get_root, package, options=config)
    else:
        filename = 'karl.includes:standalone.zcml'
        app = bfg_make_app(get_root, filename=filename, options=config)

    return app
Esempio n. 17
0
def make_karl_pipeline(app):
    config = app.config
    uri = app.uri
    pipeline = app
    urchin_account = config.get('urchin.account')
    if urchin_account:
        pipeline = UrchinMiddleware(pipeline, urchin_account)
    pipeline = make_who_middleware(pipeline, config)
    pipeline = make_tm(pipeline)
    pipeline = zodb_connector(pipeline, config, zodb_uri=uri)
    pipeline = Retry(pipeline, 3, retryable)
    pipeline = error_log_middleware(pipeline)
    if not asbool(config.get('debug', 'False')):
        pipeline = ErrorPageFilter(pipeline, None, 'static', '')
    return pipeline
Esempio n. 18
0
def configure_redislog(**config):
    if not asbool(config.get('redislog', 'False')):
        return None

    redisconfig = dict([(k[9:], v) for k, v in config.items()
                        if k.startswith('redislog.')])
    for intkey in ('port', 'db', 'expires'):
        if intkey in redisconfig:
            redisconfig[intkey] = int(intkey)

    debug = config.get('debug', False)
    if debug:
        level = logging.DEBUG
    else:
        level = logging.INFO
    return RedisLogHandler(redisconfig, level, config['get_current_instance'])
Esempio n. 19
0
File: admin.py Progetto: zagy/karl
def _get_redislog(registry):
    redislog = getattr(registry, 'redislog', None)
    if redislog:
        return redislog

    settings = registry.settings
    if not asbool(settings.get('redislog', 'False')):
        return

    redisconfig = dict([(k[9:], v) for k, v in settings.items()
                        if k.startswith('redislog.')])
    for intkey in ('port', 'db', 'expires'):
        if intkey in redisconfig:
            redisconfig[intkey] = int(intkey)

    from karl.redislog import RedisLog
    settings.redislog = redislog = RedisLog(**redisconfig)
    return redislog
Esempio n. 20
0
def _get_redislog(registry):
    redislog = getattr(registry, 'redislog', None)
    if redislog:
        return redislog

    settings = registry.settings
    if not asbool(settings.get('redislog', 'False')):
        return

    redisconfig = dict([(k[9:], v) for k, v in settings.items()
                        if k.startswith('redislog.')])
    for intkey in ('port', 'db', 'expires'):
        if intkey in redisconfig:
            redisconfig[intkey] = int(intkey)

    from karl.redislog import RedisLog
    settings.redislog = redislog = RedisLog(**redisconfig)
    return redislog
Esempio n. 21
0
def configure_karl(config, load_zcml=True):
    # Authorization/Authentication policies
    settings = config.registry.settings
    authentication_policy = MultiAuthenticationPolicy([
        AuthTktAuthenticationPolicy(settings['who_secret'],
                                    callback=group_finder,
                                    cookie_name=settings['who_cookie']),
        # for b/w compat with bootstrapper
        RepozeWho1AuthenticationPolicy(callback=group_finder),
        BasicAuthenticationPolicy()
    ])
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.set_authentication_policy(authentication_policy)

    # Static tree revisions routing
    static_rev = settings.get('static_rev')
    if not static_rev:
        static_rev = _guess_static_rev()
        settings['static_rev'] = static_rev
    config.add_static_view('/static/%s' % static_rev,
                           'karl.views:static',
                           cache_max_age=60 * 60 * 24 * 365)

    # Add a redirecting static view to all _other_ revisions.
    def _expired_static_predicate(info, request):
        # We add a redirecting route to all static/*,
        # _except_ if it starts with the active revision segment.
        path = info['match']['path']
        return path and path[0] != static_rev

    config.add_route('expired-static',
                     '/static/*path',
                     custom_predicates=(_expired_static_predicate, ))

    # Need a session if using Velruse
    config.set_session_factory(Session(settings['who_secret']))

    config.include('karl.security.sso')
    config.include('karl.debugload')
    config.include('karl.underprofile')

    if load_zcml:
        config.hook_zca()
        config.include('pyramid_zcml')
        config.load_zcml('standalone.zcml')

    debug = asbool(settings.get('debug', 'false'))
    if not debug:
        config.add_view('karl.errorpage.errorpage',
                        context=Exception,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage',
                        context=HTTPNotFound,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage',
                        context=NotFound,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage',
                        context=ReadOnlyError,
                        renderer="karl.views:templates/errorpage.pt")

    debugtoolbar = asbool(settings.get('debugtoolbar', 'false'))
    if debugtoolbar and pyramid_debugtoolbar:
        config.include(pyramid_debugtoolbar)

    config.add_subscriber(block_webdav, NewRequest)

    if slowlog is not None:
        config.include(slowlog)

    if perfmetrics is not None:
        config.include(perfmetrics)

    if 'intranet_search_paths' in settings:
        settings['intranet_search_paths'] = settings[
            'intranet_search_paths'].split()
    else:
        settings['intranet_search_paths'] = ('/profiles', '/offices')

    # admin5 Admin UI
    config.include('admin5')
    config.include('karl.box')
Esempio n. 22
0
def configure_karl(config, load_zcml=True):
    # Authorization/Authentication policies
    settings = config.registry.settings
    authentication_policy = AuthTktAuthenticationPolicy(
        settings.get('auth_secret', settings.get('who_secret', 'secret')),
        callback=group_finder,
        cookie_name=settings.get('auth_cookie_name',
                                 settings.get('who_cookie',
                                              'pnutbtr')),  # noqa
        timeout=int(settings.get('auth_timeout', 600)),
        reissue_time=int(settings.get('auth_reissue_time', 120)),
        max_age=int(settings.get('auth_max_age', 172800)),
        secure=settings.get('auth_secure', 'false') in (True, 'true', 'True'))
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.set_authentication_policy(authentication_policy)
    # Static tree revisions routing

    static_path, rev = add_versioned_static_resource(config, '/static',
                                                     'karl.views:static')

    # Need a session if using Velruse
    config.set_session_factory(
        Session(
            settings.get('auth_secret', settings.get('who_secret', 'secret'))))

    config.include('karl.security.sso')

    if load_zcml:
        config.hook_zca()
        config.include('pyramid_zcml')
        config.load_zcml('standalone.zcml')

    debug = asbool(settings.get('debug', 'false'))
    if not debug:
        config.add_view('karl.errorpage.errorpage',
                        context=Exception,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage',
                        context=HTTPNotFound,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage',
                        context=NotFound,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage',
                        context=ReadOnlyError,
                        renderer="karl.views:templates/errorpage.pt")

    debugtoolbar = asbool(settings.get('debugtoolbar', 'false'))
    if debugtoolbar and pyramid_debugtoolbar:
        config.include(pyramid_debugtoolbar)

    config.add_subscriber(block_webdav, NewRequest)

    if slowlog is not None:
        config.include(slowlog)

    if perfmetrics is not None:
        config.include(perfmetrics)

    if isinstance(config, Configurator):
        # define css only if config is correct instance type
        # this caused some tests to fail...
        config.define_css('karl-wikitoc', static_path + '/karl-wikitoc.css')
        config.define_css('karl-multifileupload',
                          static_path + '/karl-multifileupload.css')
        config.define_css('karl-ui',
                          static_path + '/karl-ui.css',
                          always_include=True)
        config.define_css('karl-base',
                          static_path + '/karl-base.css',
                          always_include=True)
        config.define_css('karl-theme',
                          static_path + '/karl-theme.css',
                          always_include=True)
        config.define_css('karl-ie',
                          static_path + '/karl_ie.css',
                          always_include=True,
                          ie_expression='lte IE 8')
        config.define_css('karl-ie8',
                          static_path + '/karl_ie8.css',
                          always_include=True,
                          ie_expression='IE 8')
        config.define_css('karl-ie9',
                          static_path + '/karl_ie9.css',
                          always_include=True,
                          ie_expression='gte IE 9')

        config.define_javascript('karl-ui',
                                 resource_name='karl-ui',
                                 always_include=True)
        config.define_javascript('karl-custom',
                                 resource_name='karl-custom',
                                 always_include=True)
        config.define_javascript('karl-multifileupload',
                                 resource_name='karl-multifileupload')
        config.define_javascript('karl-wikitoc', resource_name='karl-wikitoc')
        config.define_javascript('tinymce', name='tinymce')
Esempio n. 23
0
File: api.py Progetto: iotest3/new
    def __init__(self, context, request, page_title=None):
        self.settings = get_settings() or {}
        self.site = site = find_site(context)
        self.context = context
        self.request = request
        self.userid = authenticated_userid(request)
        self.app_url = app_url = request.application_url
        self.profile_url = app_url + '/profiles/%s' % self.userid
        self.here_url = self.context_url = resource_url(context, request)
        self.view_url = resource_url(context, request, request.view_name)
        self.js_devel_mode = asbool(self.settings.get('js_devel_mode', None))
        self.read_only = not is_normal_mode(request.registry)
        self.static_url = '%s/static/%s' % (
            app_url, request.registry.settings.get('static_rev'))
        self.browser_upgrade_url = request.registry.settings.get('browser_upgrade_url', '')

        # this data will be provided for the client javascript
        self.karl_client_data = {}

        # Provide a setting in the INI to fully control the entire URL
        # to the static.  This is when the proxy runs a different port
        # number, or to "pipeline" resources on a different URL path.
        full_static_path = self.settings.get('full_static_path', False)
        if full_static_path:
            if '%d' in full_static_path:
                # XXX XXX note self._start_time is needed... and not _start_time
                # XXX XXX since this was a trivial bug, there is chance that
                # XXX XXX this actually never runs! TODO testing???
                full_static_path = full_static_path % self._start_time
            self.static_url = full_static_path
        self.page_title = page_title
        self.system_name = self.settings.get('system_name', 'KARL')
        self.user_is_admin = 'group.KarlAdmin' in effective_principals(request)
        self.can_administer = has_permission('administer', site, request)
        self.can_email = has_permission('email', site, request)
        self.admin_url = resource_url(site, request, 'admin.html')
        self.site_announcement = getattr(site, 'site_announcement', '')
        date_format = get_user_date_format(context, request)
        self.karl_client_data['date_format'] = date_format
        # XXX XXX XXX This will never work from peoples formish templates
        # XXX XXX XXX (edit_profile and derivates) because, in those form
        # XXX XXX XXX controllers, the api is instantiated from __init__,
        # XXX XXX XXX where request.form is still unset!!! (From all other
        # XXX XXX XXX formcontrollers the api is instantiated from __call__,
        # XXX XXX XXX which is why this works. A chicken-and-egg problem, really.
        if hasattr(request, 'form') and getattr(request.form, 'errors', False):
            # This is a failed form submission request, specify an error message
            self.error_message = u'Please correct the indicated errors.'

        if self.settings:
            self.kaltura_info = dict(
                enabled =  self.settings.get(
                    'kaltura_enabled', False) in ('true', 'True'),
                partner_id = self.settings.get('kaltura_partner_id', ''),
                sub_partner_id = self.settings.get(
                    'kaltura_sub_partner_id', ''),
                admin_secret = self.settings.get('kaltura_admin_secret', ''),
                user_secret = self.settings.get('kaltura_user_secret', ''),
                kcw_uiconf_id = self.settings.get(
                    'kaltura_kcw_uiconf_id', '1000741'),
                player_uiconf_id = self.settings.get(
                    'kaltura_player_uiconf_id', ''),
                player_cache_st = self.settings.get(
                    'kaltura_player_cache_st', ''),
                local_user = self.userid,
            )
            if not self.settings.get(
                'kaltura_client_session', False) in ('true', 'True'):
                # Secrets will not be sent to client, instead session is handled on the server.
                self.kaltura_info['session_url'] = app_url + '/' + 'kaltura_create_session.json'
        else:
            self.kaltura_info = dict(
                enabled = False,
                )

        # propagate the head data to the client
        d = self.karl_client_data['kaltura'] = dict(self.kaltura_info)
        # remove secrets if needed
        if 'session_url' in d:
            # server side session management, do not send secrets to client
            del d['user_secret']
            del d['admin_secret']
Esempio n. 24
0
File: login.py Progetto: zagy/karl
def login_view(context, request):
    request.layout_manager.use_layout('anonymous')
    came_from = _fixup_came_from(request, request.POST.get('came_from'))

    if request.params.get('form.submitted', None) is not None:

        challenge_qs = {'came_from': came_from}
        # identify
        login = request.POST.get('login')
        password = request.POST.get('password')
        if login is None or password is None:
            return HTTPFound(location='%s/login.html'
                                        % request.application_url)
        max_age = request.POST.get('max_age')
        if max_age is not None:
            max_age = int(max_age)

        # authenticate
        userid = None
        reason = 'Bad username or password'
        users = find_users(context)
        for authenticate in (password_authenticator, impersonate_authenticator):
            userid = authenticate(users, login, password)
            if userid:
                break

        # if not successful, try again
        if not userid:
            challenge_qs['reason'] = reason
            return HTTPFound(location='%s/login.html?%s'
                             % (request.application_url,
                                urlencode(challenge_qs, doseq=True)))

        # else, remember
        return remember_login(context, request, userid, max_age, came_from)

    # Log in user seamlessly with kerberos if enabled
    try_kerberos = request.GET.get('try_kerberos', None)
    if try_kerberos:
        try_kerberos = asbool(try_kerberos)
    else:
        try_kerberos = asbool(get_setting(context, 'kerberos', 'False'))
    if try_kerberos:
        from karl.security.kerberos_auth import get_kerberos_userid
        userid = get_kerberos_userid(request)
        if userid:
            return remember_login(context, request, userid, None, came_from)

        # Break infinite loop if kerberos authorization fails
        if request.authorization and request.authorization[0] == 'Negotiate':
            try_kerberos = False

    page_title = 'Login to %s' % request.registry.settings.get('system_name', 'KARL') # Per #366377, don't say what screen
    layout = request.layout_manager.layout
    layout.page_title = page_title
    api = TemplateAPI(context, request, page_title)

    came_from = _fixup_came_from(request,
                                 request.params.get('came_from', request.url))

    api.status_message = request.params.get('reason', None)
    response = render_to_response(
        'templates/login.pt',
        dict(
            api=api,
            came_from=came_from,
            nothing='',
            try_kerberos=try_kerberos,
            app_url=request.application_url),
        request=request)
    forget_headers = forget(request)
    response.headers.extend(forget_headers)
    return response
Esempio n. 25
0
def configure_karl(config, load_zcml=True):
    # Authorization/Authentication policies
    settings = config.registry.settings
    authentication_policy = MultiAuthenticationPolicy([
        AuthTktAuthenticationPolicy(
            settings['who_secret'],
            callback=group_finder,
            cookie_name=settings['who_cookie']),
        # for b/w compat with bootstrapper
        RepozeWho1AuthenticationPolicy(callback=group_finder),
        BasicAuthenticationPolicy()])
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.set_authentication_policy(authentication_policy)

    # Static tree revisions routing
    static_rev = settings.get('static_rev')
    if not static_rev:
        static_rev = _guess_static_rev()
        settings['static_rev'] = static_rev
    config.add_static_view('/static/%s' % static_rev, 'karl.views:static',
        cache_max_age=60 * 60 * 24 * 365)
    # Add a redirecting static view to all _other_ revisions.
    def _expired_static_predicate(info, request):
        # We add a redirecting route to all static/*,
        # _except_ if it starts with the active revision segment.
        path = info['match']['path']
        return path and path[0] != static_rev
    config.add_route('expired-static', '/static/*path',
        custom_predicates=(_expired_static_predicate, ))

    # Need a session if using Velruse
    config.set_session_factory(Session(settings['who_secret']))

    config.include('karl.security.sso')
    config.include('karl.debugload')
    config.include('karl.underprofile')

    if load_zcml:
        config.hook_zca()
        config.include('pyramid_zcml')
        config.load_zcml('standalone.zcml')

    debug = asbool(settings.get('debug', 'false'))
    if not debug:
        config.add_view('karl.errorpage.errorpage', context=Exception,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage', context=HTTPNotFound,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage', context=NotFound,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage', context=ReadOnlyError,
                        renderer="karl.views:templates/errorpage.pt")

    debugtoolbar = asbool(settings.get('debugtoolbar', 'false'))
    if debugtoolbar and pyramid_debugtoolbar:
        config.include(pyramid_debugtoolbar)

    config.add_subscriber(block_webdav, NewRequest)

    if slowlog is not None:
        config.include(slowlog)

    if perfmetrics is not None:
        config.include(perfmetrics)

    if 'intranet_search_paths' in settings:
        settings['intranet_search_paths'] = settings[
            'intranet_search_paths'].split()
    else:
        settings['intranet_search_paths'] = ('/profiles', '/offices')

    # admin5 Admin UI
    config.include('admin5')
    config.include('karl.box')
Esempio n. 26
0
File: login.py Progetto: hj91/karl
def login_view(context, request):
    settings = request.registry.settings
    request.layout_manager.use_layout('anonymous')
    came_from = _fixup_came_from(request, request.POST.get('came_from'))

    if request.params.get('form.submitted', None) is not None:

        challenge_qs = {'came_from': came_from}
        # identify
        login = request.POST.get('login')
        password = request.POST.get('password')
        if login is None or password is None:
            return HTTPFound(location='%s/login.html' %
                             request.application_url)
        max_age = request.POST.get('max_age')
        if max_age is not None:
            max_age = int(max_age)

        # authenticate
        userid = None
        reason = 'Bad username or password'
        users = find_users(context)
        for authenticate in (password_authenticator,
                             impersonate_authenticator):
            userid = authenticate(users, login, password)
            if userid:
                break

        # if not successful, try again
        if not userid:
            challenge_qs['reason'] = reason
            return HTTPFound(
                location='%s/login.html?%s' %
                (request.application_url, urlencode(challenge_qs, doseq=True)))

        # else, remember
        return remember_login(context, request, userid, max_age, came_from)

    # Log in user seamlessly with kerberos if enabled
    try_kerberos = request.GET.get('try_kerberos', None)
    if try_kerberos:
        try_kerberos = asbool(try_kerberos)
    else:
        try_kerberos = asbool(get_setting(context, 'kerberos', 'False'))
    if try_kerberos:
        from karl.security.kerberos_auth import get_kerberos_userid
        userid = get_kerberos_userid(request)
        if userid:
            return remember_login(context, request, userid, None, came_from)

        # Break infinite loop if kerberos authorization fails
        if request.authorization and request.authorization[0] == 'Negotiate':
            try_kerberos = False

    page_title = 'Login to %s' % settings.get(
        'system_name', 'KARL')  # Per #366377, don't say what screen
    layout = request.layout_manager.layout
    layout.page_title = page_title
    api = TemplateAPI(context, request, page_title)

    came_from = _fixup_came_from(request,
                                 request.params.get('came_from', request.url))
    request.session['came_from'] = came_from

    sso_providers = []
    sso = settings.get('sso')
    if sso:
        # importing here rather than in global scope allows to only require
        # velruse be installed for systems using it.
        from velruse import login_url
        for name in sso.split():
            provider = settings.get('sso.%s.provider' % name)
            title = settings.get('sso.%s.title' % name)
            sso_providers.append({
                'title': title,
                'name': name,
                'url': login_url(request, provider)
            })

    api.status_message = request.params.get('reason', None)
    response = render_to_response('templates/login.pt',
                                  dict(api=api,
                                       came_from=came_from,
                                       nothing='',
                                       try_kerberos=try_kerberos,
                                       sso_providers=sso_providers,
                                       app_url=request.application_url),
                                  request=request)
    forget_headers = forget(request)
    response.headers.extend(forget_headers)
    return response
Esempio n. 27
0
def login_view(context, request):
    settings = request.registry.settings
    came_from = request.session.get('came_from', request.url)
    came_from = _fixup_came_from(request, came_from)
    request.session['came_from'] = came_from

    if request.params.get('form.submitted', None) is not None:
        # identify
        login = request.POST.get('login')
        password = request.POST.get('password')
        if login is None or password is None:
            return HTTPFound(location='%s/login.html'
                                        % request.application_url)
        max_age = request.POST.get('max_age')
        if max_age is not None:
            max_age = int(max_age)

        # authenticate
        userid = None
        reason = 'Bad username or password'
        users = find_users(context)
        for authenticate in (password_authenticator, impersonate_authenticator):
            userid = authenticate(users, login, password)
            if userid:
                break

        # if not successful, try again
        if not userid:
            redirect = request.resource_url(
                request.root, 'login.html', query={'reason': reason})
            return HTTPFound(location=redirect)

        # else, remember
        return remember_login(context, request, userid, max_age)

    # Log in user seamlessly with kerberos if enabled
    try_kerberos = request.GET.get('try_kerberos', None)
    if try_kerberos:
        try_kerberos = asbool(try_kerberos)
    else:
        try_kerberos = asbool(get_setting(context, 'kerberos', 'False'))
    if try_kerberos:
        from karl.security.kerberos_auth import get_kerberos_userid
        userid = get_kerberos_userid(request)
        if userid:
            return remember_login(context, request, userid, None)

        # Break infinite loop if kerberos authorization fails
        if request.authorization and request.authorization[0] == 'Negotiate':
            try_kerberos = False

    page_title = 'Login to %s' % settings.get('system_name', 'KARL') # Per #366377, don't say what screen
    api = TemplateAPI(context, request, page_title)

    sso_providers = []
    sso = settings.get('sso')
    if sso:
        # importing here rather than in global scope allows to only require
        # velruse be installed for systems using it.
        from velruse import login_url
        for name in sso.split():
            provider = settings.get('sso.%s.provider' % name)
            title = settings.get('sso.%s.title' % name)
            sso_providers.append({'title': title, 'name': name,
                                  'url': login_url(request, provider)})

    api.status_message = request.params.get('reason', None)
    response = render_to_response(
        'templates/login.pt',
        dict(
            api=api,
            nothing='',
            try_kerberos=try_kerberos,
            sso_providers=sso_providers,
            app_url=request.application_url),
        request=request)
    forget_headers = forget(request)
    response.headers.extend(forget_headers)
    return response
Esempio n. 28
0
File: api.py Progetto: araymund/karl
    def __init__(self, context, request, page_title=None):
        self.settings = get_settings() or {}
        self.site = site = find_site(context)
        self.context = context
        self.request = request
        self.userid = authenticated_userid(request)
        self.app_url = app_url = request.application_url
        self.profile_url = app_url + '/profiles/%s' % self.userid
        self.here_url = self.context_url = resource_url(context, request)
        self.view_url = resource_url(context, request, request.view_name)
        self.js_devel_mode = asbool(self.settings.get('js_devel_mode', None))
        self.read_only = not is_normal_mode(request.registry)
        self.static_url = '%s/static/%s' % (
            app_url, request.registry.settings.get('static_rev'))
        self.browser_upgrade_url = request.registry.settings.get('browser_upgrade_url', '')

        # this data will be provided for the client javascript
        self.karl_client_data = {}

        # Provide a setting in the INI to fully control the entire URL
        # to the static.  This is when the proxy runs a different port
        # number, or to "pipeline" resources on a different URL path.
        full_static_path = self.settings.get('full_static_path', False)
        if full_static_path:
            if '%d' in full_static_path:
                # XXX XXX note self._start_time is needed... and not _start_time
                # XXX XXX since this was a trivial bug, there is chance that
                # XXX XXX this actually never runs! TODO testing???
                full_static_path = full_static_path % self._start_time
            self.static_url = full_static_path
        self.page_title = page_title
        self.system_name = self.settings.get('system_name', 'KARL')
        self.user_is_admin = 'group.KarlAdmin' in effective_principals(request)
        self.can_administer = has_permission('administer', site, request)
        self.can_email = has_permission('email', site, request)
        self.admin_url = resource_url(site, request, 'admin.html')
        self.site_announcement = getattr(site, 'site_announcement', '')
        date_format = get_user_date_format(context, request)
        self.karl_client_data['date_format'] = date_format
        # XXX XXX XXX This will never work from peoples formish templates
        # XXX XXX XXX (edit_profile and derivates) because, in those form
        # XXX XXX XXX controllers, the api is instantiated from __init__,
        # XXX XXX XXX where request.form is still unset!!! (From all other
        # XXX XXX XXX formcontrollers the api is instantiated from __call__,
        # XXX XXX XXX which is why this works. A chicken-and-egg problem, really.
        if hasattr(request, 'form') and getattr(request.form, 'errors', False):
            # This is a failed form submission request, specify an error message
            self.error_message = u'Please correct the indicated errors.'

        if self.settings:
            self.kaltura_info = dict(
                enabled =  self.settings.get(
                    'kaltura_enabled', False) in ('true', 'True'),
                partner_id = self.settings.get('kaltura_partner_id', ''),
                sub_partner_id = self.settings.get(
                    'kaltura_sub_partner_id', ''),
                admin_secret = self.settings.get('kaltura_admin_secret', ''),
                user_secret = self.settings.get('kaltura_user_secret', ''),
                kcw_uiconf_id = self.settings.get(
                    'kaltura_kcw_uiconf_id', '1000741'),
                player_uiconf_id = self.settings.get(
                    'kaltura_player_uiconf_id', ''),
                player_cache_st = self.settings.get(
                    'kaltura_player_cache_st', ''),
                local_user = self.userid,
            )
            if not self.settings.get(
                'kaltura_client_session', False) in ('true', 'True'):
                # Secrets will not be sent to client, instead session is handled on the server.
                self.kaltura_info['session_url'] = app_url + '/' + 'kaltura_create_session.json'
        else:
            self.kaltura_info = dict(
                enabled = False,
                )

        # propagate the head data to the client
        d = self.karl_client_data['kaltura'] = dict(self.kaltura_info)
        # remove secrets if needed
        if 'session_url' in d:
            # server side session management, do not send secrets to client
            del d['user_secret']
            del d['admin_secret']
Esempio n. 29
0
def configure_karl(config, load_zcml=True):
    # Authorization/Authentication policies
    settings = config.registry.settings
    authentication_policy = MultiAuthenticationPolicy([
        AuthTktAuthenticationPolicy(settings['who_secret'],
                                    callback=group_finder,
                                    cookie_name=settings['who_cookie']),
        # for b/w compat with bootstrapper
        RepozeWho1AuthenticationPolicy(callback=group_finder),
        BasicAuthenticationPolicy()
    ])
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.set_authentication_policy(authentication_policy)

    # Static tree revisions routing
    static_rev = settings.get('static_rev')
    if not static_rev:
        static_rev = _guess_static_rev()
        settings['static_rev'] = static_rev
    config.add_static_view('/static/%s' % static_rev,
                           'karl.views:static',
                           cache_max_age=60 * 60 * 24 * 365)

    # Add a redirecting static view to all _other_ revisions.
    def _expired_static_predicate(info, request):
        # We add a redirecting route to all static/*,
        # _except_ if it starts with the active revision segment.
        path = info['match']['path']
        return path and path[0] != static_rev

    config.add_route('expired-static',
                     '/static/*path',
                     custom_predicates=(_expired_static_predicate, ))

    # Need a session if using Velruse
    config.set_session_factory(Session(settings['who_secret']))

    # Configure bottlecap layouts
    config.include('bottlecap')
    config.add_renderer('.pt', ux2_metarenderer_factory)
    config.registry.registerUtility(FormishZPTMetaRenderer(), IFormishRenderer)
    config.include('karl.security.sso')

    if load_zcml:
        config.hook_zca()
        config.include('pyramid_zcml')
        config.load_zcml('standalone.zcml')

    # chatter uses this to display user chatter pages, because
    # there is no container for chatter to hang a view from.
    config.add_view('karl.views.chatter.finder',
                    context=NotFound,
                    renderer="karl.views:templates/errorpage.pt")

    debug = asbool(settings.get('debug', 'false'))
    if not debug:
        config.add_view('karl.errorpage.errorpage',
                        context=Exception,
                        renderer="karl.views:templates/errorpage.pt")

    debugtoolbar = asbool(settings.get('debugtoolbar', 'false'))
    if debugtoolbar and pyramid_debugtoolbar:
        config.include(pyramid_debugtoolbar)

    config.add_subscriber(block_webdav, NewRequest)

    if slowlog is not None:
        config.include(slowlog)

    if perfmetrics is not None:
        config.include(perfmetrics)
Esempio n. 30
0
def configure_karl(config, load_zcml=True):
    # Authorization/Authentication policies
    settings = config.registry.settings
    authentication_policy = AuthTktAuthenticationPolicy(
        settings.get('auth_secret', settings.get('who_secret', 'secret')),
        callback=group_finder,
        cookie_name=settings.get('auth_cookie_name', settings.get('who_cookie', 'pnutbtr')),  # noqa
        timeout=int(settings.get('auth_timeout', 600)),
        reissue_time=int(settings.get('auth_reissue_time', 120)),
        max_age=int(settings.get('auth_max_age', 172800)),
        secure=settings.get('auth_secure', 'false') in (True, 'true', 'True')
    )
    config.set_authorization_policy(ACLAuthorizationPolicy())
    config.set_authentication_policy(authentication_policy)
    # Static tree revisions routing

    static_path, rev = add_versioned_static_resource(
        config, '/static', 'karl.views:static')

    # Need a session if using Velruse
    config.set_session_factory(
        Session(settings.get('auth_secret', settings.get('who_secret', 'secret'))))

    config.include('karl.security.sso')

    if load_zcml:
        config.hook_zca()
        config.include('pyramid_zcml')
        config.load_zcml('standalone.zcml')

    debug = asbool(settings.get('debug', 'false'))
    if not debug:
        config.add_view('karl.errorpage.errorpage', context=Exception,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage', context=HTTPNotFound,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage', context=NotFound,
                        renderer="karl.views:templates/errorpage.pt")
        config.add_view('karl.errorpage.errorpage', context=ReadOnlyError,
                        renderer="karl.views:templates/errorpage.pt")

    debugtoolbar = asbool(settings.get('debugtoolbar', 'false'))
    if debugtoolbar and pyramid_debugtoolbar:
        config.include(pyramid_debugtoolbar)

    config.add_subscriber(block_webdav, NewRequest)

    if slowlog is not None:
        config.include(slowlog)

    if perfmetrics is not None:
        config.include(perfmetrics)

    if isinstance(config, Configurator):
        # define css only if config is correct instance type
        # this caused some tests to fail...
        config.define_css('karl-wikitoc', static_path + '/karl-wikitoc.css')
        config.define_css('karl-multifileupload',
                          static_path + '/karl-multifileupload.css')
        config.define_css('karl-ui', static_path + '/karl-ui.css',
                          always_include=True)
        config.define_css('karl-base', static_path + '/karl-base.css',
                          always_include=True)
        config.define_css('karl-theme', static_path + '/karl-theme.css',
                          always_include=True)
        config.define_css(
            'karl-ie', static_path + '/karl_ie.css',
            always_include=True, ie_expression='lte IE 8')
        config.define_css(
            'karl-ie8', static_path + '/karl_ie8.css',
            always_include=True, ie_expression='IE 8')
        config.define_css(
            'karl-ie9', static_path + '/karl_ie9.css',
            always_include=True, ie_expression='gte IE 9')

        config.define_javascript(
            'karl-ui', resource_name='karl-ui', always_include=True)
        config.define_javascript(
            'karl-custom', resource_name='karl-custom', always_include=True)
        config.define_javascript(
            'karl-multifileupload', resource_name='karl-multifileupload')
        config.define_javascript('karl-wikitoc', resource_name='karl-wikitoc')
        config.define_javascript('tinymce', name='tinymce')