예제 #1
0
def make_object(value, default, *args, **kw):
    if not value:
        return default(*args, **kw)
    elif isinstance(value, basestring):
        return import_string.eval_import(value)
    else:
        return value
예제 #2
0
파일: open_id.py 프로젝트: terrasea/paste
def make_open_id_middleware(
    app,
    global_conf,
    # Should this default to something, or inherit something from global_conf?:
    data_store_path,
    auth_prefix="/oid",
    login_redirect=None,
    catch_401=False,
    url_to_username=None,
    apply_auth_tkt=False,
    auth_tkt_logout_path=None,
):
    from paste.deploy.converters import asbool
    from paste.util import import_string

    catch_401 = asbool(catch_401)
    if url_to_username and isinstance(url_to_username, str):
        url_to_username = import_string.eval_import(url_to_username)
    apply_auth_tkt = asbool(apply_auth_tkt)
    new_app = AuthOpenIDHandler(
        app,
        data_store_path=data_store_path,
        auth_prefix=auth_prefix,
        login_redirect=login_redirect,
        catch_401=catch_401,
        url_to_username=url_to_username or None,
    )
    if apply_auth_tkt:
        from paste.auth import auth_tkt

        new_app = auth_tkt.make_auth_tkt_middleware(new_app, global_conf, logout_path=auth_tkt_logout_path)
    return new_app
예제 #3
0
def make_open_id_middleware(
    app,
    global_conf,
    # Should this default to something, or inherit something from global_conf?:
    data_store_path,
    auth_prefix='/oid',
    login_redirect=None,
    catch_401=False,
    url_to_username=None,
    apply_auth_tkt=False,
    auth_tkt_logout_path=None):
    from paste.deploy.converters import asbool
    from paste.util import import_string
    catch_401 = asbool(catch_401)
    if url_to_username and isinstance(url_to_username, basestring):
        url_to_username = import_string.eval_import(url_to_username)
    apply_auth_tkt = asbool(apply_auth_tkt)
    new_app = AuthOpenIDHandler(
        app, data_store_path=data_store_path, auth_prefix=auth_prefix,
        login_redirect=login_redirect, catch_401=catch_401,
        url_to_username=url_to_username or None)
    if apply_auth_tkt:
        from paste.auth import auth_tkt
        new_app = auth_tkt.make_auth_tkt_middleware(
            new_app, global_conf, logout_path=auth_tkt_logout_path)
    return new_app
예제 #4
0
def make_eval_exception(app, global_conf, xmlhttp_key=None, reporters=None):
    """
    Wraps the application in an interactive debugger.

    This debugger is a major security hole, and should only be
    used during development.

    xmlhttp_key is a string that, if present in QUERY_STRING,
    indicates that the request is an XMLHttp request, and the
    Javascript/interactive debugger should not be returned.  (If you
    try to put the debugger somewhere with innerHTML, you will often
    crash the browser)
    """
    if xmlhttp_key is None:
        xmlhttp_key = global_conf.get('xmlhttp_key', '_')
    if reporters is None:
        reporters = global_conf.get('error_reporters')
    if reporters and isinstance(reporters, basestring):
        reporter_strings = reporters.split()
        reporters = []
        for reporter_string in reporter_strings:
            reporter = import_string.eval_import(reporter_string)
            if isinstance(reporter, (type, types.ClassType)):
                reporter = reporter()
            reporters.append(reporter)
    return EvalException(app, xmlhttp_key=xmlhttp_key, reporters=reporters)
예제 #5
0
 def get_validate_func(self):
     settings = self.request.registry.settings
     key = 'authentication.cookie.validate_function'
     func_str = settings.get(key)
     if not func_str:
         raise AttributeError('%s is not defined.' % key)
     return eval_import(func_str)
예제 #6
0
def includeme(config):
    settings = config.registry.settings
    prefix = 'pyramid_auth.ldap'
    config.set_authentication_policy(
        AuthTktAuthenticationPolicy(
            **parse_settings(settings, SETTINGS, 'cookie', prefix)
        )
    )

    validate_function = validate_ldap
    func_str = config.registry.settings.get(
        'pyramid_auth.ldap.validate_function')
    if func_str:
        validate_function = eval_import(func_str)
    config.registry.settings[
        'pyramid_auth.validate_function'] = validate_function

    config.ldap_setup(**parse_settings(settings,
                                       SETTINGS,
                                       'setup',
                                       prefix))
    config.ldap_set_login_query(**parse_settings(settings,
                                                 SETTINGS,
                                                 'login',
                                                 prefix))
    config.ldap_set_groups_query(**parse_settings(settings,
                                                  SETTINGS,
                                                  'groups',
                                                  prefix))

    login_includeme(config)
예제 #7
0
def get_authenticate_function(app, authenticate_conf, format, prefix):
    """
    Sets up the users object, adds the middleware to add the users object
    to the environ and then returns authenticate methods to check a password
    and a digest.
    """
    function = None
    users = None
    if len(authenticate_conf) < 1:
        raise AuthKitConfigError('Expected at least one authenticate key, not'
                                 ' %r' % authenticate_conf)
    if authenticate_conf.keys() == ['function']:
        function = authenticate_conf['function']
        if isinstance(function, (str, unicode)):
            function = eval_import(function)
    else:
        user_conf = strip_base(authenticate_conf, 'user.')
        if not user_conf:
            raise AuthKitConfigError(
                'No authenticate function or users specified')
        else:
            if user_conf.has_key('encrypt'):
                enc_func = eval_import(user_conf['encrypt'])
                secret = user_conf.get('encrypt.secret', '')

                def encrypt(password):
                    return enc_func(password, secret)
            else:
                encrypt = None
            user_object = 'authkit.users.UsersFromString'
            if 'type' in user_conf.keys():
                user_object = user_conf['type']
            if isinstance(user_object, (str, unicode)):
                user_object = eval_import(user_object)
            users = user_object(user_conf['data'], encrypt)
            app = AddToEnviron(app, 'authkit.users', users)
            log.debug("authkit.users added to environ")
            if format == 'basic':
                function = valid_password
                log.debug("valid_password chosen %r", function)
            elif format == 'digest':
                log.debug("digest_password chosen %r", function)
                function = digest_password
            else:
                raise Exception('Invalid format for authenticate function %r' %
                                format)
    return app, function, users
