示例#1
0
def make_auth_basic(app, global_config, conn=None, **local_conf):
    """Paste entry point for auth basic middleware using repoze.what"""

    if not conn:
        section = local_conf.get('section', 'ldap')
        config_file = local_conf.get('config',
                                     os.path.expanduser('~/.ldap.cfg'))
        conn = Connection(section, filename=config_file)

    basicauth = BasicAuthPlugin('Private web site')
    identifiers = [("basicauth", basicauth)]
    challengers = [("basicauth", basicauth)]

    authenticators = [("accounts", auth.Authenticator(conn, **local_conf))]
    groups = {'all_groups': auth.GroupAdapter(conn, **local_conf)}
    permissions = {'all_perms': auth.PermissionAdapter(conn, **local_conf)}
    mdproviders = [("accounts", auth.MDPlugin(conn, **local_conf))]

    return setup_auth(app,
                      groups,
                      permissions,
                      identifiers=identifiers,
                      authenticators=authenticators,
                      challengers=challengers,
                      mdproviders=mdproviders)
示例#2
0
def add_auth(app):

    # We need to set up the repoze.who components used by repoze.what for
    # authentication
    from repoze.who.plugins.htpasswd import HTPasswdPlugin, crypt_check
    from repoze.who.plugins.basicauth import BasicAuthPlugin
    htpasswd = HTPasswdPlugin('passwd', crypt_check)
    basicauth = BasicAuthPlugin('Alerts')
    identifiers = [('basicauth', basicauth)]
    authenticators = [('htpasswd', htpasswd)]
    challengers = [('basicauth', basicauth)]
    mdproviders = []

    # We'll use group and permission based exclusively on INI files
    from repoze.what.plugins.ini import INIGroupAdapter
    from repoze.what.plugins.ini import INIPermissionsAdapter

    groups = {'all_groups': INIGroupAdapter('groups.ini')}
    permissions = {'all_perms': INIPermissionsAdapter('permissions.ini')}

    # Finally, we create the repoze.what middleware
    import logging

    from repoze.what.middleware import setup_auth

    middleware = setup_auth(app=app,
                            group_adapters=groups,
                            permission_adapters=permissions,
                            identifiers=identifiers,
                            authenticators=authenticators,
                            challengers=challengers,
                            mdproviders=mdproviders,
                            log_level=logging.DEBUG)
    return middleware
示例#3
0
def AuthBasicMiddleware(app, global_config, **local_conf):

    if 'couchdb.uri' not in local_conf:
        local_conf['couchdb.uri'] = 'http://127.0.0.1:5984'

    server = couchdbkit.Server(local_conf['couchdb.uri'])
    db = server.get_or_create_db(local_conf['couchdb.db_name'])

    authenticator = couchdbkit.Authenticator(db)

    groups = couchdbkit.GroupAdapter(db)
    groups = {'all_groups': groups}

    basicauth = BasicAuthPlugin('Private web site')
    identifiers = [("basicauth", basicauth)]
    challengers = [("basicauth", basicauth)]

    authenticators = [("accounts", authenticator)]
    mdproviders = [("accounts", couchdbkit.MDPlugin(db))]

    permissions = {'all_perms': couchdbkit.PermissionAdapter(db)}

    return setup_auth(app,
                      groups,
                      permissions,
                      identifiers=identifiers,
                      authenticators=authenticators,
                      challengers=challengers,
                      mdproviders=mdproviders)
