Beispiel #1
0
 def _makeApp(self, groups, permissions, **who_args):
     cookie = AuthTktCookiePlugin('secret', 'authtkt')
     
     form = RedirectingFormPlugin('/login', '/login_handler',
                                  '/logout_handler',
                                  rememberer_name='cookie')
     
     identifiers = [('main_identifier', form), ('cookie', cookie)]
     
     authenticators = [('fake_authenticator', FakeAuthenticator())]
     
     challengers = [('form', form)]
     
     if groups is None:
         app_with_auth = setup_auth(
             DummyApp(),
             identifiers=identifiers,
             authenticators=authenticators,
             challengers=challengers,
             **who_args
             )
     else:
         app_with_auth = setup_auth(
             DummyApp(),
             groups,
             permissions,
             identifiers=identifiers,
             authenticators=authenticators,
             challengers=challengers,
             **who_args
             )
     return app_with_auth
Beispiel #2
0
    def _makeApp(self, groups, permissions, **who_args):
        cookie = AuthTktCookiePlugin('secret', 'authtkt')

        form = RedirectingFormPlugin('/login',
                                     '/login_handler',
                                     '/logout_handler',
                                     rememberer_name='cookie')

        identifiers = [('main_identifier', form), ('cookie', cookie)]

        authenticators = [('fake_authenticator', FakeAuthenticator())]

        challengers = [('form', form)]

        if groups is None:
            app_with_auth = setup_auth(DummyApp(),
                                       identifiers=identifiers,
                                       authenticators=authenticators,
                                       challengers=challengers,
                                       **who_args)
        else:
            app_with_auth = setup_auth(DummyApp(),
                                       groups,
                                       permissions,
                                       identifiers=identifiers,
                                       authenticators=authenticators,
                                       challengers=challengers,
                                       **who_args)
        return app_with_auth
Beispiel #3
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)
Beispiel #4
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)
Beispiel #5
0
def make_app(controller_klass, environ={}, with_errors=False):
    """Creates a ``TestApp`` instance."""
    # The basic middleware:
    app = ControllerWrap(controller_klass)
    app = SetupCacheGlobal(app, environ, setup_cache=True, setup_session=True)
    if with_errors:
        app = ErrorHandler(app, {}, debug=False)
        app = StatusCodeRedirect(app, [403, 404, 500])
    app = RegistryManager(app)
    app = SessionMiddleware(app, {}, data_dir=session_dir)
    app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, 'cache'))

    # We're not going to use groups or permissions-related predicates here:
    groups_adapters = None
    permissions_adapters = None

    # Setting repoze.who up:
    cookie = AuthTktCookiePlugin('secret', 'authtkt')
    identifiers = [('cookie', cookie)]

    app = setup_auth(app, groups_adapters, permissions_adapters,
                     identifiers=identifiers, authenticators=[],
                     challengers=[], skip_authentication=True)

    app = httpexceptions.make_middleware(app)
    return TestApp(app)
Beispiel #6
0
def make_app(controller_klass, environ={}):
    """Creates a ``TestApp`` instance."""
    # The basic middleware:
    app = ControllerWrap(controller_klass)
    app = SetupCacheGlobal(app, environ, setup_cache=True, setup_session=True)
    app = RegistryManager(app)
    app = SessionMiddleware(app, {}, data_dir=session_dir)
    app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, 'cache'))

    # We're not going to use groups or permissions-related predicates here:
    groups_adapters = None
    permissions_adapters = None

    # Setting repoze.who up:
    cookie = AuthTktCookiePlugin('secret', 'authtkt')
    identifiers = [('cookie', cookie)]

    app = setup_auth(app,
                     groups_adapters,
                     permissions_adapters,
                     identifiers=identifiers,
                     authenticators=[],
                     challengers=[],
                     skip_authentication=True)

    app = httpexceptions.make_middleware(app)
    return TestApp(app)
Beispiel #7
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
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)
def add_auth(app, config):
    """Add authentication and authorization middleware to the ``app``."""
    groups_adapter = SqlGroupsAdapter(Group, User, DBSession)
    groups_adapter.translations['item_name'] = 'user_id'
    permission_adapter = SqlPermissionsAdapter(Permission, Group, DBSession)
    return setup_auth(app, {'sql_groups': groups_adapter}, 
        {'sql_permissions': permission_adapter}, **who_config(config))
def make_app(controller_klass, environ={}):
    """Creates a ``TestApp`` instance."""
    # The basic middleware:
    app = ControllerWrap(controller_klass)
    app = SetupCacheGlobal(app, environ, setup_cache=True, setup_session=True)
    app = RegistryManager(app)
    app = SessionMiddleware(app, {}, data_dir=session_dir)
    app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, "cache"))

    # We're not going to use groups or permissions-related predicates here:
    groups_adapters = None
    permissions_adapters = None

    # Setting repoze.who up:
    cookie = AuthTktCookiePlugin("secret", "authtkt")
    identifiers = [("cookie", cookie)]

    app = setup_auth(
        app,
        groups_adapters,
        permissions_adapters,
        identifiers=identifiers,
        authenticators=[],
        challengers=[],
        skip_authentication=True,
    )

    app = httpexceptions.make_middleware(app)
    return TestApp(app)
Beispiel #11
0
    def _make_app(self):
        r"""Create a demo app with the WSGI-like stack applied on top"""
        self.plugin = self._makeOne(realm='OAuthRealm')

        app = DemoApp()

        # Apply repoze on top
        app = setup_auth(app, group_adapters=None, permission_adapters=None,
            identifiers=[('oauth', self.plugin)],
            authenticators=[('oauth', self.plugin)],
            challengers=[('oauth', self.plugin)])

        self.app = TestApp(app)
        return self.app