예제 #8
0
def get_template(template_conf, prefix):
    """
    Another utility method to reduce code duplication. This function parses a
    template from one of the available template options:

    ``string``
        The template as a string
        
    ``file``
        A file containing the template

    ``obj``
        A paste eval_import string or callable which returns a string

    authkit.form.template.string = 
    authkit.form.template.file = 
    authkit.form.template.obj =

    """
    template = None
    if len(template_conf) != 1:
        raise AuthKitConfigError('Expected one template entry, not %r' %
                                 (', '.join(template_conf.keys())))
    if template_conf.keys()[0] not in ['string', 'file', 'obj']:
        raise AuthKitConfigError("Template option can only be 'string', 'file'"
                                 " or 'obj'")
    if template_conf.keys()[0] == 'string':
        template = template_conf['string']
    elif template_conf.keys()[0] == 'file':
        if not os.path.exists(template_conf['file']):
            raise AuthKitConfigError('No such file %r exists. It was specified'
                                     ' by config option %r' %
                                     (template_conf['file'], prefix + 'file'))
        fp = open(template_conf['file'], 'r')
        template = fp.read()
        fp.close()
        if not template:
            raise AuthKitConfigError('No data in template file %s specified by'
                                     ' config option %r' %
                                     (template_conf['file'], prefix + 'file'))
    elif template_conf.keys()[0] == 'obj':
        template = eval_import(template_conf['obj'])
        if not template:
            raise AuthKitConfigError('No data in template obj %s specified by '
                                     'config option %r' %
                                     (template_conf['obj'], prefix + 'obj'))
    else:
        raise AuthKitConfigError("Unknown option %r" %
                                 (prefix + template_conf.keys()[0]))
    if not template:
        raise AuthKitConfigError(
            "The template loaded did not contain any data")
    if isinstance(template, (str, unicode)):

        def render_template():
            return template

        return render_template
    return template
예제 #9
0
def load_openid_config(
    app,
    auth_conf, 
    app_conf=None,
    global_conf=None,
    prefix='authkit.openid', 
):
    global template
    template_ = template
    template_conf = strip_base(auth_conf, 'template.')
    if template_conf:
        template_ = get_template(template_conf, prefix=prefix+'template.')
    urltouser = auth_conf.get('urltouser', None)
    if isinstance(urltouser, str):
        urltouser = eval_import(urltouser)
    for option in ['store.type', 'store.config', 'path.signedin']:
        if not auth_conf.has_key(option):
            raise AuthKitConfigError(
                'Missing the config key %s%s'%(prefix, option)
            )
    user_setter_params={
        'store_type': auth_conf['store.type'], 
        'store_config': auth_conf['store.config'],
        'baseurl': auth_conf.get('baseurl',''),
        'path_signedin': auth_conf['path.signedin'],
        'path_process': auth_conf.get('path.process','/process'),
        'template': template_,
        'urltouser': urltouser,
        'charset': auth_conf.get('charset'),
        'openid_form_fieldname': auth_conf.get('openid_form_fieldname'),
        'force_redirect': auth_conf.get('force_redirect'),
        'sreg_required': auth_conf.get('sreg.required'),
        'sreg_optional': auth_conf.get('sreg.optional'),
        'sreg_policyurl': auth_conf.get('sreg.policyurl'),
        'session_middleware': auth_conf.get('session.middleware','beaker.session'),
    }
    
    # Add an Attribute Exchange configuration items
    user_setter_params.update(_load_ax_config(auth_conf))

    auth_handler_params={
        'template':user_setter_params['template'],
        'path_verify':auth_conf.get('path.verify', '/verify'),
        'baseurl':user_setter_params['baseurl'],
        'charset':user_setter_params['charset'],
        'force_redirect': auth_conf.get('force_redirect', False),
        'openid_form_fieldname': auth_conf.get('openid_form_fieldname', None),
    }
    # The following lines were suggested in #59 but I don't know
    # why they are needed because you shouldn't be using the 
    # user management API.
    # authenticate_conf = strip_base(auth_conf, 'authenticate.')
    # app, authfunc, users = get_authenticate_function(
    #     app, 
    #     authenticate_conf, 
    #     prefix=prefix+'authenticate.', 
    #     format='basic'
    # )
    return app, auth_handler_params, user_setter_params
예제 #10
0
def setUpModule():
    global compmgr, syscomp, userscomp, projcomp, permission_data, seed, cachemgr

    testdir = os.path.basename(os.path.dirname(__file__))
    testfile = os.path.basename(__file__)
    seed = config['seed'] and int(config['seed']) or genseed()
    log_mheader(log, testdir, testfile, seed)
    random.seed(seed)
    info = "   Creating models ..."
    log.info(info)
    print info

    # Setup SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    # init_model( engine )
    create_models(engine,
                  config,
                  sysentries_cfg=meta.sysentries_cfg,
                  permissions=permissions)
    print "   Generating data ..."
    permission_data = gen_pgroups(seed=seed)
    compmgr = config['compmgr']
    userscomp = config['userscomp']
    projcomp = ProjectComponent(compmgr)
    syscomp = SystemComponent(compmgr)
    print "   Populating users ( no_of_users=%s, no_of_relations=%s ) ..." % \
                ( no_of_users, no_of_relations )
    pop_user(no_of_users, no_of_relations, seed=seed)
    print "   Populating licenses ( no_of_tags=%s, no_of_attachs=%s ) ..." % \
                ( no_of_tags, no_of_attachs )
    pop_licenses(no_of_tags, no_of_attachs, seed=seed)
    print "   Populating projects ( no_of_projects=%s ) ..." % no_of_projects
    pop_projects(no_of_projects, no_of_tags, no_of_attachs, seed=seed)

    # initialize the PMS system
    mapmod = eval_import(config['zeta.pmap.module'])
    permmod.init_pms = eval_import(config['zeta.pmap.mapfunc'])
    permmod.pms_root = permmod.init_pms(ctxt=ctxt)
    permmod.default_siteperms = mapmod.default_siteperms
    permmod.default_projperms = mapmod.default_projperms

    # Setup cache manager
    isdir(cachedir) or os.makedirs(cachedir)
    cachemgr = cachemod.cachemanager(cachedir)
    config['cachemgr'] = cachemgr
