示例#1
0
def add_auth(app, config):
    """Add authentication and authorization middleware to the ``app``."""
    return setup_sql_auth(
        app,
        User,
        Group,
        Permission,
        DBSession,
        login_url=login_form_url,
        # XXX: These two URLs are intercepted by the sql_auth middleware
        login_handler=login_handler_url,
        logout_handler=logout_handler_url,

        # You may optionally define a page where you want users to be
        # redirected to on login:
        post_login_url=post_login_url,

        # You may optionally define a page where you want users to be
        # redirected to on logout:
        post_logout_url=post_logout_url,

        # Hook into the auth process to read the session ID out of the POST
        # vars during flash upload requests.
        classifier=classifier_for_flash_uploads,

        # override this if you would like to provide a different who plugin for
        # managing login and logout of your application
        form_plugin=None,

        # The salt used to encrypt auth cookie data. This value must be unique
        # to each deployment so it comes from the INI config file and is
        # randomly generated when you run paster make-config
        cookie_secret=config['sa_auth.cookie_secret'])
示例#2
0
文件: auth.py 项目: 86me/mediacore
def add_auth(app, config):
    """Add authentication and authorization middleware to the ``app``."""
    return setup_sql_auth(
        app, User, Group, Permission, DBSession,

        # NOTE: all four URLs are defined in mediacore.config.routing
        # XXX: The first two URLs are intercepted by the sql_auth middleware
        login_handler = '/login/submit',
        logout_handler = '/logout',

        # You may optionally define a page where you want users to be
        # redirected to on login:
        post_login_url = '/login/continue',

        # You may optionally define a page where you want users to be
        # redirected to on logout:
        post_logout_url = '/logout/continue',

        # Hook into the auth process to read the session ID out of the POST
        # vars during flash upload requests.
        classifier = classifier_for_flash_uploads,

        # override this if you would like to provide a different who plugin for
        # managing login and logout of your application
        form_plugin = None,

        # The salt used to encrypt auth cookie data. This value must be unique
        # to each deployment so it comes from the INI config file and is
        # randomly generated when you run paster make-config
        cookie_secret = config['sa_auth.cookie_secret']
    )
示例#3
0
def AuthMiddleware(app):
    """
    Add authentication and authorization middleware to the ``app``.
    """
    # url_for mustn't be used here because AuthMiddleware is built once at startup,
    # url path can be reconstructed only on http requests (based on environ)
    basic_redirect_form = BasicRedirectFormPlugin(login_form_url="/signin",
                                                  login_handler_path="/login",
                                                  post_login_url="/",
                                                  logout_handler_path="/logout",
                                                  post_logout_url="/signin",
                                                  rememberer_name="cookie")

    return setup_sql_auth(
            app,
            user_class = model.User,
            group_class = model.Group,
            permission_class = model.Permission,
            dbsession = model.meta.Session,
            form_plugin = basic_redirect_form,
            cookie_secret = config['cookie_secret'],
            translations = {
                'user_name': 'login',
                'users': 'users',
                'group_name': 'name',
                'groups': 'groups',
                'permission_name': 'name',
                'permissions': 'permissions',
                'validate_password': '******'},
            )
    def add_auth_middleware(self, app, skip_authentication):
        """
        Configure authentication and authorization.

        :param app: The TG2 application.
        :param skip_authentication: Should authentication be skipped if
            explicitly requested? (used by repoze.who-testutil)
        :type skip_authentication: bool

        """
        from repoze.what.plugins.quickstart import setup_sql_auth
        from repoze.what.plugins.pylonshq import booleanize_predicates

        # Predicates booleanized:
        booleanize_predicates()

        # Configuring auth logging:
        if 'log_stream' not in self.sa_auth:
            self.sa_auth['log_stream'] = logging.getLogger('auth')

        # Removing keywords not used by repoze.who:
        auth_args = copy(self.sa_auth)
        if 'sa_auth' in config:
            auth_args.update(config.sa_auth)
        if 'password_encryption_method' in auth_args:
            del auth_args['password_encryption_method']
        if not skip_authentication:
            if not 'cookie_secret' in auth_args.keys():
                msg = "base_config.sa_auth.cookie_secret is required "\
                "you must define it in app_cfg.py or set "\
                "sa_auth.cookie_secret in development.ini"
                raise TGConfigError(msg)
        app = setup_sql_auth(app, skip_authentication=skip_authentication,
                             **auth_args)
        return app