Beispiel #12
0
def add_auth(app):
    """
    Add authentication and authorization middleware to the ``app``.

    :param app: The WSGI application.
    :return: The same WSGI application, with authentication and
        authorization middleware.

    People will login using HTTP Authentication and their credentials are
    kept in an ``Htpasswd`` file. For authorization through repoze.what,
    we load our groups stored in an ``Htgroups`` file and our permissions
    stored in an ``.ini`` file.

    """

    from repoze.who.plugins.basicauth import BasicAuthPlugin
    #from repoze.who.plugins.htpasswd import HTPasswdPlugin, crypt_check

    from repoze.what.middleware import setup_auth
    from repoze.what.plugins.sql import SQLPermissionsAdapter
    

    # Defining the group adapters; you may add as much as you need:
    groups = {'all_groups': SqlGroupsAdapter(Group, User, DBSession)}

    # Defining the permission adapters; you may add as much as you need:
    permissions = {'all_perms': SqlPermissionsAdapter(Permission, Group, DBSession)}

    # repoze.who identifiers; you may add as much as you need:
    basicauth = BasicAuthPlugin('Private web site')
    identifiers = [('basicauth', basicauth)]

    # repoze.who authenticators; you may add as much as you need:
    htpasswd_auth = HTPasswdPlugin('/path/to/users.htpasswd', crypt_check)
    authenticators = [('htpasswd', htpasswd_auth)]

    # repoze.who challengers; you may add as much as you need:
    challengers = [('basicauth', basicauth)]

    app_with_auth = setup_auth(
        app,
        groups,
        permissions,
        identifiers=identifiers,
        authenticators=authenticators,
        challengers=challengers)
    return app_with_auth
Beispiel #13
0
def AuthBasicMiddleware(app, conf, user_class):
    groups = GroupAdapter(user_class)
    groups = {'all_groups': groups}
    permissions = {'all_perms': PermissionAdapter(conf["couchdb.db"])}

    basicauth = BasicAuth()
    cookie = AuthTktCookiePlugin(conf['cookies.secret'])

    who_args = {}
    who_args['authenticators'] = [('accounts', Authenticator(user_class))]
    who_args['challengers'] = [('basicauth', basicauth)]
    who_args['identifiers'] = [('basicauth', basicauth), ('cookie', cookie)]
    who_args['mdproviders'] = [('accounts', MDPlugin(user_class))]
    who_args['log_stream'] = sys.stdout
    who_args['log_level'] = logging.DEBUG

    return setup_auth(app, groups, permissions, **who_args)
Beispiel #14
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)
Beispiel #15
0
def AuthBasicMiddleware(app, conf, user_class):
    groups = GroupAdapter(user_class)
    groups = {'all_groups': groups}
    permissions = {'all_perms': PermissionAdapter(conf["couchdb.db"])}

    basicauth = BasicAuth()
    cookie = AuthTktCookiePlugin(conf['cookies.secret'])

    who_args = {}
    who_args['authenticators'] = [('accounts', Authenticator(user_class))]
    who_args['challengers'] = [('basicauth', basicauth)]
    who_args['identifiers'] = [('basicauth', basicauth), ('cookie', cookie)]
    who_args['mdproviders'] = [('accounts', MDPlugin(user_class))]
    who_args['log_stream'] = sys.stdout
    who_args['log_level'] = logging.DEBUG

    return setup_auth(app, groups, permissions, **who_args)
Beispiel #16
0
def add_auth(app, config):
    """
    Add authentication and authorization middleware to the ``app``.

    :param app: The WSGI application.
    :return: The same WSGI application, with authentication and
        authorization middleware.

    People will login using HTTP Authentication and their credentials are
    kept in an ``Htpasswd`` file. For authorization through repoze.what,
    we load our groups stored in an ``Htgroups`` file and our permissions
    stored in an ``.ini`` file.

    """

    
    OAuthTwitterConsumer.consumer_key = config['oauth.consumer_key']
    OAuthTwitterConsumer.consumer_secret = config['oauth.consumer_secret']

    oauth = OAuthIdentificationPlugin(OAuthTwitterConsumer,
                                        login_handler_path = '/login',
                                        logout_handler_path = '/logout',
                                        login_form_url = '/login_form',
                                        logged_in_url = '/',
                                        logged_out_url = '/',
                                        came_from_field = 'came_from',
                                        rememberer_name='auth_tkt')

    identifiers = [('oauth', oauth), ('auth_tkt', AuthTktCookiePlugin('secret', 'auth_tkt'))]

    authenticators = [('oauth', oauth)]

    # repoze.who challengers; you may add as much as you need:
    challengers = [('oauth', oauth)]

    permissions = {}
    groups = {}

    app_with_auth = setup_auth(
        app,
        identifiers=identifiers,
        authenticators=authenticators,
        challengers=challengers,
        challenge_decider=oauth_challenge_decider)
    return app_with_auth
Beispiel #17
0
def make_app(controller_klass, environ={}):
    """Creates a `TestApp` instance."""

    app = ControllerWrap(controller_klass)
    app = SetupCacheGlobal(app, environ, setup_cache=True, setup_session=True)
    app = RegistryManager(app)
    app = SessionMiddleware(app, {}, data_dir=session_dir)
    app = CacheMiddleware(app, {}, data_dir=os.path.join(data_dir, 'cache'))

    # Setting up the source adapters:
    groups_adapters = {'my_groups': FakeGroupSourceAdapter()}
    permissions_adapters = {'my_permissions': FakePermissionSourceAdapter()}
    
    # Setting up repoze.who:
    cookie = AuthTktCookiePlugin('secret', 'authtkt')
    
    identifiers = [('cookie', cookie)]
    app = setup_auth(app, groups_adapters, permissions_adapters, 
                     identifiers=identifiers, authenticators=[],
                     challengers=[], skip_authentication=True)

    app = httpexceptions.make_middleware(app)
    return TestApp(app)
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,
                     )