예제 #11
0
    def __init__(self, data, encrypt=None):
        if encrypt is None:

            def encrypt(password):
                return password

        self.encrypt = encrypt
        if isinstance(data, (str, unicode)):
            data_parts = data.split('\n')
            data = []
            if len(data_parts) == 2:
                data.append(eval_import(data_parts[0].strip()))
                data.append(eval_import(data_parts[1].strip()))
            else:
                raise AuthKitError(
                    "Expected two lines in the user configuration, not %s" %
                    (len(data_parts)))
        self.get_conn, self.release_conn = data
예제 #12
0
    def __init__(
        self,
        global_conf,
        directory,
        base_python_name,
        index_names=NoDefault,
        hide_extensions=NoDefault,
        ignore_extensions=NoDefault,
        constructors=None,
        **constructor_conf
    ):
        """
        Create a URLParser object that looks at `directory`.
        `base_python_name` is the package that this directory
        represents, thus any Python modules in this directory will
        be given names under this package.
        """
        if global_conf:
            import warnings

            warnings.warn(
                "The global_conf argument to URLParser is deprecated; "
                "either pass in None or {}, or use make_url_parser",
                DeprecationWarning,
            )
        else:
            global_conf = {}
        if os.path.sep != "/":
            directory = directory.replace(os.path.sep, "/")
        self.directory = directory
        self.base_python_name = base_python_name
        # This logic here should be deprecated since it is in
        # make_url_parser
        if index_names is NoDefault:
            index_names = global_conf.get("index_names", ("index", "Index", "main", "Main"))
        self.index_names = converters.aslist(index_names)
        if hide_extensions is NoDefault:
            hide_extensions = global_conf.get("hide_extensions", (".pyc", ".bak", ".py~", ".pyo"))
        self.hide_extensions = converters.aslist(hide_extensions)
        if ignore_extensions is NoDefault:
            ignore_extensions = global_conf.get("ignore_extensions", ())
        self.ignore_extensions = converters.aslist(ignore_extensions)
        self.constructors = self.global_constructors.copy()
        if constructors:
            self.constructors.update(constructors)
        # @@: Should we also check the global options for constructors?
        for name, value in constructor_conf.items():
            if not name.startswith("constructor "):
                raise ValueError(
                    "Only extra configuration keys allowed are "
                    "'constructor .ext = import_expr'; you gave %r "
                    "(=%r)" % (name, value)
                )
            ext = name[len("constructor ") :].strip()
            if isinstance(value, (str, unicode)):
                value = import_string.eval_import(value)
            self.constructors[ext] = value
예제 #13
0
파일: __init__.py 프로젝트: nakato/AuthKit
def get_template(template_conf, prefix):
    """
    Another utility method to reduce code duplication. This function parses a
    template from one of the available template options:

    ``string``
        The template as a string
        
    ``file``
        A file containing the template

    ``obj``
        A paste eval_import string or callable which returns a string

    authkit.form.template.string = 
    authkit.form.template.file = 
    authkit.form.template.obj =

    """
    template = None
    if len(template_conf) != 1:
        raise AuthKitConfigError('Expected one template entry, not %r' % 
                                 (', '.join(template_conf.keys())))
    if template_conf.keys()[0] not in ['string', 'file', 'obj']:
        raise AuthKitConfigError("Template option can only be 'string', 'file'"
                                 " or 'obj'")
    if template_conf.keys()[0] == 'string':
        template = template_conf['string']
    elif template_conf.keys()[0] == 'file':
        if not os.path.exists(template_conf['file']):
            raise AuthKitConfigError('No such file %r exists. It was specified'
                                     ' by config option %r' % 
                                     (template_conf['file'], prefix+'file'))
        fp = open(template_conf['file'], 'r')
        template = fp.read()
        fp.close()
        if not template:
            raise AuthKitConfigError('No data in template file %s specified by'
                                     ' config option %r' % 
                                     (template_conf['file'], prefix+'file'))
    elif template_conf.keys()[0] == 'obj':
        template = eval_import(template_conf['obj'])
        if not template:
            raise AuthKitConfigError('No data in template obj %s specified by '
                                     'config option %r' % 
                                     (template_conf['obj'], prefix+'obj'))
    else:
        raise AuthKitConfigError("Unknown option %r" % 
                                 (prefix+template_conf.keys()[0]))
    if not template:
        raise AuthKitConfigError("The template loaded did not contain any data")
    if isinstance(template, (str, unicode)):
        def render_template():
            return template
        return render_template
    return template
예제 #14
0
 def __init__(self, environ, data, encrypt=None):
     if encrypt is None:
         def encrypt(password):
             return password
     self.encrypt = encrypt
     if isinstance(data, (str, unicode)):
         data_parts = data.split('\n')
         data = []
         if len(data_parts) == 2:
             data.append(eval_import(data_parts[0].strip()))
             data.append(eval_import(data_parts[1].strip()))
         else:
             raise AuthKitError(
                 "Expected two lines in the user configuration, not %s"%(
                     len(data_parts)
                 )
             )
     self.get_conn, self.release_conn = data
     self.environ = environ
예제 #15
0
파일: wsgi_app.py 프로젝트: sithmel/ForRest
def make_app(global_conf, resource_class, **kw):

    from paste.util.import_string import eval_import
    import types

    conf = global_conf.copy()
    conf.update(kw)
    Resources = eval_import(resource_class)
    assert isinstance(Resources, types.TypeType), "resource_class must resolve to a function"
    conf['resources'] = Resources(**conf)
    return RestApp(conf)
