本文整理汇总了Python中repoze.who.config.WhoConfig类的典型用法代码示例。如果您正苦于以下问题:Python WhoConfig类的具体用法?Python WhoConfig怎么用?Python WhoConfig使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WhoConfig类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
import zope.app.wsgi
zope_conf = os.path.join(here, 'zope.conf')
zope = zope.app.wsgi.getWSGIApplication(zope_conf)
from repoze.who.middleware import PluggableAuthenticationMiddleware
from repoze.who.config import WhoConfig
parser = WhoConfig(here)
parser.parse(open(os.path.join(here, 'who.ini')))
log_stream = sys.stdout
log_level = logging.DEBUG
app = PluggableAuthenticationMiddleware(
zope,
parser.identifiers,
parser.authenticators,
parser.challengers,
parser.mdproviders,
parser.request_classifier,
parser.challenge_decider,
log_stream,
log_level,
)
from paste import httpserver
httpserver.serve(app, host='0.0.0.0', port='9876')
示例2: add_auth_middleware
def add_auth_middleware(self, app, skip_authentication):
"""
Configure authentication and authorization.
:param app: The TG2 application.
:param skip_authentication: Should authentication be skipped if
explicitly requested? (used by repoze.who-testutil)
:type skip_authentication: bool
"""
if asbool(config.get('loom.profile', False)):
log.debug('Setting up profiling middleware')
app = AccumulatingProfileMiddleware(
app,
log_filename='/home/volkmuth/profile/app.log',
cachegrind_filename='/home/volkmuth/profile/cachegrind.out.app',
discard_first_request=False,
flush_at_shutdown=True,
path='/__profile__')
parser = WhoConfig(config['here'])
parser.parse(open(config.get('who.config_file', 'who.ini')))
app = make_middleware(skip_authentication, app,
parser.identifiers,
parser.authenticators,
parser.challengers,
parser.mdproviders,
parser.request_classifier,
parser.challenge_decider,
remote_user_key=parser.remote_user_key)
#app = make_who_with_config(app, config, config.get('who.config_file','who.ini'),
# config.get('who.log_file','stdout'), config.get('who.log_level','debug'),
# skip_authentication
# )
app = ModuleMiddleware(app)
return app
示例3: _mk_mw_cfg
def _mk_mw_cfg(app, global_conf, config_file,
log_file=None, log_level=None):
"""
Inspiré par C{repoze.who.config:make_middleware_with_config}.
"""
parser = WhoConfig(global_conf['here'])
parser.parse(open(config_file))
log_stream = None
if log_file is not None:
if log_file.lower() == 'stdout':
log_stream = sys.stdout
else:
log_stream = open(log_file, 'wb')
if log_level is None:
log_level = logging.INFO
else:
log_level = _LEVELS[log_level.lower()]
return VigiloAuthMiddleware(
app,
parser.identifiers,
parser.authenticators,
parser.challengers,
parser.mdproviders,
parser.request_classifier,
parser.challenge_decider,
log_stream,
log_level,
parser.remote_user_key,
)
示例4: make_middleware_with_config
def make_middleware_with_config(app, global_conf, config_file, log_file=None,
log_level=None, skip_authentication=False):
"""
Proxy :func:`repoze.who.config.make_middleware_with_config` to skip
authentication when required.
If ``skip_authentication`` evaluates to ``True``, then the returned
middleware will be an instance of :class:`AuthenticationForgerMiddleware`.
"""
if not asbool(skip_authentication):
# We must not replace the middleware
return mk_mw_cfg(app, global_conf, config_file, log_file, log_level)
# We must replace the middleware:
parser = WhoConfig(global_conf['here'])
parser.parse(open(config_file))
return AuthenticationForgerMiddleware(
app,
parser.identifiers,
parser.authenticators,
parser.challengers,
parser.mdproviders,
parser.request_classifier,
parser.challenge_decider,
remote_user_key=parser.remote_user_key,
)
示例5: api_factory_from_settings
def api_factory_from_settings(settings, prefix="who."):
"""Create a new repoze.who APIFactory from the deployment settings.
This function uses the paster deployment settings to create a repoze.who
APIFactory object. Settings starting with "who." are collected and
formatted into an ini-file which can be read by the repoze.who config
parser, and the resulting APIFactory object is returned.
"""
# If we have already built and cached one, just use it directly.
cache_key = prefix + "api_factory"
if cache_key in settings:
return settings[cache_key]
# Grab out all the settings keys that start with our prefix.
who_settings = {}
for name, value in settings.iteritems():
if not name.startswith(prefix):
continue
who_settings[name[len(prefix):]] = value
# Construct a who.ini config file in memory.
# First, read in any config file specified in the settings.
who_ini_lines = []
if "config_file" in who_settings:
with open(who_settings["config_file"], "r") as f:
who_ini_lines.extend(ln.strip() for ln in f)
# Format any dotted setting names into an ini-file section.
# For example, a settings file line like:
# who.identifiers.plugins = blah
# Will become an ini-file entry like:
# [identifiers]
# plugins = blah
for name, value in who_settings.iteritems():
if isinstance(value, (list, tuple)):
value = " ".join(value)
else:
value = str(value)
try:
section, var = name.rsplit(".", 1)
except ValueError:
pass
else:
who_ini_lines.append("[%s]" % (section.replace(".", ":"),))
who_ini_lines.append("%s = %s" % (var, value))
# Now we can parse that config using repoze.who's own machinery.
parser = WhoConfig(who_settings.get("here", ""))
parser.parse("\n".join(who_ini_lines))
api_factory = APIFactory(parser.identifiers,
parser.authenticators,
parser.challengers,
parser.mdproviders,
parser.request_classifier,
parser.challenge_decider)
# Cache it so we don't have to repeat all that work.
settings[cache_key] = api_factory
return api_factory
示例6: _make_api_factory
def _make_api_factory(self):
parser = WhoConfig("")
parser.parse(WHO_CONFIG)
return APIFactory(parser.identifiers,
parser.authenticators,
parser.challengers,
parser.mdproviders,
parser.request_classifier,
parser.challenge_decider)
示例7: _configure_api_factory
def _configure_api_factory():
global api_factory
if api_factory is None:
config = WhoConfig(here='/tmp') # XXX config file location
config.parse(WHO_CONFIG)
api_factory = APIFactory(identifiers=config.identifiers,
authenticators=config.authenticators,
challengers=config.challengers,
mdproviders=config.mdproviders,
request_classifier=config.request_classifier,
challenge_decider=config.challenge_decider,
)
return api_factory
示例8: _wsgi_app
def _wsgi_app(self):
parser = WhoConfig("")
parser.parse(WHO_CONFIG)
def application(environ, start_response):
start_response("401 Unauthorized", [])
return [""]
return PluggableAuthenticationMiddleware(application,
parser.identifiers,
parser.authenticators,
parser.challengers,
parser.mdproviders,
parser.request_classifier,
parser.challenge_decider)
示例9: make_middleware_with_config
def make_middleware_with_config(app, global_conf, config_file, who_config_file="", log_file=None, log_level=None):
"""Override repoze.what.plugins.config:make_middleware_with_config
Allows us to call a Baruwa modified authentication stark
"""
if not who_config_file:
who_config_file = config_file
who_parser = WhoConfig(global_conf["here"])
who_parser.parse(open(who_config_file))
what_parser = WhatConfig(global_conf["here"])
what_parser.parse(open(config_file))
log_stream = None
if log_file is not None:
if log_file.lower() == "stdout":
log_stream = sys.stdout
else:
try:
log_stream = open(log_file, "wb")
except IOError:
log_stream = None
if log_level is None:
log_level = logging.INFO
else:
log_level = _LEVELS[log_level.lower()]
return setup_auth(
app,
group_adapters=what_parser.group_adapters,
permission_adapters=what_parser.permission_adapters,
identifiers=who_parser.identifiers,
authenticators=who_parser.authenticators,
challengers=who_parser.challengers,
mdproviders=who_parser.mdproviders,
classifier=who_parser.request_classifier,
challenge_decider=who_parser.challenge_decider,
log_stream=log_stream,
log_level=log_level,
remote_user_key=who_parser.remote_user_key,
)
示例10: make_middleware_with_config
def make_middleware_with_config(app, global_conf, log_file=None):
"""Override repoze.what.plugins.config:make_middleware_with_config
Allows us to call a Baruwa modified authentication stark and use
single configuration file
"""
who_parser = WhoConfig(global_conf['here'])
who_parser.parse(open(global_conf['__file__']))
what_parser = WhatConfig(global_conf['here'])
what_parser.parse(open(global_conf['__file__']))
log_level = 'DEBUG' if asbool(global_conf['debug']) else 'INFO'
log_stream = None
if log_file is not None:
if log_file.lower() == 'stdout':
log_stream = sys.stdout
else:
try:
log_stream = open(log_file, 'wb')
except IOError:
log_stream = None
if log_level is None:
log_level = logging.INFO
else:
log_level = _LEVELS[log_level.lower()]
return setup_auth(app,
group_adapters=what_parser.group_adapters,
permission_adapters=what_parser.permission_adapters,
identifiers=who_parser.identifiers,
authenticators=who_parser.authenticators,
challengers=who_parser.challengers,
mdproviders=who_parser.mdproviders,
classifier=who_parser.request_classifier,
challenge_decider=who_parser.challenge_decider,
log_stream = log_stream,
log_level = log_level,
remote_user_key = who_parser.remote_user_key,
)
示例11: make_who_middleware
def make_who_middleware(app, config):
who_config = pkg_resources.resource_stream(__name__, 'who.ini').read()
who_config = who_config % dict(
cookie=config['who_cookie'],
secret=config['who_secret'],
realm=config.get('who_realm', config['system_name']))
parser = WhoConfig(config['here'])
parser.parse(who_config)
return PluggableAuthenticationMiddleware(
app,
parser.identifiers,
parser.authenticators,
parser.challengers,
parser.mdproviders,
parser.request_classifier,
parser.challenge_decider,
None, # log_stream
logging.INFO,
parser.remote_user_key,
)
示例12: __init__
def __init__(self, config):
# Load the auth backend if specified.
# There may not be one configured if repoze.who is going to look
# elsewhere for credentials, e.g. in a htpasswd database.
self.config = config
try:
self.backend = load_and_configure(self.config, 'auth')
except KeyError:
self.backend = None
self.logger = CLIENT_HOLDER.default_client
# Extract who-related settings from the config or from our defaults.
# the configured authentication backend.
who_settings = self._get_who_settings(self.config)
# Build up a who.ini config file in memory.
# Any settings of the form "A.B.C = X" get translated into
# a config file section like "[A:B]\nC = X"
who_ini_lines = []
for key, value in who_settings.iteritems():
try:
section, var = key.rsplit(".", 1)
except ValueError:
pass
else:
section = section.replace(".", ":")
who_ini_lines.append("[%s]" % (section,))
who_ini_lines.append("%s = %s" % (var, value))
# Now we can parse that config using repoze.who's own machinery.
parser = WhoConfig("")
parser.parse("\n".join(who_ini_lines))
self._api_factory = APIFactory(parser.identifiers,
parser.authenticators,
parser.challengers,
parser.mdproviders,
parser.request_classifier,
parser.challenge_decider)
# Give all backend plugins access to the config.
self._configure_backend_plugins(self._api_factory)
示例13: make_middleware_with_config
def make_middleware_with_config(app, global_conf, config_file,
who_config_file = '',
log_file=None, log_level=None):
if not who_config_file:
who_config_file = config_file
who_parser = WhoConfig(global_conf['here'])
who_parser.parse(open(who_config_file))
what_parser = WhatConfig(global_conf['here'])
what_parser.parse(open(config_file))
log_stream = None
if log_file is not None:
if log_file.lower() == 'stdout':
log_stream = sys.stdout
else:
log_stream = open(log_file, 'wb')
if log_level is None:
log_level = logging.INFO
else:
log_level = _LEVELS[log_level.lower()]
return setup_auth(app,
group_adapters=what_parser.group_adapters,
permission_adapters=what_parser.permission_adapters,
identifiers=who_parser.identifiers,
authenticators=who_parser.authenticators,
challengers=who_parser.challengers,
mdproviders=who_parser.mdproviders,
classifier=who_parser.request_classifier,
challenge_decider=who_parser.challenge_decider,
log_stream = log_stream,
log_level = log_level,
remote_user_key = who_parser.remote_user_key,
)
示例14: make_app
def make_app(conf, full_stack=True, static_files=True, **app_conf):
"""Create a Pylons WSGI application and return it
``conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``full_stack``
Whether this application provides a full WSGI stack (by default,
meaning it handles its own exceptions and errors). Disable
full_stack when this application is "managed" by another WSGI
middleware.
``static_files``
Whether this application serves its own static files; disable
when another web server is responsible for serving them.
``app_conf``
The application's local configuration. Normally specified in
the [app:<name>] section of the Paste ini file (where <name>
defaults to main).
"""
# Configure the Pylons environment
load_environment(conf, app_conf)
# The Pylons WSGI app
app = PylonsApp()
# set pylons globals
app_globals.reset()
for plugin in PluginImplementations(IMiddleware):
app = plugin.make_middleware(app, config)
# Routing/Session/Cache Middleware
app = RoutesMiddleware(app, config['routes.map'])
# we want to be able to retrieve the routes middleware to be able to update
# the mapper. We store it in the pylons config to allow this.
config['routes.middleware'] = app
app = SessionMiddleware(app, config)
app = CacheMiddleware(app, config)
# CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
#app = QueueLogMiddleware(app)
# Fanstatic
if asbool(config.get('debug', False)):
fanstatic_config = {
'versioning': True,
'recompute_hashes': True,
'minified': False,
'bottom': True,
'bundle': False,
}
else:
fanstatic_config = {
'versioning': True,
'recompute_hashes': False,
'minified': True,
'bottom': True,
'bundle': True,
}
app = Fanstatic(app, **fanstatic_config)
if asbool(full_stack):
# Handle Python exceptions
app = ErrorHandler(app, conf, **config['pylons.errorware'])
# Display error documents for 401, 403, 404 status codes (and
# 500 when debug is disabled)
if asbool(config['debug']):
app = StatusCodeRedirect(app, [400, 404])
else:
app = StatusCodeRedirect(app, [400, 404, 500])
# Initialize repoze.who
who_parser = WhoConfig(conf['here'])
who_parser.parse(open(app_conf['who.config_file']))
if asbool(config.get('openid_enabled', 'true')):
from repoze.who.plugins.openid.identification import OpenIdIdentificationPlugin
# Monkey patches for repoze.who.openid
# Fixes #1659 - enable log-out when CKAN mounted at non-root URL
from ckan.lib import repoze_patch
OpenIdIdentificationPlugin.identify = repoze_patch.identify
OpenIdIdentificationPlugin.redirect_to_logged_in = repoze_patch.redirect_to_logged_in
OpenIdIdentificationPlugin._redirect_to_loginform = repoze_patch._redirect_to_loginform
OpenIdIdentificationPlugin.challenge = repoze_patch.challenge
who_parser.identifiers = [i for i in who_parser.identifiers if \
not isinstance(i, OpenIdIdentificationPlugin)]
who_parser.challengers = [i for i in who_parser.challengers if \
not isinstance(i, OpenIdIdentificationPlugin)]
app = PluggableAuthenticationMiddleware(app,
who_parser.identifiers,
who_parser.authenticators,
who_parser.challengers,
who_parser.mdproviders,
who_parser.request_classifier,
#.........这里部分代码省略.........
示例15: make_pylons_stack
def make_pylons_stack(conf, full_stack=True, static_files=True, **app_conf):
"""Create a Pylons WSGI application and return it
``conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``full_stack``
Whether this application provides a full WSGI stack (by default,
meaning it handles its own exceptions and errors). Disable
full_stack when this application is "managed" by another WSGI
middleware.
``static_files``
Whether this application serves its own static files; disable
when another web server is responsible for serving them.
``app_conf``
The application's local configuration. Normally specified in
the [app:<name>] section of the Paste ini file (where <name>
defaults to main).
"""
# Configure the Pylons environment
load_environment(conf, app_conf)
# The Pylons WSGI app
app = pylons_app = CKANPylonsApp()
# set pylons globals
app_globals.reset()
for plugin in PluginImplementations(IMiddleware):
app = plugin.make_middleware(app, config)
# Routing/Session/Cache Middleware
app = RoutesMiddleware(app, config['routes.map'])
# we want to be able to retrieve the routes middleware to be able to update
# the mapper. We store it in the pylons config to allow this.
config['routes.middleware'] = app
app = SessionMiddleware(app, config)
app = CacheMiddleware(app, config)
# CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
# app = QueueLogMiddleware(app)
if asbool(config.get('ckan.use_pylons_response_cleanup_middleware', True)):
app = execute_on_completion(app, config,
cleanup_pylons_response_string)
# Fanstatic
if asbool(config.get('debug', False)):
fanstatic_config = {
'versioning': True,
'recompute_hashes': True,
'minified': False,
'bottom': True,
'bundle': False,
}
else:
fanstatic_config = {
'versioning': True,
'recompute_hashes': False,
'minified': True,
'bottom': True,
'bundle': True,
}
app = Fanstatic(app, **fanstatic_config)
for plugin in PluginImplementations(IMiddleware):
try:
app = plugin.make_error_log_middleware(app, config)
except AttributeError:
log.critical('Middleware class {0} is missing the method'
'make_error_log_middleware.'
.format(plugin.__class__.__name__))
if asbool(full_stack):
# Handle Python exceptions
app = ErrorHandler(app, conf, **config['pylons.errorware'])
# Display error documents for 400, 403, 404 status codes (and
# 500 when debug is disabled)
if asbool(config['debug']):
app = StatusCodeRedirect(app, [400, 403, 404])
else:
app = StatusCodeRedirect(app, [400, 403, 404, 500])
# Initialize repoze.who
who_parser = WhoConfig(conf['here'])
who_parser.parse(open(app_conf['who.config_file']))
app = PluggableAuthenticationMiddleware(
app,
who_parser.identifiers,
who_parser.authenticators,
who_parser.challengers,
who_parser.mdproviders,
who_parser.request_classifier,
who_parser.challenge_decider,
logging.getLogger('repoze.who'),
#.........这里部分代码省略.........