def setup_sql_auth(app,
                   user_class,
                   group_class,
                   permission_class,
                   dbsession,
                   form_plugin=None,
                   form_identifies=True,
                   cookie_secret='secret',
                   cookie_name='authtkt',
                   login_url='/login',
                   login_handler='/login_handler',
                   post_login_url=None,
                   logout_handler='/logout_handler',
                   post_logout_url=None,
                   login_counter_name=None,
                   translations={},
                   **who_args):
    """
    Configure :mod:`repoze.who` and :mod:`repoze.what` with SQL-only 
    authentication and authorization, respectively.
    
    :param app: Your WSGI application.
    :param user_class: The SQLAlchemy/Elixir class for the users.
    :param group_class: The SQLAlchemy/Elixir class for the groups.
    :param permission_class: The SQLAlchemy/Elixir class for the permissions.
    :param dbsession: The SQLAlchemy/Elixir session.
    :param form_plugin: The main :mod:`repoze.who` challenger plugin; this is 
        usually a login form.
    :param form_identifies: Whether the ``form_plugin`` may and should act as
        an :mod:`repoze.who` identifier.
    :type form_identifies: bool
    :param cookie_secret: The "secret" for the AuthTktCookiePlugin.
    :type cookie_secret: str
    :param cookie_name: The name for the AuthTktCookiePlugin.
    :type cookie_name: str
    :param login_url: The URL where the login form is displayed.
    :type login_url: str
    :param login_handler: The URL where the login form is submitted.
    :type login_handler: str
    :param post_login_url: The URL/path where users should be redirected to
        after login.
    :type post_login_url: str
    :param logout_handler: The URL where the logout is handled.
    :type login_handler: str
    :param post_logout_url: The URL/path where users should be redirected to
        after logout.
    :type post_logout_url: str
    :param login_counter_name: The name of the variable in the query string
        that represents the login counter; defaults to ``__logins``.
    :type login_counter_name: str
    :param translations: The model translations.
    :type translations: dict
    :return: The WSGI application with authentication and authorization
        middleware.
    
    It configures :mod:`repoze.who` with the following plugins:
    
    * Identifiers:
    
      * :class:`repoze.who.plugins.friendlyform.FriendlyFormPlugin` as the 
        first identifier and challenger -- using ``login`` as the URL/path 
        where the login form will be displayed, ``login_handler`` as the 
        URL/path where the form will be sent and ``logout_handler`` as the 
        URL/path where the user will be logged out. The so-called *rememberer* 
        of such an identifier will be the identifier below.
        
        If ``post_login_url`` is defined, the user will be redirected to that
        page after login. Likewise, if ``post_logout_url`` is defined, the
        user will be redirected to that page after logout.
        
        You can override the 
        :class:`repoze.who.plugins.friendlyform.FriendlyFormPlugin`'s login 
        counter variable name (which defaults to ``__logins``) by defining
        ``login_counter_name``.
        
        .. tip::
        
            This plugin may be overridden with the ``form_plugin`` argument. 
            See also the ``form_identifies`` argument.
      * :class:`repoze.who.plugins.auth_tkt.AuthTktCookiePlugin`. You can
        customize the cookie name and secret using the ``cookie_name`` and
        ``cookie_secret`` arguments, respectively.
      
      Then it will append the identifiers you pass through the ``identifiers``
      keyword argument, if any.
    
    * Authenticators:
    
      * :class:`repoze.who.plugins.sa.SQLAlchemyAuthenticatorPlugin`, using
        the ``user_class`` and ``dbsession`` arguments as its user class and
        DB session, respectively.
      
      Then it will append the authenticators you pass through the 
      ``authenticators`` keyword argument, if any.
    
    * Challengers:
    
      * The same Form-based plugin used in the identifiers.
      
      Then it will append the challengers you pass through the 
      ``challengers`` keyword argument, if any.
    
    * Metadata providers:
    
      * :class:`repoze.who.plugins.sa.SQLAlchemyUserMDPlugin`, using
        the ``user_class`` and ``dbsession`` arguments as its user class and
        DB session, respectively.
      
      Then it will append the metadata providers you pass through the 
      ``mdproviders`` keyword argument, if any.
    
    Additional keyword arguments will be passed to 
    :class:`repoze.who.middleware.PluggableAuthenticationMiddleware`.
    
    .. note::
    
        If you don't want to use the groups/permissions-based authorization
        pattern, then set ``group_class`` and ``permission_class`` to ``None``.
    
    """
    plugin_translations = find_plugin_translations(translations)

    if group_class is None or permission_class is None:
        group_adapters = permission_adapters = None
    else:
        source_adapters = configure_sql_adapters(
            user_class, group_class, permission_class, dbsession,
            plugin_translations['group_adapter'],
            plugin_translations['permission_adapter'])
        group_adapters = {'sql_auth': source_adapters['group']}
        permission_adapters = {'sql_auth': source_adapters['permission']}

    # Setting the repoze.who authenticators:
    sqlauth = SQLAlchemyAuthenticatorPlugin(user_class, dbsession)
    sqlauth.translations.update(plugin_translations['authenticator'])
    if 'authenticators' not in who_args:
        who_args['authenticators'] = []
    who_args['authenticators'].append(('sqlauth', sqlauth))

    cookie = AuthTktCookiePlugin(cookie_secret, cookie_name)

    # Setting the repoze.who identifiers
    if 'identifiers' not in who_args:
        who_args['identifiers'] = []
    who_args['identifiers'].append(('cookie', cookie))

    if form_plugin is None:
        form = FriendlyFormPlugin(login_url,
                                  login_handler,
                                  post_login_url,
                                  logout_handler,
                                  post_logout_url,
                                  login_counter_name=login_counter_name,
                                  rememberer_name='cookie')
    else:
        form = form_plugin

    if form_identifies:
        who_args['identifiers'].insert(0, ('main_identifier', form))

    # Setting the repoze.who challengers:
    if 'challengers' not in who_args:
        who_args['challengers'] = []
    who_args['challengers'].append(('form', form))

    # Setting up the repoze.who mdproviders:
    sql_user_md = SQLAlchemyUserMDPlugin(user_class, dbsession)
    sql_user_md.translations.update(plugin_translations['mdprovider'])
    if 'mdproviders' not in who_args:
        who_args['mdproviders'] = []
    who_args['mdproviders'].append(('sql_user_md', sql_user_md))

    middleware = setup_auth(app, group_adapters, permission_adapters,
                            **who_args)
    return middleware