예제 #16
0
 def __init__(self,
              global_conf,
              directory,
              base_python_name,
              index_names=NoDefault,
              hide_extensions=NoDefault,
              ignore_extensions=NoDefault,
              constructors=None,
              **constructor_conf):
     """
     Create a URLParser object that looks at `directory`.
     `base_python_name` is the package that this directory
     represents, thus any Python modules in this directory will
     be given names under this package.
     """
     if global_conf:
         import warnings
         warnings.warn(
             'The global_conf argument to URLParser is deprecated; '
             'either pass in None or {}, or use make_url_parser',
             DeprecationWarning)
     else:
         global_conf = {}
     if os.path.sep != '/':
         directory = directory.replace(os.path.sep, '/')
     self.directory = directory
     self.base_python_name = base_python_name
     # This logic here should be deprecated since it is in
     # make_url_parser
     if index_names is NoDefault:
         index_names = global_conf.get('index_names',
                                       ('index', 'Index', 'main', 'Main'))
     self.index_names = converters.aslist(index_names)
     if hide_extensions is NoDefault:
         hide_extensions = global_conf.get('hide_extensions',
                                           ('.pyc', '.bak', '.py~', '.pyo'))
     self.hide_extensions = converters.aslist(hide_extensions)
     if ignore_extensions is NoDefault:
         ignore_extensions = global_conf.get('ignore_extensions', ())
     self.ignore_extensions = converters.aslist(ignore_extensions)
     self.constructors = self.global_constructors.copy()
     if constructors:
         self.constructors.update(constructors)
     # @@: Should we also check the global options for constructors?
     for name, value in constructor_conf.items():
         if not name.startswith('constructor '):
             raise ValueError(
                 "Only extra configuration keys allowed are "
                 "'constructor .ext = import_expr'; you gave %r "
                 "(=%r)" % (name, value))
         ext = name[len('constructor '):].strip()
         if isinstance(value, (str, unicode)):
             value = import_string.eval_import(value)
         self.constructors[ext] = value
예제 #17
0
    def __init__(self, model, encrypt=None):
        if encrypt is None:

            def encrypt(password):
                return password

        self.encrypt = encrypt
        if isinstance(model, (str, unicode)):
            model = eval_import(model)

        self.model = model
예제 #18
0
def setUpModule() :
    global userdata, userreldata, compmgr, userscomp, seed, cachemgr

    testdir  = os.path.basename( os.path.dirname( __file__ ))
    testfile = os.path.basename( __file__ )
    seed     = config['seed'] and int(config['seed']) or genseed()
    log_mheader( log, testdir, testfile, seed )
    random.seed( seed )
    info = "   Creating models (module-level) ... "
    log.info( info )
    print info
    # Setup SQLAlchemy database engine
    engine = engine_from_config( config, 'sqlalchemy.' )
    # init_model( engine )
    create_models( engine, config, sysentries_cfg=meta.sysentries_cfg, 
                   permissions=permissions )

    compmgr     = config['compmgr']
    userscomp   = config['userscomp']
    userreltypes= userscomp.reltypes
    userdata    = gen_usercontent( no_of_users=no_of_users, seed=seed )
    userreldata = gen_userrelations( userdata.keys(),
                                     userreltypes,
                                     no_of_relations=no_of_relations,
                                     seed=seed
                                   )
    for username in userdata :
        userdata[username]['userrels'] = userreldata[username]

    # initialize the PMS system
    mapmod = eval_import( config['zeta.pmap.module'] )
    permmod.init_pms = eval_import( config['zeta.pmap.mapfunc'] )
    permmod.pms_root = permmod.init_pms( ctxt=ctxt )
    permmod.default_siteperms = mapmod.default_siteperms
    permmod.default_projperms = mapmod.default_projperms

    # Setup cache manager
    isdir( cachedir ) or os.makedirs( cachedir )
    cachemgr = cachemod.cachemanager( cachedir )
    config['cachemgr'] = cachemgr
예제 #19
0
def setUpModule():
    """Create database and tables."""
    global compmgr, userscomp, syscomp, attachcomp, seed, cachemgr

    testdir = os.path.basename(os.path.dirname(__file__))
    testfile = os.path.basename(__file__)
    seed = config['seed'] and int(config['seed']) or genseed()
    log_mheader(log, testdir, testfile, seed)
    random.seed(seed)
    info = "   Creating models (module-level) ... "
    log.info(info)
    print info
    # Setup SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    # init_model( engine )
    create_models(engine,
                  config,
                  sysentries_cfg=meta.sysentries_cfg,
                  permissions=permissions)
    userscomp = config['userscomp']
    compmgr = config['compmgr']
    syscomp = SystemComponent(compmgr)
    attachcomp = AttachComponent(compmgr)
    print "   Populating permissions ..."
    pop_permissions(seed=seed)
    print "   Populating users ( no_of_users=%s, no_of_relations=%s ) ..." % \
                ( no_of_users, no_of_relations )
    pop_user(no_of_users, no_of_relations, seed=seed)

    # initialize the PMS system
    mapmod = eval_import(config['zeta.pmap.module'])
    permmod.init_pms = eval_import(config['zeta.pmap.mapfunc'])
    permmod.pms_root = permmod.init_pms(ctxt=ctxt)
    permmod.default_siteperms = mapmod.default_siteperms
    permmod.default_projperms = mapmod.default_projperms

    # Setup cache manager
    isdir(cachedir) or os.makedirs(cachedir)
    cachemgr = cachemod.cachemanager(cachedir)
    config['cachemgr'] = cachemgr