示例#4
0
def setup_auth(app, config):
    groupadapter = InstanceGroupSourceAdapter()
    #groupadapter.translations.update({'sections': 'groups'})
    permissionadapter = SqlPermissionsAdapter(model.Permission,
                                              model.Group,
                                              model.meta.Session)
    #permissionadapter.translations.update(permission_translations)

    group_adapters = {'sql_auth': groupadapter}
    permission_adapters = {'sql_auth': permissionadapter}

    basicauth = BasicAuthPlugin('Adhocracy HTTP Authentication')
    auth_tkt = InstanceAuthTktCookiePlugin(
        '41d207498d3812741e27c6441760ae494a4f9fbf',
        cookie_name='adhocracy_login', timeout=86400 * 2,
        reissue_time=3600)

    form = FriendlyFormPlugin(
            '/login',
            '/perform_login',
            '/post_login',
            '/logout',
            '/post_logout',
            login_counter_name='_login_tries',
            rememberer_name='auth_tkt')

    sqlauth = SQLAlchemyAuthenticatorPlugin(model.User, model.meta.Session)
    sql_user_md = SQLAlchemyUserMDPlugin(model.User, model.meta.Session)

    identifiers = [('form', form),
                   ('basicauth', basicauth),
                   ('auth_tkt', auth_tkt)]
    authenticators = [('sqlauth', sqlauth), ('auth_tkt', auth_tkt)]
    challengers = [('form', form), ('basicauth', basicauth)]
    mdproviders = [('sql_user_md', sql_user_md)]

    log_stream = None
    #log_stream = sys.stdout

    return setup_what(app, group_adapters, permission_adapters,
                      identifiers=identifiers,
                      authenticators=authenticators,
                      challengers=challengers,
                      mdproviders=mdproviders,
                      log_stream=log_stream,
                      log_level=logging.DEBUG,
                      # kwargs passed to repoze.who.plugins.testutils:
                      skip_authentication=config.get('skip_authentication'),
                      remote_user_key='HTTP_REMOTE_USER')
示例#5
0
def AuthenticationMiddleware(app, config):
    from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin
    from repoze.who.plugins.basicauth import BasicAuthPlugin
    from repoze.who.plugins.friendlyform import FriendlyFormPlugin
    from repoze.who.plugins.cookie import InsecureCookiePlugin
    from repoze.what.plugins.ini import INIPermissionsAdapter
    from repoze.what.middleware import setup_auth

    conn = ldap.get_conn()

    cookie = InsecureCookiePlugin('__ac')
    loginform = FriendlyFormPlugin(login_form_url="/login",
                                   login_handler_path="/do_login",
                                   post_login_url="/login",
                                   logout_handler_path="/logout",
                                   post_logout_url="/login",
                                   rememberer_name="_ac")

    authenticator = auth.Authenticator(conn)

    groups = auth.GroupAdapter(conn)
    groups = {'all_groups': groups}

    basicauth = BasicAuthPlugin('Private web site')
    if 'auth.basic' in config:
        identifiers = [("basicauth", basicauth)]
        challengers = [("basicauth", basicauth)]
    else:
        identifiers = [("loginform", loginform), ("_ac", cookie),
                       ("basicauth", basicauth)]
        challengers = [("loginform", loginform)]

    authenticators = [("accounts", authenticator)]
    mdproviders = [("accounts", auth.MDPlugin(conn))]

    permissions = {
        'all_perms': INIPermissionsAdapter(config['auth.permissions'])
    }

    return setup_auth(app,
                      groups,
                      permissions,
                      identifiers=identifiers,
                      authenticators=authenticators,
                      challengers=challengers,
                      mdproviders=mdproviders)
示例#6
0
def AuthenticationMiddleware(app):
    import isitopen.model as model
    import isitopen.lib.helpers as h
    modelpassword = ModelPasswordPlugin(model)
    basicauth = BasicAuthPlugin('repoze.who')
    auth_tkt = AuthTktCookiePlugin('secret', 'auth_tkt')
    form = RedirectingFormPlugin(
        login_form_url=h.url_for(controller='account', action='login'),
        login_handler_path=h.url_for('login-handler'),
        logout_handler_path=h.url_for('logout-handler'),
        rememberer_name='auth_tkt',
    )

    form.classifications = { IIdentifier:['browser'],
                             IChallenger:['browser'] } # only for browser
    identifiers = [('form', form),('auth_tkt',auth_tkt),('basicauth',basicauth)]
    authenticators = [('modelpassword', modelpassword)]
    challengers = [('form',form), ('basicauth',basicauth)]
    mdproviders = []

    from repoze.who.classifiers import default_request_classifier
    from repoze.who.classifiers import default_challenge_decider
    log_stream = None
    import os
    if os.environ.get('WHO_LOG'):
        log_stream = sys.stdout

    return PluggableAuthenticationMiddleware(
        app,
        identifiers,
        authenticators,
        challengers,
        mdproviders,
        default_request_classifier,
        default_challenge_decider,
        log_stream = log_stream,
        log_level = logging.DEBUG
    )