示例#5
0
文件: auth.py 项目: yjacolin/Studio
def AuthMiddleware(app):
    """
    Add authentication and authorization middleware to the ``app``.
    """
    # url_for mustn't be used here because AuthMiddleware is built once at startup,
    # url path can be reconstructed only on http requests (based on environ)
    basic_redirect_form = BasicRedirectFormPlugin(
        login_form_url="/signin",
        login_handler_path="/login",
        post_login_url="/",
        logout_handler_path="/logout",
        post_logout_url="/signin",
        rememberer_name="cookie",
    )

    return setup_sql_auth(
        app,
        user_class=model.User,
        group_class=model.Group,
        permission_class=model.Permission,
        dbsession=model.meta.Session,
        form_plugin=basic_redirect_form,
        cookie_secret=config["cookie_secret"],
        translations={
            "user_name": "login",
            "users": "users",
            "group_name": "name",
            "groups": "groups",
            "permission_name": "name",
            "permissions": "permissions",
            "validate_password": "******",
        },
    )
示例#6
0
def add_auth(app, config):
    """
    Add authentication and authorization middleware to the ``app``.

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

    """
    # we need to provide repoze.what with translations as described here:
    # http://what.repoze.org/docs/plugins/quickstart/
    return setup_sql_auth(app,
                          User,
                          Group,
                          Permission,
                          Session,
                          login_url='/admin/account/login',
                          post_login_url='/admin',
                          post_logout_url='/admin/account/login',
                          login_handler='/admin/account/login_handler',
                          logout_handler='/admin/account/logout',
                          cookie_secret=config.get('cookie_secret'),
                          translations={
                              'user_name': 'username',
                              'group_name': 'name',
                              'permission_name': 'name',
                          })
示例#7
0
def add_auth_from_config(app, global_conf, config_file):
    """
    Add authentication and authorization middleware.
    
    :param app: The WSGI application to be secured.
    :param global_conf: The PasteDeploy global configuration.
    :type global_conf: dict
    :param config_file: The path to the configuration file for the quickstart
        plugin.
    :type config_file: basestring
    
    ``global_conf`` is not used at present, but could be used in the future.
    
    :raises repoze.what.plugins.quickstart.MissingOptionError: If one of the 
        mandatory options (``dbsession``, ``user_class``, ``group_class``, 
        ``permission_class``) is missing.
    :raises repoze.what.plugins.quickstart.BadOptionError: If an option has an
        invalid value.
    
    """
    auth_config = _AuthConf(config_file)
    auth_config.find_options()

    # Validating the configuration:
    if "dbsession" not in auth_config.options:
        raise MissingOptionError("The database session is missing")
    elif "user_class" not in auth_config.options:
        raise MissingOptionError("The SQLAlchemy-based user class is missing")
    elif "group_class" not in auth_config.options:
        raise MissingOptionError("The SQLAlchemy-based group class is missing")
    elif "permission_class" not in auth_config.options:
        raise MissingOptionError("The SQLAlchemy-based permission class is " "missing")

    app_with_auth = setup_sql_auth(app, **auth_config.options)
    return app_with_auth
示例#8
0
    def add_auth_middleware(self, app, skip_authentication):
        """
        Configure authentication and authorization.
        
        :param app: The TG2 application.
        :param skip_authentication: Should authentication be skipped if
            explicitly requested? (used by repoze.who-testutil)
        :type skip_authentication: bool
        
        """
        from repoze.what.plugins.quickstart import setup_sql_auth
        from repoze.what.plugins.pylonshq import booleanize_predicates

        # Predicates booleanized:
        booleanize_predicates()

        # Configuring auth logging:
        if 'log_stream' not in self.sa_auth:
            self.sa_auth['log_stream'] = logging.getLogger('auth')

        # Removing keywords not used by repoze.who:
        auth_args = copy(self.sa_auth)
        if 'password_encryption_method' in auth_args:
            del auth_args['password_encryption_method']
        if not skip_authentication:
            if not 'cookie_secret' in auth_args.keys():
                msg = "base_config.sa_auth.cookie_secret is required " \
                "you must define it in app_cfg.py or set " \
                "sa_auth.cookie_secret in development.ini"
                print msg
                raise ConfigurationError(message=msg)
        app = setup_sql_auth(app,
                             skip_authentication=skip_authentication,
                             **auth_args)
        return app