예제 #20
0
파일: form.py 프로젝트: 10sr/hue
def make_form(app, global_conf, realm, authfunc, **kw):
    """
    Grant access via form authentication

    Config looks like this::

      [filter:grant]
      use = egg:Paste#auth_form
      realm=myrealm
      authfunc=somepackage.somemodule:somefunction

    """
    from paste.util.import_string import eval_import
    import types
    authfunc = eval_import(authfunc)
    assert isinstance(authfunc, types.FunctionType), "authfunc must resolve to a function"
    template = kw.get('template')
    if template is not None:
        template = eval_import(template)
        assert isinstance(template, str), "template must resolve to a string"

    return AuthFormHandler(app, authfunc, template)
예제 #21
0
def make_form(app, global_conf, realm, authfunc, **kw):
    """
    Grant access via form authentication

    Config looks like this::

      [filter:grant]
      use = egg:Paste#auth_form
      realm=myrealm
      authfunc=somepackage.somemodule:somefunction
      
    """
    from paste.util.import_string import eval_import
    import types
    authfunc = eval_import(authfunc)
    assert isinstance(authfunc, types.FunctionType), "authfunc must resolve to a function"
    template = kw.get('template')
    if template is not None:
        template = eval_import(template)
        assert isinstance(template, str), "template must resolve to a string"

    return AuthFormHandler(app, authfunc, template)
예제 #22
0
 def __init__(self, model, encrypt=None):
     if encrypt is None:
         def encrypt(password):
             return password
     self.encrypt = encrypt
     if isinstance(model, (str, unicode)):
         model = eval_import(model)
     if hasattr(model, 'authkit_initialized'):
         self.model = model
         self.meta = self.model.meta
     else:
         self.model = self.update_model(model)
         self.meta = self.model.meta        
         model.authkit_initialized = True
예제 #23
0
파일: factories.py 프로젝트: mtpi/daffydav
def make_app(global_conf, **kw):

    CONFIG = global_conf.copy()
    CONFIG.update(kw)

    # load daffydav.conf
    daffydav_conf = SafeConfigParser()
    daffydav_conf.read(CONFIG["config_file"])

    # authenticator backend
    auth = eval_import(daffydav_conf.get("authenticator", "backend"))
    auth_options = ConfigBackendOptions(daffydav_conf.items("authenticator"))
    CONFIG["authenticator_realm"] = auth_realm = daffydav_conf.get("authenticator", "realm")
    auth_daemon = AuthDaemon(auth, auth_options)

    # virtual filesystem backend
    CONFIG["vfs"] = eval_import(daffydav_conf.get("vfs", "backend"))
    CONFIG["vfs_options"] = ConfigBackendOptions(daffydav_conf.items("vfs"))

    # filemanager interface backend
    fmbackend = eval_import(daffydav_conf.get("filemanager", "backend"))
    fmbackend_options = ConfigBackendOptions(daffydav_conf.items("filemanager"))
    CONFIG["filemanager_backend"] = fmbackend(**fmbackend_options)

    # === MIDDLEWARE ===
    # Main application
    app = application
    # Authenticator Middleware
    app = AuthBasicHandler(app, auth_realm, auth_daemon.authfunc)
    # paste RegistryManager middleware for thread-local objects
    app = RegistryManager(app)
    # ConfigMiddleware means that paste.deploy.CONFIG will,
    # during this request (threadsafe) represent the
    # configuration dictionary we set up:
    app = ConfigMiddleware(app, CONFIG)

    return app
예제 #24
0
def get_groups(dn, request):
    """Get the groups for the given dn.

    We get the groups from the ldap and we also get from the function set in
    the config. It's usefull, if you have more permission set in the DB or if
    you want to add new logic.
    """
    lis = []
    if request.registry.settings.get('authentication.ldap.groups.filter_tmpl'):
        lis += get_ldap_groups(dn, request)
    callback = request.registry.settings.get('authentication.ldap.callback')
    if callback:
        func = eval_import(callback)
        lis += func(dn, request)
    return lis
예제 #25
0
def create_login_form(settings):
    func_str = settings.get('pyramid_auth.validate_function')
    if not func_str:
        raise AttributeError, ('pyramid_auth.validate_function '
                               'is not defined in the conf')
    func = eval_import(func_str)

    class LoginForm(twf.TableForm):
        login = twf.TextField(validator=twc.Validator(required=True))
        password = twf.PasswordField(validator=twc.Validator(required=True))
        submit = twf.SubmitButton(id='submit', value='Login')

        validator = UserExists(login='******',
                               password='******',
                               validate_func=func)
    return LoginForm
예제 #26
0
 def __init__(self, environ, data=None, encrypt=None):
     if encrypt is None:
         def encrypt(password):
             return password
     self.encrypt = encrypt
     self.environ = environ
     
     self.adminrole = environ.get('authkit.google.adminrole', None)
     if self.adminrole:
         self.adminrole = self.adminrole.lower()
     
     # load the user_model given in the data:
     if data and isinstance(data, (str, unicode)):
         self.user_model = eval_import(data)
     else:
         self.user_model = BaseUser
예제 #27
0
    def __init__(self, model, encrypt=None):
        if encrypt is None:

            def encrypt(password):
                return password

        self.encrypt = encrypt
        if isinstance(model, (str, unicode)):
            model = eval_import(model)

        if hasattr(model, 'authkit_initialized'):
            raise AuthKitError(
                'The AuthKit database model has already been setup')
        else:
            model.authkit_initialized = True

        self.model = self.update_model(model)
예제 #28
0
def make_basic(app, global_conf, realm, authfunc, **kw):
    """
    Grant access via basic authentication

    Config looks like this::

      [filter:grant]
      use = egg:Paste#auth_basic
      realm=myrealm
      authfunc=somepackage.somemodule:somefunction

    """
    from paste.util.import_string import eval_import
    import types
    authfunc = eval_import(authfunc)
    assert isinstance(authfunc, types.FunctionType), "authfunc must resolve to a function"
    return AuthBasicHandler(app, realm, authfunc)