示例#7
0
def make_test_middleware(app, global_conf):
    """ Functionally equivalent to

    [plugin:form]
    use = repoze.who.plugins.form.FormPlugin
    rememberer_name = cookie
    login_form_qs=__do_login

    [plugin:cookie]
    use = repoze.who.plugins.cookie:InsecureCookiePlugin
    cookie_name = oatmeal

    [plugin:basicauth]
    use = repoze.who.plugins.basicauth.BasicAuthPlugin
    realm = repoze.who

    [plugin:htpasswd]
    use = repoze.who.plugins.htpasswd.HTPasswdPlugin
    filename = <...>
    check_fn = repoze.who.plugins.htpasswd:crypt_check

    [general]
    request_classifier = repoze.who.classifiers:default_request_classifier
    challenge_decider = repoze.who.classifiers:default_challenge_decider

    [identifiers]
    plugins = form:browser cookie basicauth

    [authenticators]
    plugins = htpasswd

    [challengers]
    plugins = form:browser basicauth
    """
    # be able to test without a config file
    from repoze.who.plugins.basicauth import BasicAuthPlugin
    from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin
    from repoze.who.plugins.cookie import InsecureCookiePlugin
    from repoze.who.plugins.form import FormPlugin
    from repoze.who.plugins.htpasswd import HTPasswdPlugin
    io = StringIO()
    salt = 'aa'
    for name, password in [ ('admin', 'admin'), ('chris', 'chris') ]:
        io.write('%s:%s\n' % (name, password))
    io.seek(0)
    def cleartext_check(password, hashed):
        return password == hashed #pragma NO COVERAGE
    htpasswd = HTPasswdPlugin(io, cleartext_check)
    basicauth = BasicAuthPlugin('repoze.who')
    auth_tkt = AuthTktCookiePlugin('secret', 'auth_tkt')
    cookie = InsecureCookiePlugin('oatmeal')
    form = FormPlugin('__do_login', rememberer_name='auth_tkt')
    form.classifications = { IIdentifier:['browser'],
                             IChallenger:['browser'] } # only for browser
    identifiers = [('form', form),('auth_tkt',auth_tkt),('basicauth',basicauth)]
    authenticators = [('htpasswd', htpasswd)]
    challengers = [('form',form), ('basicauth',basicauth)]
    mdproviders = []
    from repoze.who.classifiers import default_request_classifier
    from repoze.who.classifiers import default_challenge_decider
    log_stream = None
    import os
    if os.environ.get('WHO_LOG'):
        log_stream = sys.stdout
    middleware = PluggableAuthenticationMiddleware(
        app,
        identifiers,
        authenticators,
        challengers,
        mdproviders,
        default_request_classifier,
        default_challenge_decider,
        log_stream = log_stream,
        log_level = logging.DEBUG
        )
    return middleware