示例#9
0
def add_auth(app):
    """Add authentication and authorization middleware to the ``app``.

    We're going to define post-login and post-logout pages to do some cool things.
    """
    return setup_sql_auth(app, User, Group, Permission, Session,
                          logout_handler='/logout',
                          post_login_url='/post_login',
                          post_logout_url='/post_logout')
 def test_timeout(self):
     """AuthTktCookiePlugin's timeout and reissue_time must be supported"""
     app = setup_sql_auth(MockApplication(), User, None, None, DBSession,
                          cookie_timeout=2, cookie_reissue_time=1)
     self._in_registry(app, "cookie", AuthTktCookiePlugin)
     identifier = app.name_registry['cookie']
     # Making sure the arguments were passed:
     self.assertEqual(identifier.timeout, 2)
     self.assertEqual(identifier.reissue_time, 1)
示例#11
0
def add_auth(app):
    """ Add authentication and authorization middleware to the ``app``.

    Post-login and post-logout pages setup.
    """
    return setup_sql_auth(app, User, Group, Permission, Session,
                          logout_handler='/logout',
                          post_login_url='/post_login',
                          post_logout_url='/post_logout',
                          charset='utf-8')
示例#12
0
 def test_timeout(self):
     """AuthTktCookiePlugin's timeout and reissue_time must be supported"""
     app = setup_sql_auth(MockApplication(),
                          User,
                          None,
                          None,
                          DBSession,
                          cookie_timeout=2,
                          cookie_reissue_time=1)
     self._in_registry(app, "cookie", AuthTktCookiePlugin)
     identifier = app.name_registry['cookie']
     # Making sure the arguments were passed:
     self.assertEqual(identifier.timeout, 2)
     self.assertEqual(identifier.reissue_time, 1)
 def test_no_groups_or_permissions(self):
     """Groups and permissions must be optional"""
     app = setup_sql_auth(MockApplication(), User, None, None, DBSession)
     self._in_registry(app, 'authorization_md', AuthorizationMetadata)
     # Testing that in fact it works:
     environ = {}
     identity = {'repoze.who.userid': u'rms'}
     md = app.name_registry['authorization_md']
     md.add_metadata(environ, identity)
     expected_credentials = {
         'repoze.what.userid': u'rms',
         'groups': tuple(),
         'permissions': tuple()}
     self.assertEqual(expected_credentials, 
                      environ['repoze.what.credentials'])
示例#14
0
 def test_no_groups_or_permissions(self):
     """Groups and permissions must be optional"""
     app = setup_sql_auth(MockApplication(), User, None, None, DBSession)
     self._in_registry(app, 'authorization_md', AuthorizationMetadata)
     # Testing that in fact it works:
     environ = {}
     identity = {'repoze.who.userid': u'rms'}
     md = app.name_registry['authorization_md']
     md.add_metadata(environ, identity)
     expected_credentials = {
         'repoze.what.userid': u'rms',
         'groups': tuple(),
         'permissions': tuple()
     }
     self.assertEqual(expected_credentials,
                      environ['repoze.what.credentials'])
示例#15
0
def add_auth(app, config):
   return setup_sql_auth(
       app, AuthUser, AuthGroup, AuthPermission, Session,
       login_handler = '/login/submit',
       logout_handler = '/logout',
       post_login_url = '/login/continue',
       post_logout_url = '/logout/continue',
       cookie_secret = 'my_secret_word',
       translations = {
           'user_name' : 'username',
           'groups' : 'auth_groups',
           'group_name' : 'name',
           'permissions' : 'auth_permissions',
           'permission_name' : 'name'
       }
   )
示例#16
0
def add_auth(app, config):
    return setup_sql_auth(app,
                          AuthUser,
                          AuthGroup,
                          AuthPermission,
                          Session,
                          login_handler='/login/submit',
                          logout_handler='/logout',
                          post_login_url='/login/continue',
                          post_logout_url='/logout/continue',
                          cookie_secret='my_secret_word',
                          translations={
                              'user_name': 'username',
                              'groups': 'auth_groups',
                              'group_name': 'name',
                              'permissions': 'auth_permissions',
                              'permission_name': 'name'
                          })
示例#17
0
def add_auth(app, skip_authentication):
    """
    Add auth middleware to the ``app`` application.
    
    :param app: The WSGI application.
    :param skip_authentication: Should authentication be skipped while testing
        protected areas? (officially recommended)
    
    """
    
    securedapp = setup_sql_auth(app, User, Group, Permission, meta.Session_post,
                                logout_handler='/logout',
                                post_login_url='/post_login',
                                post_logout_url='/post_logout',
                                log_level="info", 
                                skip_authentication=skip_authentication)
    
    return securedapp