예제 #29
0
파일: basic.py 프로젝트: 10sr/hue
def make_basic(app, global_conf, realm, authfunc, **kw):
    """
    Grant access via basic authentication

    Config looks like this::

      [filter:grant]
      use = egg:Paste#auth_basic
      realm=myrealm
      authfunc=somepackage.somemodule:somefunction

    """
    from paste.util.import_string import eval_import
    import types
    authfunc = eval_import(authfunc)
    assert isinstance(authfunc, types.FunctionType), "authfunc must resolve to a function"
    return AuthBasicHandler(app, realm, authfunc)
예제 #30
0
    def __init__(self, model, encrypt=None):
        if encrypt is None:
            def encrypt(password):
                return password
        self.encrypt = encrypt
        if isinstance(model, (str, unicode)):
            model = eval_import(model)
        if hasattr(model, 'authkit_initialized'):
            raise AuthKitError(
                'The AuthKit database model has already been setup'
            )
        else:
            model.authkit_initialized = True

        # Update the model
        self.model = self.update_model(model)
        self.meta = self.model.meta        
예제 #31
0
def load_openid_config(app, auth_conf, app_conf=None, global_conf=None, prefix="authkit.openid"):
    global template
    template_ = template
    template_conf = strip_base(auth_conf, "template.")
    if template_conf:
        template_ = get_template(template_conf, prefix=prefix + "template.")
    urltouser = auth_conf.get("urltouser", None)
    if isinstance(urltouser, str):
        urltouser = eval_import(urltouser)
    for option in ["store.type", "store.config", "path.signedin"]:
        if not auth_conf.has_key(option):
            raise AuthKitConfigError("Missing the config key %s%s" % (prefix, option))
    user_setter_params = {
        "store_type": auth_conf["store.type"],
        "store_config": auth_conf["store.config"],
        "baseurl": auth_conf.get("baseurl", ""),
        "path_signedin": auth_conf["path.signedin"],
        "path_process": auth_conf.get("path.process", "/process"),
        "template": template_,
        "urltouser": urltouser,
        "charset": auth_conf.get("charset"),
        "sreg_required": auth_conf.get("sreg.required"),
        "sreg_optional": auth_conf.get("sreg.optional"),
        "sreg_policyurl": auth_conf.get("sreg.policyurl"),
        "session_middleware": auth_conf.get("session.middleware", "beaker.session"),
    }
    auth_handler_params = {
        "template": user_setter_params["template"],
        "path_verify": auth_conf.get("path.verify", "/verify"),
        "baseurl": user_setter_params["baseurl"],
        "charset": user_setter_params["charset"],
    }
    # The following lines were suggested in #59 but I don't know
    # why they are needed because you shouldn't be using the
    # user management API.
    # authenticate_conf = strip_base(auth_conf, 'authenticate.')
    # app, authfunc, users = get_authenticate_function(
    #     app,
    #     authenticate_conf,
    #     prefix=prefix+'authenticate.',
    #     format='basic'
    # )
    return app, auth_handler_params, user_setter_params
예제 #32
0
def make_middleware(app,
                    global_conf,
                    database=None,
                    use_transaction=False,
                    hub=None):
    """
    WSGI middleware that sets the connection for the request (using
    the database URI or connection object) and the given hub (or
    ``sqlobject.sqlhub`` if not given).

    If ``use_transaction`` is true, then the request will be run in a
    transaction.

    Applications can use the keys (which are all no-argument functions):

    ``sqlobject.get_connection()``:
      Returns the connection object
      
    ``sqlobject.abort()``:
      Aborts the transaction.  Does not raise an error, but at the *end*
      of the request there will be a rollback.
      
    ``sqlobject.begin()``:
      Starts a transaction.  First commits (or rolls back if aborted) if
      this is run in a transaction.

    ``sqlobject.in_transaction()``:
      Returns true or false, depending if we are currently in a
      transaction.
    """
    use_transaction = asbool(use_transaction)
    if database is None:
        database = global_conf.get('database')
    if not database:
        raise ValueError("You must provide a 'database' configuration value")
    if isinstance(hub, basestring):
        hub = import_string.eval_import(hub)
    if not hub:
        hub = sqlobject.sqlhub
    if isinstance(database, basestring):
        database = sqlobject.connectionForURI(database)
    return SQLObjectMiddleware(app, database, use_transaction, hub)
예제 #33
0
def includeme(config):
    settings = config.registry.settings
    policy = settings.get('authentication.policy') or 'cookie'

    if policy not in ['cookie', 'remote_user', 'ldap']:
        raise Exception('Policy not supported: %s' % policy)

    mod = eval_import('pyramid_auth.%s_auth' % policy)
    config.set_authorization_policy(ACLAuthorizationPolicy())
    mod.includeme(config)

    sqladmin_dir = 'pyramid_auth:templates'

    if 'mako.directories' not in settings:
        settings['mako.directories'] = []

    if type(settings['mako.directories']) is list:
        settings['mako.directories'] += [sqladmin_dir]
    else:
        settings['mako.directories'] += '\n%s' % sqladmin_dir
예제 #34
0
def load_openid_config(
    app,
    auth_conf, 
    app_conf=None,
    global_conf=None,
    prefix='authkit.openid', 
):
    global template
    template_ = template
    template_conf = strip_base(auth_conf, 'template.')
    if template_conf:
        template_ = get_template(template_conf, prefix=prefix+'template.')
    urltouser = auth_conf.get('urltouser', None)
    if isinstance(urltouser, str):
        urltouser = eval_import(urltouser)
    for option in ['store.type', 'store.config', 'path.signedin']:
        if not auth_conf.has_key(option):
            raise AuthKitConfigError(
                'Missing the config key %s%s'%(prefix, option)
            )
    user_setter_params={
        'store_type': auth_conf['store.type'], 
        'store_config': auth_conf['store.config'],
        'baseurl': auth_conf.get('baseurl',''),
        'path_signedin': auth_conf['path.signedin'],
        'path_process': auth_conf.get('path.process','/process'),
        'template': template_,
        'urltouser': urltouser,
        'charset': auth_conf.get('charset'),
        'sreg_required': auth_conf.get('sreg.required'),
        'sreg_optional': auth_conf.get('sreg.optional'),
        'sreg_policyurl': auth_conf.get('sreg.policyurl'),
        'session_middleware': 'beaker.session',
    }
    auth_handler_params={
        'template':user_setter_params['template'],
        'path_verify':auth_conf.get('path.verify', '/verify'),
        'baseurl':user_setter_params['baseurl'],
        'charset':user_setter_params['charset'],
    }
    return app, auth_handler_params, user_setter_params