示例#8
0
def make_faswho_middleware(app,
                           log_stream=None,
                           login_handler='/login_handler',
                           login_form_url='/login',
                           logout_handler='/logout_handler',
                           post_login_url='/post_login',
                           post_logout_url=None,
                           fas_url=FAS_URL,
                           insecure=False,
                           ssl_cookie=True,
                           httponly=True):
    '''
    :arg app: WSGI app that is being wrapped
    :kwarg log_stream: :class:`logging.Logger` to log auth messages
    :kwarg login_handler: URL where the login form is submitted
    :kwarg login_form_url: URL where the login form is displayed
    :kwarg logout_handler: URL where the logout form is submitted
    :kwarg post_login_url: URL to redirect the user to after login
    :kwarg post_logout_url: URL to redirect the user to after logout
    :kwarg fas_url: Base URL to the FAS server
    :kwarg insecure: Allow connecting to a fas server without checking the
        server's SSL certificate.  Opens you up to MITM attacks but can be
        useful when testing.  *Do not enable this in production*
    :kwarg ssl_cookie: If :data:`True` (default), tell the browser to only
        send the session cookie back over https.
    :kwarg httponly: If :data:`True` (default), tell the browser that the
        session cookie should only be read for sending to a server, not for
        access by JavaScript or other clientside technology.  This prevents
        using the session cookie to pass information to JavaScript clients but
        also prevents XSS attacks from stealing the session cookie
        information.
    '''

    # Because of the way we override values (via a dict in AppConfig), we
    # need to make this a keyword arg and then check it here to make it act
    # like a positional arg.
    if not log_stream:
        raise TypeError(
            'log_stream must be set when calling make_fasauth_middleware()')

    faswho = FASWhoPlugin(fas_url,
                          insecure=insecure,
                          ssl_cookie=ssl_cookie,
                          httponly=httponly)
    csrf_mdprovider = CSRFMetadataProvider()

    form = FriendlyFormPlugin(login_form_url,
                              login_handler,
                              post_login_url,
                              logout_handler,
                              post_logout_url,
                              rememberer_name='fasident',
                              charset='utf-8')

    form.classifications = {
        IIdentifier: ['browser'],
        IChallenger: ['browser']
    }  # only for browser

    basicauth = BasicAuthPlugin('repoze.who')

    identifiers = [('form', form), ('fasident', faswho),
                   ('basicauth', basicauth)]
    authenticators = [('fasauth', faswho)]
    challengers = [('form', form), ('basicauth', basicauth)]
    mdproviders = [('fasmd', faswho), ('csrfmd', csrf_mdprovider)]

    if os.environ.get('FAS_WHO_LOG'):
        log_stream = sys.stdout

    app = CSRFProtectionMiddleware(app)
    app = PluggableAuthenticationMiddleware(
        app,
        identifiers,
        authenticators,
        challengers,
        mdproviders,
        fas_request_classifier,
        default_challenge_decider,
        log_stream=log_stream,
    )

    return app
示例#9
0
def make_test_middleware(app, global_conf):
    """ Functionally equivalent to

    [plugin:redirector]
    use = repoze.who.plugins.redirector.RedirectorPlugin
    login_url = /login.html

    [plugin:auth_tkt]
    use = repoze.who.plugins.auth_tkt:AuthTktCookiePlugin
    secret = SEEKRIT
    cookie_name = oatmeal

    [plugin:basicauth]
    use = repoze.who.plugins.basicauth.BasicAuthPlugin
    realm = repoze.who

    [plugin:htpasswd]
    use = repoze.who.plugins.htpasswd.HTPasswdPlugin
    filename = <...>
    check_fn = repoze.who.plugins.htpasswd:crypt_check

    [general]
    request_classifier = repoze.who.classifiers:default_request_classifier
    challenge_decider = repoze.who.classifiers:default_challenge_decider

    [identifiers]
    plugins = authtkt basicauth

    [authenticators]
    plugins = authtkt htpasswd

    [challengers]
    plugins = redirector:browser basicauth
    """
    # be able to test without a config file
    from repoze.who.plugins.basicauth import BasicAuthPlugin
    from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin
    from repoze.who.plugins.redirector import RedirectorPlugin
    from repoze.who.plugins.htpasswd import HTPasswdPlugin
    io = StringIO()
    for name, password in [('admin', 'admin'), ('chris', 'chris')]:
        io.write('%s:%s\n' % (name, password))
    io.seek(0)

    def cleartext_check(password, hashed):
        return password == hashed  #pragma NO COVERAGE

    htpasswd = HTPasswdPlugin(io, cleartext_check)
    basicauth = BasicAuthPlugin('repoze.who')
    auth_tkt = AuthTktCookiePlugin('secret', 'auth_tkt')
    redirector = RedirectorPlugin('/login.html')
    redirector.classifications = {IChallenger: ['browser']}  # only for browser
    identifiers = [
        ('auth_tkt', auth_tkt),
        ('basicauth', basicauth),
    ]
    authenticators = [('htpasswd', htpasswd)]
    challengers = [('redirector', redirector), ('basicauth', basicauth)]
    mdproviders = []
    from repoze.who.classifiers import default_request_classifier
    from repoze.who.classifiers import default_challenge_decider
    log_stream = None
    import os
    if os.environ.get('WHO_LOG'):
        log_stream = sys.stdout
    middleware = PluggableAuthenticationMiddleware(app,
                                                   identifiers,
                                                   authenticators,
                                                   challengers,
                                                   mdproviders,
                                                   default_request_classifier,
                                                   default_challenge_decider,
                                                   log_stream=log_stream,
                                                   log_level=logging.DEBUG)
    return middleware