Beispiel #20
0
def setup_sql_auth(app, user_class, group_class, permission_class,
                   dbsession, form_plugin=None, form_identifies=True,
                   cookie_secret='secret', cookie_name='authtkt',
                   login_url='/login', login_handler='/login_handler',
                   post_login_url=None, logout_handler='/logout_handler',
                   post_logout_url=None, login_counter_name=None,
                   translations={}, **who_args):
    """
    Configure :mod:`repoze.who` and :mod:`repoze.what` with SQL-only 
    authentication and authorization, respectively.
    
    :param app: Your WSGI application.
    :param user_class: The SQLAlchemy/Elixir class for the users.
    :param group_class: The SQLAlchemy/Elixir class for the groups.
    :param permission_class: The SQLAlchemy/Elixir class for the permissions.
    :param dbsession: The SQLAlchemy/Elixir session.
    :param form_plugin: The main :mod:`repoze.who` challenger plugin; this is 
        usually a login form.
    :param form_identifies: Whether the ``form_plugin`` may and should act as
        an :mod:`repoze.who` identifier.
    :type form_identifies: bool
    :param cookie_secret: The "secret" for the AuthTktCookiePlugin.
    :type cookie_secret: str
    :param cookie_name: The name for the AuthTktCookiePlugin.
    :type cookie_name: str
    :param login_url: The URL where the login form is displayed.
    :type login_url: str
    :param login_handler: The URL where the login form is submitted.
    :type login_handler: str
    :param post_login_url: The URL/path where users should be redirected to
        after login.
    :type post_login_url: str
    :param logout_handler: The URL where the logout is handled.
    :type login_handler: str
    :param post_logout_url: The URL/path where users should be redirected to
        after logout.
    :type post_logout_url: str
    :param login_counter_name: The name of the variable in the query string
        that represents the login counter; defaults to ``__logins``.
    :type login_counter_name: str
    :param translations: The model translations.
    :type translations: dict
    :return: The WSGI application with authentication and authorization
        middleware.
    
    It configures :mod:`repoze.who` with the following plugins:
    
    * Identifiers:
    
      * :class:`repoze.who.plugins.friendlyform.FriendlyFormPlugin` as the 
        first identifier and challenger -- using ``login`` as the URL/path 
        where the login form will be displayed, ``login_handler`` as the 
        URL/path where the form will be sent and ``logout_handler`` as the 
        URL/path where the user will be logged out. The so-called *rememberer* 
        of such an identifier will be the identifier below.
        
        If ``post_login_url`` is defined, the user will be redirected to that
        page after login. Likewise, if ``post_logout_url`` is defined, the
        user will be redirected to that page after logout.
        
        You can override the 
        :class:`repoze.who.plugins.friendlyform.FriendlyFormPlugin`'s login 
        counter variable name (which defaults to ``__logins``) by defining
        ``login_counter_name``.
        
        .. tip::
        
            This plugin may be overridden with the ``form_plugin`` argument. 
            See also the ``form_identifies`` argument.
      * :class:`repoze.who.plugins.auth_tkt.AuthTktCookiePlugin`. You can
        customize the cookie name and secret using the ``cookie_name`` and
        ``cookie_secret`` arguments, respectively.
      
      Then it will append the identifiers you pass through the ``identifiers``
      keyword argument, if any.
    
    * Authenticators:
    
      * :class:`repoze.who.plugins.sa.SQLAlchemyAuthenticatorPlugin`, using
        the ``user_class`` and ``dbsession`` arguments as its user class and
        DB session, respectively.
      
      Then it will append the authenticators you pass through the 
      ``authenticators`` keyword argument, if any.
    
    * Challengers:
    
      * The same Form-based plugin used in the identifiers.
      
      Then it will append the challengers you pass through the 
      ``challengers`` keyword argument, if any.
    
    * Metadata providers:
    
      * :class:`repoze.who.plugins.sa.SQLAlchemyUserMDPlugin`, using
        the ``user_class`` and ``dbsession`` arguments as its user class and
        DB session, respectively.
      
      Then it will append the metadata providers you pass through the 
      ``mdproviders`` keyword argument, if any.
    
    Additional keyword arguments will be passed to 
    :class:`repoze.who.middleware.PluggableAuthenticationMiddleware`.
    
    .. note::
    
        If you don't want to use the groups/permissions-based authorization
        pattern, then set ``group_class`` and ``permission_class`` to ``None``.
    
    """
    plugin_translations = find_plugin_translations(translations)
    
    if group_class is None or permission_class is None:
        group_adapters = permission_adapters = None
    else:
        source_adapters = configure_sql_adapters(
            user_class,
            group_class,
            permission_class,
            dbsession,
            plugin_translations['group_adapter'],
            plugin_translations['permission_adapter'])
        group_adapters = {'sql_auth': source_adapters['group']}
        permission_adapters = {'sql_auth': source_adapters['permission']}
    
    # Setting the repoze.who authenticators:
    sqlauth = SQLAlchemyAuthenticatorPlugin(user_class, dbsession)
    sqlauth.translations.update(plugin_translations['authenticator'])
    if 'authenticators' not in who_args:
        who_args['authenticators'] = []
    who_args['authenticators'].append(('sqlauth', sqlauth))
    
    cookie = AuthTktCookiePlugin(cookie_secret, cookie_name)
    
    # Setting the repoze.who identifiers
    if 'identifiers' not in who_args:
        who_args['identifiers'] = []
    who_args['identifiers'].append(('cookie', cookie))
    
    if form_plugin is None:
        form = FriendlyFormPlugin(
            login_url,
            login_handler,
            post_login_url,
            logout_handler,
            post_logout_url,
            login_counter_name=login_counter_name,
            rememberer_name='cookie')
    else:
        form = form_plugin
    
    if form_identifies:
        who_args['identifiers'].insert(0, ('main_identifier', form))
    
    # Setting the repoze.who challengers:
    if 'challengers' not in who_args:
        who_args['challengers'] = []
    who_args['challengers'].append(('form', form))
    
    # Setting up the repoze.who mdproviders:
    sql_user_md = SQLAlchemyUserMDPlugin(user_class, dbsession)
    sql_user_md.translations.update(plugin_translations['mdprovider'])
    #if 'mdproviders' not in who_args:
    #    who_args['mdproviders'] = []
    #who_args['mdproviders'].append(('sql_user_md', sql_user_md))
    
    middleware = setup_auth(app, group_adapters, permission_adapters, 
                            **who_args)
    return middleware