예제 #35
0
def make_middleware(app, global_conf, database=None, use_transaction=False,
                    hub=None):
    """
    WSGI middleware that sets the connection for the request (using
    the database URI or connection object) and the given hub (or
    ``sqlobject.sqlhub`` if not given).

    If ``use_transaction`` is true, then the request will be run in a
    transaction.

    Applications can use the keys (which are all no-argument functions):

    ``sqlobject.get_connection()``:
      Returns the connection object

    ``sqlobject.abort()``:
      Aborts the transaction.  Does not raise an error, but at the *end*
      of the request there will be a rollback.

    ``sqlobject.begin()``:
      Starts a transaction.  First commits (or rolls back if aborted) if
      this is run in a transaction.

    ``sqlobject.in_transaction()``:
      Returns true or false, depending if we are currently in a
      transaction.
    """
    use_transaction = asbool(use_transaction)
    if database is None:
        database = global_conf.get('database')
    if not database:
        raise ValueError(
            "You must provide a 'database' configuration value")
    if isinstance(hub, string_type):
        hub = import_string.eval_import(hub)
    if not hub:
        hub = sqlobject.sqlhub
    if isinstance(database, string_type):
        database = sqlobject.connectionForURI(database)
    return SQLObjectMiddleware(app, database, use_transaction, hub)
예제 #36
0
파일: open_id.py 프로젝트: bobrock/AuthKit
def load_openid_config(
    app,
    auth_conf,
    app_conf=None,
    global_conf=None,
    prefix='authkit.openid',
):
    global template
    template_ = template
    template_conf = strip_base(auth_conf, 'template.')
    if template_conf:
        template_ = get_template(template_conf, prefix=prefix + 'template.')
    urltouser = auth_conf.get('urltouser', None)
    if isinstance(urltouser, str):
        urltouser = eval_import(urltouser)
    for option in ['store.type', 'store.config', 'path.signedin']:
        if not auth_conf.has_key(option):
            raise AuthKitConfigError('Missing the config key %s%s' %
                                     (prefix, option))
    user_setter_params = {
        'store_type':
        auth_conf['store.type'],
        'store_config':
        auth_conf['store.config'],
        'baseurl':
        auth_conf.get('baseurl', ''),
        'path_signedin':
        auth_conf['path.signedin'],
        'path_process':
        auth_conf.get('path.process', '/process'),
        'template':
        template_,
        'urltouser':
        urltouser,
        'charset':
        auth_conf.get('charset'),
        'sreg_required':
        auth_conf.get('sreg.required'),
        'sreg_optional':
        auth_conf.get('sreg.optional'),
        'sreg_policyurl':
        auth_conf.get('sreg.policyurl'),
        'session_middleware':
        auth_conf.get('session.middleware', 'beaker.session'),
    }

    # Add an Attribute Exchange configuration items
    user_setter_params.update(_load_ax_config(auth_conf))

    auth_handler_params = {
        'template': user_setter_params['template'],
        'path_verify': auth_conf.get('path.verify', '/verify'),
        'baseurl': user_setter_params['baseurl'],
        'charset': user_setter_params['charset'],
    }
    # The following lines were suggested in #59 but I don't know
    # why they are needed because you shouldn't be using the
    # user management API.
    # authenticate_conf = strip_base(auth_conf, 'authenticate.')
    # app, authfunc, users = get_authenticate_function(
    #     app,
    #     authenticate_conf,
    #     prefix=prefix+'authenticate.',
    #     format='basic'
    # )
    return app, auth_handler_params, user_setter_params
예제 #37
0
 def get_validate_func(self):
     settings = self.request.registry.settings
     func_str = settings.get('authentication.ldap.validate_function')
     if func_str:
         return eval_import(func_str)
     return validate_ldap
예제 #38
0
def get_authenticate_function(app, authenticate_conf, format, prefix):
    """
    Sets up the users object, adds the middleware to add the users object
    to the environ and then returns authenticate methods to check a password
    and a digest.
    """
    function = None
    users = None
    if len(authenticate_conf) < 1:
        raise AuthKitConfigError('Expected at least one authenticate key, not'
                                 ' %r'%authenticate_conf)
    if authenticate_conf.keys() == ['function']:
        function = authenticate_conf['function']
        if isinstance(function, (str, unicode)):
            function = eval_import(function)
    else:
        user_conf = strip_base(authenticate_conf, 'user.')
        if not user_conf:
            raise AuthKitConfigError('No authenticate function or users specified')
        else:
            if user_conf.has_key('encrypt'):
                if format == 'digest':
                    raise AuthKitConfigError('Encryption cannot be used with '
                        'digest authentication because the server needs to '
                        'know the password to generate the digest, try basic '
                        'or form and cookie authentication instead')
                enc_func = eval_import(user_conf['encrypt'])
                secret = user_conf.get('encrypt.secret','')
                def encrypt(password):
                    return enc_func(password, secret)
            else:
                encrypt = None
            user_object = 'authkit.users.UsersFromString'
            if 'type' in user_conf.keys():
                user_object = user_conf['type']
            if isinstance(user_object, (str, unicode)):
                user_object = eval_import(user_object)

            if not hasattr(user_object, "api_version"):
                users = user_object(user_conf['data'], encrypt)
                app = AddToEnviron(app, 'authkit.users', users)
                log.debug("authkit.users added to environ")
            elif user_object.api_version == 0.4:
                app = AddUsersObjectToEnviron(
                    app, 
                    'authkit.users', 
                    user_object, 
                    encrypt=encrypt, 
                    data=user_conf.get('data'),
                )
                log.debug("Setting up authkit.users middleware")
            else:
                raise Exception(
                    'Unknown API version %s for user management API'%(
                        users.api_version,
                    )
                )         
            if format == 'basic':
                function = valid_password
                log.debug("valid_password chosen %r", function)
            elif format == 'digest':
                log.debug("digest_password chosen %r", function)
                function = digest_password
            else:
                raise Exception('Invalid format for authenticate function %r' 
                                % format)
    return app, function, users