示例#10
0
def setup_auth(app, config):
    groupadapter = InstanceGroupSourceAdapter()
    #groupadapter.translations.update({'sections': 'groups'})
    permissionadapter = SqlPermissionsAdapter(model.Permission, model.Group,
                                              model.meta.Session)
    #permissionadapter.translations.update(permission_translations)

    group_adapters = {'sql_auth': groupadapter}
    permission_adapters = {'sql_auth': permissionadapter}

    basicauth = BasicAuthPlugin('Adhocracy HTTP Authentication')
    auth_tkt = InstanceAuthTktCookiePlugin(
        config,
        config.get('adhocracy.auth.secret', config['beaker.session.secret']),
        cookie_name='adhocracy_login',
        timeout=86400 * 2,
        reissue_time=3600,
        secure=config.get('adhocracy.protocol', 'http') == 'https')

    sqlauth = EmailSQLAlchemyAuthenticatorPlugin(model.User,
                                                 model.meta.Session)
    sql_user_md = SQLAlchemyUserMDPlugin(model.User, model.meta.Session)

    login_urls = [
        '/login',
        '/perform_login',
        '/post_login',
        '/logout',
        '/post_logout',
    ]
    login_options = dict(
        login_counter_name='_login_tries',
        rememberer_name='auth_tkt',
        charset='utf-8',
    )
    if config.get('adhocracy.login_style') == 'alternate':
        form = AlternateLoginFriendlyFormPlugin(sqlauth.get_user, *login_urls,
                                                **login_options)
    else:
        form = FriendlyFormPlugin(*login_urls, **login_options)

    identifiers = [('form', form), ('basicauth', basicauth),
                   ('auth_tkt', auth_tkt)]
    authenticators = [('sqlauth', sqlauth), ('auth_tkt', auth_tkt)]
    challengers = [('form', form), ('basicauth', basicauth)]
    mdproviders = [('sql_user_md', sql_user_md)]

    welcome.setup_auth(config, identifiers, authenticators)

    log_stream = None
    #log_stream = sys.stdout

    # If a webserver already sets a HTTP_REMOTE_USER environment variable,
    # repoze.who merely acts as a pass through and doesn't set up the proper
    # environment (e.g. environ['repoze.who.api'] is missing).
    #
    # This happens for example in the case of Shibboleth based authentication -
    # we weren't able to prevent mod_shibboleth from setting the header.
    # Therefore the remote user key to look for is not set to HTTP_REMOTE_USER,
    # but to the non-existing DONT_USE_HTTP_REMOTE_USER environment variable.

    REMOTE_USER_KEY = 'DONT_USE_HTTP_REMOTE_USER'

    return setup_what(
        app,
        group_adapters,
        permission_adapters,
        identifiers=identifiers,
        authenticators=authenticators,
        challengers=challengers,
        mdproviders=mdproviders,
        log_stream=log_stream,
        log_level=logging.DEBUG,
        # kwargs passed to repoze.who.plugins.testutils:
        skip_authentication=config.get('skip_authentication'),
        remote_user_key=REMOTE_USER_KEY)