Beispiel #21
0
    'edit': set(['older']),
    'delete': set(['male', 'older']),
}

groups = {'all_groups': DictGroupSource(group_dict)}
permissions = {'all_permissions': DictPermissionSource(permission_dict)}

cookieident = AuthTktCookiePlugin('mySuperSecretSecret')

formauth = RedirectingFormPlugin('/login',
        '/do_login',
        '/do_logout',
        rememberer_name='cookieident')
identifiers = [('formauth', formauth), ('cookieident', cookieident)]
challengers = [('formauth', formauth)]

authenticators = [('mapauth', DictAuthenticator(user_dict))]

auth_app = setup_auth(app,
        groups,
        permissions,
        identifiers=identifiers,
        authenticators=authenticators,
        challengers=challengers,
        )

# mount the application
cherrypy.tree.graft(auth_app, '/')
cherrypy.engine.start()
cherrypy.engine.block()
Beispiel #22
0
def setup_couch_auth(app, user_class=None, group_class=None, permission_class=None, 
        form_plugin=None, form_identities=True,
        cookie_secret='secret', cookie_name='authtkt', cookie_timeout=None, cookie_reissue_time=None,
        charset='utf-8', login_url='/login', login_handler='/login_handler', post_login_url=None,
        logout_handler='/logout_handler', post_logout_url=None, login_counter_name=None,
        translations=None, **who_args):
    """
    Quickly configure repoze.who and repoze.what to use CouchDB for authentication and authorization.
    With the exception of app, all parameters are options.
    :param app: The WSGI application.
    :param user_class: The class to use for the User document.
    :param group_class: The class to use for the Group document.
    :param permission_class: The class to use for the Permission document.
    :param form_plugin: The form plugin to use.  Defaults to FriendlyFormPlugin.
    :param form_identities: Whether or not to use the form plugin as an identity plugin.
    :param cookie_secret: The cookie secret to use for the authtkt plugin.
    :param cookie_name: The name of the cookie for the authtkt plugin.
    :param cookie_timeout: The cookie timeout for the authtkt plugin.
    :param cookie_reissue_time: How often to reissue the cookie for the authtkt plugin.
    :param charset: The character set for the authtkt plugin.
    :param login_url: The page that will be used to display the login form.
    :param login_handler: The URL where repoze.who will process logins.
    :param post_login_url: The URL to redirect to after login.
    :param logout_handler: The URL where repoze.who will process logouts.
    :param post_logout_url: The URL to redirect to after logout.
    :param login_counter_name: The name to use for the login counter.
    :param translations: The translations used to map CouchDB documents inside the wrapper classes.
    :param who_args: Additional configuration arguments to pass to repoze.who.
    :return: The modified WSGI application.
    """
    t11 = default_translations
    if translations is not None:
        for k, v in translations.iteritems():
            t11[k] = v

    t11['user_class'] = User if user_class is None else user_class
    t11['group_class'] = Group if group_class is None else group_class
    t11['perm_class'] = Permission if permission_class is None else permission_class

    if form_plugin is None:
        form_plugin = FriendlyFormPlugin(login_url, login_handler, post_login_url, logout_handler, post_logout_url,
            login_counter_name=login_counter_name, rememberer_name='cookie', charset=charset)
    group_adapters = {'couch_auth': GroupAdapter(t11)}
    perm_adapters = {'couch_auth': PermissionAdapter(t11)}
    authenticator = ('couch_auth', AuthenticatorPlugin(t11))
    metadata = ('couch_auth', MetadataPlugin(t11))
    identifier = ('cookie', AuthTktCookiePlugin(cookie_secret, cookie_name, timeout=cookie_timeout, reissue_time=cookie_reissue_time))
    challenger = ('form', form_plugin)
    
    if 'authenticators' not in who_args:
        who_args['authenticators'] = []
    if 'identifiers' not in who_args:
        who_args['identifiers'] = []
    if 'challengers' not in who_args:
        who_args['challengers'] = []
    if 'mdproviders' not in who_args:
        who_args['mdproviders'] = []

    if form_identities:
        who_args['identifiers'].insert(0, ('main_identifier', form_plugin))
    who_args['authenticators'].append(authenticator)
    who_args['mdproviders'].append(metadata)
    who_args['identifiers'].append(identifier)
    who_args['challengers'].append(challenger)

    return setup_auth(app, group_adapters, perm_adapters, **who_args)