示例#18
0
文件: auth.py 项目: zeroshade/lazydm
def add_auth(app, config):
    """
    Add authentication middleware to app
    We're going to define post-login and post-logout pages
    to do some cool things.

    """
    # we need to provide repoze.what with translations as described here:
    # http://what.repoze.org/docs/plugins/quickstart/
    return setup_sql_auth(app, User, Group, Permission, Session,
                login_url='/login/',
                post_login_url='/login/continue/',
                post_logout_url='/logout/continue/',
                login_handler='/login/submit/',
                logout_handler='/logout/',
                cookie_secret=config.get('cookie_secret'),
                translations={
                    'user_name': 'username',
                    'group_name': 'name',
                    'permission_name': 'name',
                })
示例#19
0
文件: __init__.py 项目: kuba/SIS
def add_auth(app, app_conf, prefix='auth.'):
    """
    Add authentication and authorization middleware to the ``app``.

    :param app_conf: The application's local configuration. Normally specified
                     in the [app:<name>] section of the Paste ini file
                     (where <name> defaults to main).

    :param prefix: Prefix for the config related to the auth.
    :type prefix: :class:`str`

    """
    # Cookie form plugin
    form_plugin = make_redirecting_plugin(
                    login_form_path='/login',
                    login_handler_path='/login_handler',
                    logout_handler_path='/logout',
                    rememberer_name='cookie',
            )
    if prefix+'cookie_secret' not in app_conf:
        raise Exception("Missing config option: %s" % prefix+'cookie_secret')

    cookie_secret = app_conf.get(prefix+'cookie_secret')
    cookie_timeout = Int.to_python(app_conf.get(prefix+'cookie_timeout'))
    cookie_reissue_time = Int.to_python(app_conf.get(prefix+'cookie_reissue_time'))

    # Perform type conversion, sice timeout and reisue_time must be int or None
    if cookie_timeout is not None:
        cookie_timeout = int(cookie_timeout)
    if cookie_reissue_time is not None:
        cookie_reissue_time = int(cookie_reissue_time)

    return setup_sql_auth(app, AuthUser, AuthGroup, AuthPermission, Session,
                          form_plugin=form_plugin,
                          cookie_secret=cookie_secret,
                          cookie_timeout=cookie_timeout,
                          cookie_reissue_time=cookie_reissue_time)
示例#20
0
def add_auth_from_config(app, global_conf, config_file):
    """
    Add authentication and authorization middleware.
    
    :param app: The WSGI application to be secured.
    :param global_conf: The PasteDeploy global configuration.
    :type global_conf: dict
    :param config_file: The path to the configuration file for the quickstart
        plugin.
    :type config_file: basestring
    
    ``global_conf`` is not used at present, but could be used in the future.
    
    :raises repoze.what.plugins.quickstart.MissingOptionError: If one of the 
        mandatory options (``dbsession``, ``user_class``, ``group_class``, 
        ``permission_class``) is missing.
    :raises repoze.what.plugins.quickstart.BadOptionError: If an option has an
        invalid value.
    
    """
    auth_config = _AuthConf(config_file)
    auth_config.find_options()

    # Validating the configuration:
    if "dbsession" not in auth_config.options:
        raise MissingOptionError("The database session is missing")
    elif "user_class" not in auth_config.options:
        raise MissingOptionError("The SQLAlchemy-based user class is missing")
    elif "group_class" not in auth_config.options:
        raise MissingOptionError("The SQLAlchemy-based group class is missing")
    elif "permission_class" not in auth_config.options:
        raise MissingOptionError("The SQLAlchemy-based permission class is "
                                 "missing")

    app_with_auth = setup_sql_auth(app, **auth_config.options)
    return app_with_auth
 def _makeApp(self, **who_args):
     app_with_auth = setup_sql_auth(MockApplication(), User, Group, Permission,
                                    DBSession, **who_args)
     return app_with_auth