示例#11
0
    def add_auth_middleware(self, app, skip_authentication):
        """
        """
        log_stream = config.get('who.log_stream', 'stdout')
        log_stream = LOG_STREAMS.get(log_stream, log_stream)
        if isinstance(log_stream, basestring):
            log_stream = logging.getLogger(log_stream)
        log_level = LOG_LEVELS.get(config['who.log_level'], logging.ERROR)
        log.debug("LOG_STREAM %s LOG_LEVEL %s", str(log_stream),
                  str(log_level))

        if 'who.config_file' in config and asbool(
                config.get('bisque.has_database')):
            parser = WhoConfig(config['here'])
            parser.parse(open(config['who.config_file']))

            if not asbool(skip_authentication):
                app = PluggableAuthenticationMiddleware(
                    app,
                    parser.identifiers,
                    parser.authenticators,
                    parser.challengers,
                    parser.mdproviders,
                    parser.request_classifier,
                    parser.challenge_decider,
                    log_stream=log_stream,
                    log_level=log_level,
                    remote_user_key=parser.remote_user_key,
                )
            else:
                app = AuthenticationForgerMiddleware(
                    app,
                    parser.identifiers,
                    parser.authenticators,
                    parser.challengers,
                    parser.mdproviders,
                    parser.request_classifier,
                    parser.challenge_decider,
                    log_stream=log_stream,
                    log_level=log_level,
                    remote_user_key=parser.remote_user_key,
                )
        else:
            log.info("MEX auth only")
            # Add mex only authentication
            from repoze.who.plugins.basicauth import BasicAuthPlugin
            from bq.core.lib.mex_auth import make_plugin
            from repoze.who.classifiers import default_request_classifier
            from repoze.who.classifiers import default_challenge_decider
            basicauth = BasicAuthPlugin('repoze.who')
            mexauth = make_plugin()

            identifiers = [('mexauth', mexauth)]
            authenticators = [('mexauth', mexauth)]
            challengers = []
            mdproviders = []
            app = PluggableAuthenticationMiddleware(
                app,
                identifiers,
                authenticators,
                challengers,
                mdproviders,
                default_request_classifier,
                default_challenge_decider,
                log_stream=log_stream,
                log_level=log_level,
            )
        return app
示例#12
0
 def test_non_default_form_plugin(self):
     app = self._makeApp(form_plugin=BasicAuthPlugin('1+1=2'))
     self._in_registry(app, 'main_identifier', BasicAuthPlugin)
示例#13
0
 def test_additional_identifiers(self):
     identifiers = [('http_auth', BasicAuthPlugin('1+1=2'))]
     app = self._makeApp(identifiers=identifiers)
     self._in_registry(app, 'main_identifier', FriendlyFormPlugin)
     self._in_registry(app, 'http_auth', BasicAuthPlugin)