def add_auth(app, sitename, sessionname, sessionsecret, password_file, groups_file, permissions_file):
    """
    Add authentication and authorization middleware to the ``app``.

    :param app: The WSGI application.
    :param sitename: the site name used in basic auth box.
    :param sessionname: basic auth name and cookie name.
    :param sessionsecret: unique secret string used to protect sessions.
    :param groups_file: the ini file source for the groups information.
    :param passwd_file: the ini file source for the permission information.
    :return: The same WSGI application, with authentication and
        authorization middleware.
        
    """
    site = sitename
    cookie_secret = sessionsecret 
    cookie_name = 'authtkt'

    login_url = url_for('/login')
    login_handler = url_for('/login_handler')
    post_login_url = None
    logout_handler = url_for('/logout_handler')
    post_logout_url = None
    login_counter_name = None

    get_log().info("add_auth: adding user/group/permission file based setup.")

    if not os.path.isfile(password_file):
        raise ValueError("Unable to find password file '%s'!" % password_file)
    else:
        user_data_file = os.path.abspath(password_file)

    if not os.path.isfile(groups_file):
        raise ValueError("Unable to find groups file '%s'!" % groups_file)
    else:
        groups = os.path.abspath(groups_file)
        
    if not os.path.isfile(permissions_file):
        raise ValueError("Unable to find password file '%s'!" % permissions_file)
    else:
        permissions = os.path.abspath(permissions_file)
    
    basicauth = BasicAuthPlugin(site)

    # Recover the User details and load it for the CSV repoze plugin to handle:
    fd = open(user_data_file, 'r')
    user_data = fd.read()
    fd.close()
    passauth_and_metadata = plain.PlainAuthenticatorMetadataProvider(user_data)
                   
    form = FriendlyFormPlugin(
        login_url,
        login_handler,
        post_login_url,
        logout_handler,
        post_logout_url,
        login_counter_name=login_counter_name,
        rememberer_name='cookie'
    )

    cookie = AuthTktCookiePlugin(cookie_secret, cookie_name)

    identifiers = [('main_identifier', form), ('basicauth', basicauth), ('cookie', cookie)]

    challengers = [('form', form), ('basicauth', basicauth)]

    authenticators = [('htpasswd', passauth_and_metadata)]

    mdproviders = [('simplemeta', passauth_and_metadata)]

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

    app_with_auth = setup_auth(
        app = app,
        group_adapters = groups,
        permission_adapters = permissions, 
        identifiers = identifiers, 
        authenticators = authenticators,
        challengers = challengers, 
        mdproviders = mdproviders, 
        log_level = logging.DEBUG
    )

    get_log().info("add_auth: user/group/permission setup OK.")
        
    return app_with_auth
Beispiel #24
0
def setup_sql_auth(app, user_class, group_class, permission_class,
                   dbsession, form_plugin=None, form_identifies=True,
                   cookie_secret='secret', cookie_name='authtkt',
                   login_url='/login', login_handler='/login_handler',
                   post_login_url=None, logout_handler='/logout_handler',
                   post_logout_url=None, login_counter_name=None,
                   translations={}, cookie_timeout=None,
                   cookie_reissue_time=None, charset="iso-8859-1",
                   use_default_authenticator=True,
                   **who_args):
    """
    Configure :mod:`repoze.who` and :mod:`repoze.what` with SQL-only 
    authentication and authorization, respectively.
    
    :param app: Your WSGI application.
    :param user_class: The SQLAlchemy/Elixir class for the users.
    :param group_class: The SQLAlchemy/Elixir class for the groups.
    :param permission_class: The SQLAlchemy/Elixir class for the permissions.
    :param dbsession: The SQLAlchemy/Elixir session.
    :param form_plugin: The main :mod:`repoze.who` challenger plugin; this is 
        usually a login form.
    :param form_identifies: Whether the ``form_plugin`` may and should act as
        an :mod:`repoze.who` identifier.
    :type form_identifies: bool
    :param cookie_secret: The "secret" for the AuthTktCookiePlugin (**set a
        custom one!**).
    :type cookie_secret: str
    :param cookie_name: The name for the AuthTktCookiePlugin.
    :type cookie_name: str
    :param login_url: The URL where the login form is displayed.
    :type login_url: str
    :param login_handler: The URL where the login form is submitted.
    :type login_handler: str
    :param post_login_url: The URL/path where users should be redirected to
        after login.
    :type post_login_url: str
    :param logout_handler: The URL where the logout is handled.
    :type login_handler: str
    :param post_logout_url: The URL/path where users should be redirected to
        after logout.
    :type post_logout_url: str
    :param login_counter_name: The name of the variable in the query string
        that represents the login counter; defaults to ``__logins``.
    :type login_counter_name: str
    :param translations: The model translations.
    :type translations: dict
    :param cookie_timeout: The time (in seconds) during which the session cookie
        would be valid.
    :type cookie_timeout: :class:`int`
    :param cookie_reissue_time: How often should the session cookie be reissued
        (in seconds); must be less than ``timeout``.
    :type cookie_reissue_time: :class:`int`
    :param use_default_authenticator: Whether the default SQL authenticator
        should be used.
    :type use_default_authenticator: :class:`bool`
    :return: The WSGI application with authentication and authorization
        middleware.
    
    It configures :mod:`repoze.who` with the following plugins:
    
    * Identifiers:
    
      * :class:`repoze.who.plugins.friendlyform.FriendlyFormPlugin` as the 
        first identifier and challenger -- using ``login`` as the URL/path 
        where the login form will be displayed, ``login_handler`` as the 
        URL/path where the form will be sent and ``logout_handler`` as the 
        URL/path where the user will be logged out. The so-called *rememberer* 
        of such an identifier will be the identifier below.
        
        If ``post_login_url`` is defined, the user will be redirected to that
        page after login. Likewise, if ``post_logout_url`` is defined, the
        user will be redirected to that page after logout.
        
        You can override the 
        :class:`repoze.who.plugins.friendlyform.FriendlyFormPlugin`'s login 
        counter variable name (which defaults to ``__logins``) by defining
        ``login_counter_name``.
        
        .. tip::
        
            This plugin may be overridden with the ``form_plugin`` argument. 
            See also the ``form_identifies`` argument.
      * :class:`repoze.who.plugins.auth_tkt.AuthTktCookiePlugin`. You can
        customize the cookie name and secret using the ``cookie_name`` and
        ``cookie_secret`` arguments, respectively.
      
      Then it will append the identifiers you pass through the ``identifiers``
      keyword argument, if any.
    
    * Authenticators:
    
      * :class:`repoze.who.plugins.sa.SQLAlchemyAuthenticatorPlugin` (unless
        ``use_default_authenticator`` is ``False``), using the ``user_class``
        and ``dbsession`` arguments as its user class and DB session,
        respectively.
      
      Then it will be appended to the authenticators you pass through the 
      ``authenticators`` keyword argument, if any. The default authenticator
      would have the lowest precedence.
    
    * Challengers:
    
      * The same Form-based plugin used in the identifiers.
      
      Then it will append the challengers you pass through the 
      ``challengers`` keyword argument, if any.
    
    * Metadata providers:
    
      * :class:`repoze.who.plugins.sa.SQLAlchemyUserMDPlugin`, using
        the ``user_class`` and ``dbsession`` arguments as its user class and
        DB session, respectively.
      
      Then it will append the metadata providers you pass through the 
      ``mdproviders`` keyword argument, if any.
    
    The ``charset`` is passed to any component which needs to decode/encode
    data to/from the user. At present, only
    :class:`~repoze.who.plugins.friendlyform.FriendlyFormPlugin` does.
    
    Additional keyword arguments will be passed to 
    :class:`repoze.who.middleware.PluggableAuthenticationMiddleware`.
    
    .. warning::
    
        It's very important to set a custom ``cookie_secret``! It's the key to
        encrypt *and* decrypt the cookies, so you shouldn't leave the default
        one.
    
    .. note::
    
        If you don't want to use the groups/permissions-based authorization
        pattern, then set ``group_class`` and ``permission_class`` to ``None``.
    
    .. versionchanged:: 1.0.5
        Introduced the ``cookie_timeout`` and ``cookie_reissue_time`` arguments.
    
    .. versionchanged:: 1.0.6
        Introduced the ``charset`` argument.
    
    .. versionchanged:: 1.0.8
        Introduced the ``use_default_authenticator`` argument.
    
    """
    plugin_translations = find_plugin_translations(translations)
    source_adapters = configure_sql_adapters(
            user_class,
            group_class,
            permission_class,
            dbsession,
            plugin_translations['group_adapter'],
            plugin_translations['permission_adapter'])

    group_adapters= {}
    group_adapter = source_adapters.get('group')
    if group_adapter:
        group_adapters = {'sql_auth': group_adapter}

    permission_adapters = {}
    permission_adapter = source_adapters.get('permission')
    if permission_adapter:
        permission_adapters = {'sql_auth': permission_adapter}
    
    # Setting the repoze.who authenticators:
    if 'authenticators' not in who_args:
        who_args['authenticators'] = []
        
    if use_default_authenticator:
        sqlauth = SQLAlchemyAuthenticatorPlugin(user_class, dbsession)
        sqlauth.translations.update(plugin_translations['authenticator'])
        who_args['authenticators'].append(('sqlauth', sqlauth))
    
    cookie = AuthTktCookiePlugin(cookie_secret, cookie_name,
                                 timeout=cookie_timeout,
                                 reissue_time=cookie_reissue_time)
    
    # Setting the repoze.who identifiers
    if 'identifiers' not in who_args:
        who_args['identifiers'] = []
    who_args['identifiers'].append(('cookie', cookie))
    
    if form_plugin is None:
        form = FriendlyFormPlugin(
            login_url,
            login_handler,
            post_login_url,
            logout_handler,
            post_logout_url,
            login_counter_name=login_counter_name,
            rememberer_name='cookie',
            charset=charset,
            )
    else:
        form = form_plugin
    
    if form_identifies:
        who_args['identifiers'].insert(0, ('main_identifier', form))
    
    # Setting the repoze.who challengers:
    if 'challengers' not in who_args:
        who_args['challengers'] = []
    who_args['challengers'].append(('form', form))
    
    # Setting up the repoze.who mdproviders:
    sql_user_md = SQLAlchemyUserMDPlugin(user_class, dbsession)
    sql_user_md.translations.update(plugin_translations['mdprovider'])
    if 'mdproviders' not in who_args:
        who_args['mdproviders'] = []
    who_args['mdproviders'].append(('sql_user_md', sql_user_md))
    
    # Including logging
    log_file = who_args.pop('log_file', None)
    if log_file is not None:
        if log_file.lower() == 'stdout':
            log_stream = sys.stdout
        elif log_file.lower() == 'stderr':
            log_stream = sys.stderr
        else:
            log_stream = open(log_file, 'wb')
        who_args['log_stream'] = log_stream

    log_level = who_args.get('log_level', None)
    if log_level is None:
        log_level = logging.INFO
    else:
        log_level = _LEVELS[log_level.lower()]
    who_args['log_level'] = log_level

    middleware = setup_auth(app, group_adapters, permission_adapters, 
                            **who_args)
    return middleware