示例#22
0
    def add_auth_middleware(self, app, skip_authentication):
        """
        Configure authentication and authorization.

        :param app: The TG2 application.
        :param skip_authentication: Should authentication be skipped if
            explicitly requested? (used by repoze.who-testutil)
        :type skip_authentication: bool

        """
        # Configuring auth logging:
        if 'log_stream' not in self.sa_auth:
            self.sa_auth['log_stream'] = logging.getLogger('auth')

        # Removing keywords not used by repoze.who:
        auth_args = copy(self.sa_auth)
        if 'sa_auth' in config:
            auth_args.update(config.sa_auth)
        if 'password_encryption_method' in auth_args:
            del auth_args['password_encryption_method']
        if not skip_authentication:
            if not 'cookie_secret' in auth_args.keys():
                msg = "base_config.sa_auth.cookie_secret is required "\
                "you must define it in app_cfg.py or set "\
                "sa_auth.cookie_secret in development.ini"
                raise TGConfigError(msg)

        if 'authmetadata' not in auth_args:
            #authmetadata not provided, fallback to old authentication setup
            if self.auth_backend == "sqlalchemy":
                from repoze.what.plugins.quickstart import setup_sql_auth
                app = setup_sql_auth(app, skip_authentication=skip_authentication, **auth_args)
            elif self.auth_backend == "ming":
                from tgming import setup_ming_auth
                app = setup_ming_auth(app, skip_authentication=skip_authentication, **auth_args)
        else:
            try:
                pos = auth_args['authenticators'].index(('default', None))
            except KeyError:
                pos = None
            except ValueError:
                pos = -1
            if pos is None or pos >= 0:
                if self.auth_backend == "sqlalchemy":
                    from tg.configuration.sqla.auth import create_default_authenticator
                    auth_args, sqlauth = create_default_authenticator(**auth_args)
                    authenticator = ('sqlauth', sqlauth)
                elif self.auth_backend == "ming":
                    from tg.configuration.mongo.auth import create_default_authenticator
                    auth_args, mingauth = create_default_authenticator(**auth_args)
                    authenticator = ('mingauth', mingauth)
                else:
                    authenticator = None
                if authenticator:
                    if pos is None:
                        auth_args['authenticators'] = [authenticator]
                    else:
                        auth_args['authenticators'][pos] = authenticator
            from tg.configuration.auth import setup_auth
            app = setup_auth(app, skip_authentication=skip_authentication, **auth_args)

        return app
示例#23
0
def add_auth(app):
    return setup_sql_auth(app, User, Group, Permission, Session,
                          post_login_url='/', post_logout_url='/login')
示例#24
0
 def _makeApp(self, **who_args):
     app_with_auth = setup_sql_auth(MockApplication(), User, Group,
                                    Permission, DBSession, **who_args)
     return app_with_auth
示例#25
0
    def add_auth_middleware(self, app, skip_authentication):
        """
        Configure authentication and authorization.

        :param app: The TG2 application.
        :param skip_authentication: Should authentication be skipped if
            explicitly requested? (used by repoze.who-testutil)
        :type skip_authentication: bool

        """
        # Configuring auth logging:
        if 'log_stream' not in self.sa_auth:
            self.sa_auth['log_stream'] = logging.getLogger('auth')

        # Removing keywords not used by repoze.who:
        auth_args = copy(self.sa_auth)
        if 'sa_auth' in config:
            auth_args.update(config.sa_auth)
        if 'password_encryption_method' in auth_args:
            del auth_args['password_encryption_method']
        if not skip_authentication:
            if not 'cookie_secret' in auth_args.keys():
                msg = "base_config.sa_auth.cookie_secret is required "\
                "you must define it in app_cfg.py or set "\
                "sa_auth.cookie_secret in development.ini"
                raise TGConfigError(msg)

        if 'authmetadata' not in auth_args:
            #authmetadata not provided, fallback to old authentication setup
            if self.auth_backend == "sqlalchemy":
                from repoze.what.plugins.quickstart import setup_sql_auth
                app = setup_sql_auth(app, skip_authentication=skip_authentication, **auth_args)
            elif self.auth_backend == "ming":
                from tgming import setup_ming_auth
                app = setup_ming_auth(app, skip_authentication=skip_authentication, **auth_args)
        else:
            try:
                pos = auth_args['authenticators'].index(('default', None))
            except KeyError:
                pos = None
            except ValueError:
                pos = -1
            if pos is None or pos >= 0:
                if self.auth_backend == "sqlalchemy":
                    from tg.configuration.sqla.auth import create_default_authenticator
                    auth_args, sqlauth = create_default_authenticator(**auth_args)
                    authenticator = ('sqlauth', sqlauth)
                elif self.auth_backend == "ming":
                    from tg.configuration.mongo.auth import create_default_authenticator
                    auth_args, mingauth = create_default_authenticator(**auth_args)
                    authenticator = ('mingauth', mingauth)
                else:
                    authenticator = None
                if authenticator:
                    if pos is None:
                        auth_args['authenticators'] = [authenticator]
                    else:
                        auth_args['authenticators'][pos] = authenticator
            from tg.configuration.auth import setup_auth
            app = setup_auth(app, skip_authentication=skip_authentication, **auth_args)

        return app