示例#14
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """
    Create a Pylons WSGI application and return it

    ``global_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(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp()

    # Profiling Middleware
    if profile_load:
        if asbool(config['profile']):
            app = AccumulatingProfileMiddleware(
                app,
                log_filename='/var/log/privacyidea/profiling.log',
                cachegrind_filename='/var/log/privacyidea/cachegrind.out',
                discard_first_request=True,
                flush_at_shutdown=True,
                path='/__profile__'
            )

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    # We do not use beaker sessions! Keep the environment smaller.
    #app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_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)
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        # Serve static files
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
        app = Cascade([static_app, app])

    # Add the repoze.who middleware
    # with a cookie encryption key, that is generated at every server start!
    cookie_timeout = int(global_conf.get("privacyIDEASessionTimeout",
                                         COOKIE_TIMEOUT))
    cookie_reissue_time = int(cookie_timeout / 2)
    cookie_key = geturandom(32)
    privacyidea_auth = auth_privacy_plugin()
    basicauth = BasicAuthPlugin('repoze.who')
    privacyidea_md = auth_privacy_plugin()
    auth_tkt = AuthTktCookiePlugin(cookie_key,
                                   cookie_name='privacyidea_session',
                                   secure=True,
                                   include_ip=False,
                                   timeout=cookie_timeout,
                                   reissue_time=cookie_reissue_time)
    form = make_redirecting_plugin(login_form_url="/account/login",
                                   login_handler_path='/account/dologin',
                                   logout_handler_path='/account/logout',
                                   rememberer_name="auth_tkt")
    # For authentication for browsers
    form.classifications = {IIdentifier: ['browser'],
                            IChallenger: ['browser']}
    # basic authentication only for API calls
    basicauth.classifications = {IIdentifier: ['basic'],
                                 IChallenger: ['basic']}
    identifiers = [('form', form),
                   ('auth_tkt', auth_tkt),
                   ('basicauth', basicauth)]
    authenticators = [('privacyidea.lib.repoze_auth:UserModelPlugin',
                       privacyidea_auth)]
    challengers = [('form', form),
                   ('basicauth', basicauth)]

    mdproviders = [('privacyidea.lib.repoze_auth:UserModelPlugin',
                    privacyidea_md)]

    #app = make_who_with_config(app, global_conf, app_conf['who.config_file'],
    #                     app_conf['who.log_file'], app_conf['who.log_level'])

    log_file = app_conf.get("who.log_file")
    if log_file is not None:
        if log_file.lower() == 'stdout':
            log_stream = None
        else:
            log_stream = open(log_file, 'wb')

    log_level = app_conf.get("who.log_level")
    if log_level is None:
        log_level = logging.INFO
    else:
        log_level = _LEVELS[log_level.lower()]

    app = PluggableAuthenticationMiddleware(
        app,
        identifiers,
        authenticators,
        challengers,
        mdproviders,
        request_classifier,
        default_challenge_decider,
        log_stream,
        log_level
        )

    return app
示例#15
0
from tg.configuration import AppConfig
from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin
from repoze.who.plugins.basicauth import BasicAuthPlugin
import os

authtkt = AuthTktCookiePlugin('authtkt', 'authtkt')
basicauth = BasicAuthPlugin("something")

import pythondispatchms
from pythondispatchms import model, lib

base_config = AppConfig()
base_config.renderers = []

# True to prevent dispatcher from striping extensions
# For example /socket.io would be served by "socket_io"
# method instead of "socket".
base_config.disable_request_extensions = False

# Set None to disable escaping punctuation characters to "_"
# when dispatching methods.
# Set to a function to provide custom escaping.
base_config.dispatch_path_translator = True

base_config.prefer_toscawidgets2 = True

base_config.package = pythondispatchms

# Enable json in expose
base_config.renderers.append('json')
示例#16
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """Create a Pylons WSGI application and return it

    ``global_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(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp()

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    basicauth = BasicAuthPlugin('OpenSpending')
    auth_tkt = AuthTktCookiePlugin(
        'RANDOM_KEY_THAT_ONLY_LOOKS_LIKE_A_PLACEHOLDER',
        cookie_name='openspending_login',
        timeout=86400 * 90,
        reissue_time=3600)
    form = FriendlyFormPlugin('/login',
                              '/perform_login',
                              '/after_login',
                              '/logout',
                              '/after_logout',
                              rememberer_name='auth_tkt')
    identifiers = [('auth_tkt', auth_tkt), ('basicauth', basicauth),
                   ('form', form)]
    authenticators = [('auth_tkt', auth_tkt),
                      ('username', UsernamePasswordAuthenticator()),
                      ('apikey', ApiKeyAuthenticator())]
    challengers = [('form', form), ('basicauth', basicauth)]
    log_stream = sys.stdout
    app = PluggableAuthenticationMiddleware(app,
                                            identifiers,
                                            authenticators,
                                            challengers, [],
                                            default_request_classifier,
                                            default_challenge_decider,
                                            log_stream=log_stream,
                                            log_level=logging.WARN)

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_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)
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        max_age = None if asbool(config['debug']) else 3600

        # Serve static files
        static_app = StaticURLParser(config['pylons.paths']['static_files'],
                                     cache_max_age=max_age)
        static_parsers = [static_app, app]
        app = Cascade(static_parsers)

    return app
示例#17
0
    # Configure the repoze.who middleware:

    ## fake .htpasswd authentication source
    io = StringIO()
    for name, password in [('admin', 'admin'), ('user', 'user')]:
        io.write('%s:%s\n' % (name, password))
    io.seek(0)

    def cleartext_check(password, hashed):
        return password == hashed

    htpasswd = HTPasswdPlugin(io, cleartext_check)

    ## other plugins
    basicauth = BasicAuthPlugin('repoze.who')
    auth_tkt = AuthTktCookiePlugin('secret', 'auth_tkt')
    redirector = RedirectorPlugin(login_url='/login.html')
    redirector.classifications = {IChallenger: ['browser']}  # only for browser

    ## group / order plugins by function
    identifiers = [('auth_tkt', auth_tkt), ('basicauth', basicauth)]
    authenticators = [('auth_tkt', auth_tkt), ('htpasswd', htpasswd)]
    challengers = [('redirector', redirector), ('basicauth', basicauth)]
    mdproviders = []

    ## set up who logging, if desired
    log_stream = None
    if os.environ.get('WHO_LOG'):
        log_stream = sys.stdout