def add_auth(app, config):
    """
    Wrap authentication and authorization middleware around the ``app``.

    We're going to define post-login and post-logout pages
    to do some cool things.

    TODO Create a new validation authenticator and challenger that support
    username, password, company

    For documentation on repoze.who and repoze.what, see
    http://docs.repoze.org/who/1.0/
    """
    log.debug("add_auth()")

    log.debug("Configuring repoze.who")
    
    form_plugin = form.make_plugin(
            config.get('repoze.who.login_form_qs'),
            rememberer_name='auth_tkt',
            formcallable='example_app.lib.auth.auth:display_login_form'
            )

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

    auth_tkt_plugin = auth_tkt.make_plugin(
            secret=config.get('repoze.who.cookie.secret'),
            secretfile=config.get('repoze.who.cookie.secretfile'),
            cookie_name=config.get('repoze.who.cookie.cookie_name'),
            secure=config.get('repoze.who.cookie.secure'),
            include_ip=config.get('repoze.who.cookie.include_ip'),
            timeout=config.get('repoze.who.cookie.timeout'),
            reissue_time=config.get('repoze.who.cookie.reissue_time'),
            userid_checker='example_app.lib.auth.auth:userid_checker'
            )
    

    sa_user_company_auth_plugin = sa_user_company.make_plugin(User, Company,
            Session)

    sa_userid_auth_plugin = sa_userid.make_authenticator_plugin(User, Session)

    sa_user_mdprovider_plugin = sa_userid.make_metadata_plugin(User, Session)

    identifiers = [('form', form_plugin), ('auth_tkt', auth_tkt_plugin)]
    authenticators = [('sa_user_compan_auth', sa_user_company_auth_plugin),
            ('sa_userid_auth', sa_userid_auth_plugin)]
    challengers = [('form', form_plugin)]
    mdproviders = [('sa_user', sa_user_mdprovider_plugin)]
   
    from repoze.who.classifiers import default_request_classifier
    from repoze.who.classifiers import default_challenge_decider

    log.debug("Configuring repoze.what")

    acl_plugin = adapters.configure_sql_adapters(
            User, AclGroup, AclPermission, Session,
            group_translations={'section_name': 'id',
                'items': 'users',
                'item_name': 'id',
                'sections': 'groups'},
            permission_translations={'section_name': 'id',
                'items': 'groups',
                'item_name': 'id',
                'sections': 'permissions'}
            )

    log.debug("Initializing middleware: repoze.what and repoze.who")

    return setup_auth(
            app,
            {'all_groups': acl_plugin['group']},
            {'all_permissions': acl_plugin['permission']},
            identifiers=identifiers,
            challengers=challengers,
            authenticators=authenticators,
            mdproviders=mdproviders,
            classifier=default_request_classifier,
            challenge_decider=default_challenge_decider,
            log_stream=log,
            log_level=logging.DEBUG
            )