예제 #39
0
    def __init__(self, application, global_conf=None,
                 debug=NoDefault,
                 error_email=None,
                 error_log=None,
                 show_exceptions_in_wsgi_errors=NoDefault,
                 from_address=None,
                 smtp_server=None,
                 smtp_username=None,
                 smtp_password=None,
                 smtp_use_tls=False,
                 error_subject_prefix=None,
                 error_message=None,
                 xmlhttp_key=None,
                 reporters=None,
                 show_error_reason=None):
        from paste.util import converters
        self.application = application
        # @@: global_conf should be handled elsewhere in a separate
        # function for the entry point
        if global_conf is None:
            global_conf = {}
        if debug is NoDefault:
            debug = converters.asbool(global_conf.get('debug'))
        if show_exceptions_in_wsgi_errors is NoDefault:
            show_exceptions_in_wsgi_errors = converters.asbool(global_conf.get('show_exceptions_in_wsgi_errors'))
        self.debug_mode = converters.asbool(debug)
        if error_email is None:
            error_email = (global_conf.get('error_email')
                           or global_conf.get('admin_email')
                           or global_conf.get('webmaster_email')
                           or global_conf.get('sysadmin_email'))
        self.error_email = converters.aslist(error_email)
        self.error_log = error_log
        self.show_exceptions_in_wsgi_errors = show_exceptions_in_wsgi_errors
        if from_address is None:
            from_address = global_conf.get('error_from_address')
            if from_address is None:
                if self.error_email:
                    from_address = self.error_email[0]
                else:
                    from_address = 'errors@localhost'
        self.from_address = from_address
        if smtp_server is None:
            smtp_server = global_conf.get('smtp_server', 'localhost')
        self.smtp_server = smtp_server
        self.smtp_username = smtp_username or global_conf.get('smtp_username')
        self.smtp_password = smtp_password or global_conf.get('smtp_password')
        self.smtp_use_tls = smtp_use_tls or converters.asbool(global_conf.get('smtp_use_tls'))
        self.error_subject_prefix = error_subject_prefix or ''
        if error_message is None:
            error_message = global_conf.get('error_message')
        self.error_message = error_message
        if xmlhttp_key is None:
            xmlhttp_key = global_conf.get('xmlhttp_key', '_')
        self.xmlhttp_key = xmlhttp_key
        reporters = reporters or global_conf.get('error_reporters')
        if reporters and isinstance(reporters, basestring):
            reporter_strings = reporters.split()
            reporters = []
            for reporter_string in reporter_strings:
                reporter = import_string.eval_import(reporter_string)
                if isinstance(reporter, (type, types.ClassType)):
                    reporter = reporter()
                reporters.append(reporter)
        self.reporters = reporters or []

        if show_error_reason is None:
            show_error_reason = global_conf.get('show_error_reason')
        self.show_error_reason = converters.asbool(show_error_reason)
예제 #40
0
 def __init__(self,
              application,
              global_conf=None,
              debug=NoDefault,
              error_email=None,
              error_log=None,
              show_exceptions_in_wsgi_errors=NoDefault,
              from_address=None,
              smtp_server=None,
              smtp_username=None,
              smtp_password=None,
              smtp_use_tls=False,
              error_subject_prefix=None,
              error_message=None,
              xmlhttp_key=None,
              reporters=None):
     from paste.util import converters
     self.application = application
     # @@: global_conf should be handled elsewhere in a separate
     # function for the entry point
     if global_conf is None:
         global_conf = {}
     if debug is NoDefault:
         debug = converters.asbool(global_conf.get('debug'))
     if show_exceptions_in_wsgi_errors is NoDefault:
         show_exceptions_in_wsgi_errors = converters.asbool(
             global_conf.get('show_exceptions_in_wsgi_errors'))
     self.debug_mode = converters.asbool(debug)
     if error_email is None:
         error_email = (global_conf.get('error_email')
                        or global_conf.get('admin_email')
                        or global_conf.get('webmaster_email')
                        or global_conf.get('sysadmin_email'))
     self.error_email = converters.aslist(error_email)
     self.error_log = error_log
     self.show_exceptions_in_wsgi_errors = show_exceptions_in_wsgi_errors
     if from_address is None:
         from_address = global_conf.get('error_from_address')
         if from_address is None:
             if self.error_email:
                 from_address = self.error_email[0]
             else:
                 from_address = 'errors@localhost'
     self.from_address = from_address
     if smtp_server is None:
         smtp_server = global_conf.get('smtp_server', 'localhost')
     self.smtp_server = smtp_server
     self.smtp_username = smtp_username or global_conf.get('smtp_username')
     self.smtp_password = smtp_password or global_conf.get('smtp_password')
     self.smtp_use_tls = smtp_use_tls or converters.asbool(
         global_conf.get('smtp_use_tls'))
     self.error_subject_prefix = error_subject_prefix or ''
     if error_message is None:
         error_message = global_conf.get('error_message')
     self.error_message = error_message
     if xmlhttp_key is None:
         xmlhttp_key = global_conf.get('xmlhttp_key', '_')
     self.xmlhttp_key = xmlhttp_key
     reporters = reporters or global_conf.get('error_reporters')
     if reporters and isinstance(reporters, basestring):
         reporter_strings = reporters.split()
         reporters = []
         for reporter_string in reporter_strings:
             reporter = import_string.eval_import(reporter_string)
             if isinstance(reporter, (type, types.ClassType)):
                 reporter = reporter()
             reporters.append(reporter)
     self.reporters = reporters or []