Beispiel #26
0
def add_auth(app, site_name, cookie_name, cookie_secret, login_url,
             login_handler_url, authenticators, mdproviders, groups,
             permissions):
    """
    Add authentication and authorization middleware to the ``app``.

    :param app: The WSGI application.
    :param site_name: the site name used in basic auth box.
    :param cookie_name: basic auth name and cookie name.
    :param cookie_secret: unique secret string used to protect sessions.
    :param login_url: the url for the login page
    :param login_handler_url: the url for the login handler
    :param authenticators: list of authenticator plugins
    :param mdproviders: list of mdprovider plugins
    :param groups: list of groups plugins
    :param permissions: list of permissions plugins
    :return: The same WSGI application, with authentication and
        authorization middleware.

    """

    get_log().info("add_auth: intialising Repoze")

    if not authenticators:
        raise ValueError("No authenticators provided")
    if not mdproviders:
        raise ValueError("No mdproviders provided")
    if not groups:
        raise ValueError("No groups provided")
    if not permissions:
        raise ValueError("No permissions provided")

    # If we ever change default behavior for challengers and identifiers,
    # move these to the above function
    logout_handler = None
    form = RedirectingFormPlugin(
        login_url,
        login_handler_url,
        logout_handler,
        rememberer_name='cookie',
    )

    cookie = AuthTktCookiePlugin(cookie_secret, cookie_name)

    #identifiers = [('main_identifier', form), ('basicauth', basicauth),\
    #   ('cookie', cookie)]
    #identifiers = [('basicauth', basicauth), ('cookie', cookie)]
    identifiers = [('form', form), ('cookie', cookie)]

    #challengers = [('form', form), ('basicauth', basicauth)]
    #challengers = [('basicauth', basicauth)]
    challengers = [('form', form)]

    #get_log().info(dict(groups))
    #get_log().info(    dict(permissions))
    #get_log().info(    identifiers)
    #get_log().info(    authenticators)
    #get_log().info(    challengers )
    #get_log().info(    mdproviders)
    app_with_auth = setup_auth(
        app=app,
        # # why these are dicts where all the other are lists...
        group_adapters=dict(groups),
        permission_adapters=dict(permissions),
        identifiers=identifiers,
        authenticators=authenticators,
        challengers=challengers,
        mdproviders=mdproviders,
        log_level=logging.DEBUG
    )

    get_log().info("add_auth: user/group/permission setup OK.")

    return app_with_auth
Beispiel #27
0
def make_app(global_conf, full_stack=True, **app_conf):
    """
    Set munkireport up with the settings found in the PasteDeploy configuration
    file used.
    
    :param global_conf: The global settings for munkireport (those
        defined under the ``[DEFAULT]`` section).
    :type global_conf: dict
    :param full_stack: Should the whole TG2 stack be set up?
    :type full_stack: str or bool
    :return: The munkireport application with all the relevant middleware
        loaded.
    
    This is the PasteDeploy factory for the munkireport application.
    
    ``app_conf`` contains all the application-specific settings (those defined
    under ``[app:main]``.
    
   
    """
    app = make_base_app(global_conf, full_stack=True, **app_conf)
    
    # Wrap your base TurboGears 2 application with custom middleware here
    
    # Initialize repoze.what plugins.
    groups_path = os.path.join(global_conf.get("appsupport_dir"), "groups.ini")
    groups = {
        "ini_groups": INIGroupAdapter(app_conf.get("what.groups_file", groups_path)),
        "dscl_groups": MacOSXGroupAdapter()
    }
    permissions_path = os.path.join(global_conf.get("appsupport_dir"), "permissions.ini")
    permissions = {
        "ini_permissions": INIPermissionsAdapter(app_conf.get("what.permissions_file", permissions_path))
    }
    
    # Initialize repoze.who plugins.
    friendlyform = FriendlyFormPlugin(
        "/login",
        "/login_handler",
        None,
        "/logout_handler",
        None,
        "auth_tkt",
        login_counter_name=None
    )
    friendlyform.classifications = {
        IIdentifier: ['browser'],
        IChallenger: ['browser']
    }
    auth_tkt = AuthTktPlugin(secret=app_conf["beaker.session.secret"])
    macosx_authenticator = MacOSXAuthenticator()
    macosx_metadataprovider = MacOSXMetadataProvider()
    file_authenticator = FileAuthenticator()
    file_metadataprovider = FileMetadataProvider()
    
    # Configuration for repoze.who.
    identifiers = [
        ('friendlyform', friendlyform),
        ('auth_tkt', auth_tkt)
    ]
    authenticators = [
        ('macosx_authenticator', macosx_authenticator),
        ('file_authenticator', file_authenticator)
    ]
    challengers = [
        ('friendlyform', friendlyform)
    ]
    mdproviders = [
        ('macosx_metadataprovider', macosx_metadataprovider),
        ('file_metadataprovider', file_metadataprovider)
    ]
    
    # Setup authentication and authorization through repoze.what.
    app = setup_auth(
        app,
        groups,
        permissions,
        identifiers=identifiers,
        authenticators=authenticators,
        challengers=challengers,
        mdproviders=mdproviders,
        #log_stream=sys.stdout,
        #log_level=logging.DEBUG
    )
    
    return app