def _base_plugin_maker(user_class=None, dbsession=None): """ Turn ``userclass`` and ``dbsession`` into Python objects. """ if user_class is None: raise ValueError("user_class must not be None") if dbsession is None: raise ValueError("dbsession must not be None") return resolveDotted(user_class), resolveDotted(dbsession)
def _base_plugin_maker(user_class=None, dbsession=None): """ Turn ``userclass`` and ``dbsession`` into Python objects. """ if user_class is None: raise ValueError('user_class must not be None') if dbsession is None: raise ValueError('dbsession must not be None') return resolveDotted(user_class), resolveDotted(dbsession)
def make_identification_plugin( fb_connect_field="fb_connect", db_session=None, user_class=None, fb_user_class=None, session_name=None, login_handler_path=None, logout_handler_paths=None, login_form_url=None, error_field='error', logged_in_url=None, logged_out_url=None, came_from_field='came_from', rememberer_name=None, md_provider_name='facebook_connect_md', fields='', ): if login_form_url is None: raise ValueError("login_form_url needs to be given") if rememberer_name is None: raise ValueError("rememberer_name needs to be given") if login_handler_path is None: raise ValueError("login_handler_path needs to be given") if logout_handler_paths is None: raise ValueError("logout_handler_paths needs to be given") if session_name is None: raise ValueError("session_name needs to be given") if logged_in_url is None: raise ValueError("logged_in_url needs to be given") if logged_out_url is None: raise ValueError("logged_out_url needs to be given") fields = [attr.strip(',') for attr in fields.split()] or None plugin = FacebookConnectIdentificationPlugin( fb_connect_field=fb_connect_field, error_field=error_field, db_session=resolveDotted(db_session), user_class=resolveDotted(user_class), fb_user_class=resolveDotted(fb_user_class), session_name=session_name, login_form_url=login_form_url, login_handler_path=login_handler_path, logout_handler_paths=logout_handler_paths, logged_in_url=logged_in_url, logged_out_url=logged_out_url, came_from_field=came_from_field, rememberer_name=rememberer_name, md_provider_name=md_provider_name, fields=fields, ) return plugin
def make_authenticator_plugin(query=None, conn_factory=None, compare_fn=None, **kw): from repoze.who.utils import resolveDotted if query is None: raise ValueError('query must be specified') if conn_factory is None: raise ValueError('conn_factory must be specified') try: conn_factory = resolveDotted(conn_factory)(**kw) except Exception as why: raise ValueError('conn_factory could not be resolved: %s' % why) if compare_fn is not None: compare_fn = resolveDotted(compare_fn) return SQLAuthenticatorPlugin(query, conn_factory, compare_fn)
def make_smtp_authenticator(dbsession, asm, dommodel, dam): "return smtp authenticator" for param in [('dbsession', dbsession), ('asm', asm), ('dommodel', dommodel), ('dam', dam)]: check_param(param[0], param[1]) session = resolveDotted(dbsession) authmodel = resolveDotted(asm) dmodel = resolveDotted(dommodel) damodel = resolveDotted(dam) authenticator = BaruwaSMTPAuthPlugin(session, authmodel, dmodel, damodel) return authenticator
def _load_from_callable(name, kwds, converters={}): """Load a plugin argument from dotted python name of callable. This function is a helper to load and possibly instanciate an argument to the plugin. It grabs the value from the dotted python name found in kwds[name]. If this is a callable, it it looks for arguments of the form kwds[name_*] and calls the object with them. """ # See if we actually have the named object. dotted_name = kwds.pop(name, None) if dotted_name is None: return None obj = resolveDotted(dotted_name) # Extract any arguments for the callable. obj_kwds = {} prefix = name + "_" for key in kwds.keys(): if key.startswith(prefix): obj_kwds[key[len(prefix):]] = kwds.pop(key) # To any type conversion on the arguments. for key, value in obj_kwds.iteritems(): converter = converters.get(key) if converter is not None: obj_kwds[key] = converter(value) # Call it if callable. if callable(obj): obj = obj(**obj_kwds) elif obj_kwds: raise ValueError("arguments provided for non-callable %r" % (name,)) return obj
def _load_object_from_kwds(name, kwds): """Load a plugin argument as an object created from the given kwds. This function is a helper to load and possibly instanciate an argument to the plugin. It grabs the value from the dotted python name found in kwds[name]. If this is a callable, it looks for arguments of the form kwds[name_*] and calls it with them to instanciate an object. """ # See if we actually have the named object. dotted_name = kwds.pop(name, None) if dotted_name is None: return None obj = resolveDotted(dotted_name) # Extract any arguments for the callable. obj_kwds = {} prefix = name + "_" for key in kwds.keys(): if key.startswith(prefix): obj_kwds[key[len(prefix):]] = kwds.pop(key) # Call it if callable. if callable(obj): obj = obj(**obj_kwds) elif obj_kwds: raise ValueError("arguments provided for non-callable %r" % (name,)) return obj
def _load_function_from_kwds(name, kwds): """Load a plugin argument as a function created from the given kwds. This function is a helper to load and possibly curry a callable argument to the plugin. It grabs the value from the dotted python name found in kwds[name] and checks that it is a callable. It looks for arguments of the form kwds[name_*] and curries them into the function as additional keyword argument before returning. """ # See if we actually have the named object. dotted_name = kwds.pop(name, None) if dotted_name is None: return None func = resolveDotted(dotted_name) # Check that it's a callable. if not callable(func): raise ValueError("Argument %r must be callable" % (name,)) # Curry in any keyword arguments. func_kwds = {} prefix = name + "_" for key in kwds.keys(): if key.startswith(prefix): func_kwds[key[len(prefix):]] = kwds.pop(key) # Return the original function if not currying anything. # This is both more effient and better for unit testing. if func_kwds: func = functools.partial(func, **func_kwds) return func
def make_metadata_plugin(name=None, query=None, conn_factory=None, filter=None, **kw): from repoze.who.utils import resolveDotted if name is None: raise ValueError('name must be specified') if query is None: raise ValueError('query must be specified') if conn_factory is None: raise ValueError('conn_factory must be specified') try: conn_factory = resolveDotted(conn_factory)(**kw) except Exception as why: raise ValueError('conn_factory could not be resolved: %s' % why) if filter is not None: filter = resolveDotted(filter) return SQLMetadataProviderPlugin(name, query, conn_factory, filter)
def make_plugin(secret=None, secretfile=None, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, userid_checker=None, ): from repoze.who.utils import resolveDotted if (secret is None and secretfile is None): raise ValueError("One of 'secret' or 'secretfile' must not be None.") if (secret is not None and secretfile is not None): raise ValueError("Specify only one of 'secret' or 'secretfile'.") if secretfile: secretfile = os.path.abspath(os.path.expanduser(secretfile)) if not os.path.exists(secretfile): raise ValueError("No such 'secretfile': %s" % secretfile) with open(secretfile) as f: secret = f.read().strip() if timeout: timeout = int(timeout) if reissue_time: reissue_time = int(reissue_time) if userid_checker is not None: userid_checker = resolveDotted(userid_checker) plugin = AuthTktCookiePlugin(secret, cookie_name, _bool(secure), _bool(include_ip), timeout, reissue_time, userid_checker, ) return plugin
def make_authenticator_plugin(query=None, conn_factory=None, compare_fn=None, **kw): """ Differs from repoze.who.plugins.sql.make_authenticator_plugin only in that kw is passed to SQLAuthenticatorPlugin. @type query: basestring @param query: SQL query to return the username and p @type conn_factory: function @param conn_factory: database connection factory @type compare_fn: function @param compare_fn: function to compare supplied and stored passwords @type kw: dict @param kw: additional configuration options that are passed to the SQLAuthenticatorPlugin constructor """ from repoze.who.utils import resolveDotted if query is None: raise ValueError('query must be specified') if conn_factory is None: raise ValueError('conn_factory must be specified') try: conn_factory = resolveDotted(conn_factory)(**kw) except Exception, why: raise ValueError('conn_factory could not be resolved: %s' % why)
def make_smtp_authenticator(dbsession, authsettingsmodel, domainmodel, domainaliasmodel): "return smtp authenticator" for param in [('dbsession', dbsession), ('authsettingsmodel', authsettingsmodel), ('domainmodel', domainmodel), ('domainaliasmodel', domainaliasmodel)]: check_param(param[0], param[1]) session = resolveDotted(dbsession) authmodel = resolveDotted(authsettingsmodel) dmodel = resolveDotted(domainmodel) damodel = resolveDotted(domainaliasmodel) authenticator = BaruwaSMTPAuthPlugin(session, authmodel, dmodel, damodel) return authenticator
def make_plugin(filename=None, check_fn=None): if filename is None: raise ValueError('filename must be specified') if check_fn is None: raise ValueError('check_fn must be specified') check = resolveDotted(check_fn) return HTPasswdPlugin(filename, check)
def _load_from_callable(name, kwds, converters={}): """Load a plugin argument from dotted python name of callable. This function is a helper to load and possibly instanciate an argument to the plugin. It grabs the value from the dotted python name found in kwds[name]. If this is a callable, it it looks for arguments of the form kwds[name_*] and calls the object with them. """ # See if we actually have the named object. dotted_name = kwds.pop(name, None) if dotted_name is None: return None obj = resolveDotted(dotted_name) # Extract any arguments for the callable. obj_kwds = {} prefix = name + "_" for key in kwds.keys(): if key.startswith(prefix): obj_kwds[key[len(prefix):]] = kwds.pop(key) # To any type conversion on the arguments. for key, value in obj_kwds.iteritems(): converter = converters.get(key) if converter is not None: obj_kwds[key] = converter(value) # Call it if callable. if callable(obj): obj = obj(**obj_kwds) elif obj_kwds: raise ValueError("arguments provided for non-callable %r" % (name, )) return obj
def make_plugin(secret=None, secretfile=None, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, userid_checker=None): from repoze.who.utils import resolveDotted # ckan specifics: # Get secret from beaker setting if necessary if secret is None or secret == u'somesecret': secret = config[u'beaker.session.secret'] # Session timeout and reissue time for auth cookie if timeout is None and config.get(u'who.timeout'): timeout = config.get(u'who.timeout') if reissue_time is None and config.get(u'who.reissue_time'): reissue_time = config.get(u'who.reissue_time') if timeout is not None and reissue_time is None: reissue_time = int(math.ceil(int(timeout) * 0.1)) # Set httponly based on config value. Default is True httponly = _bool(config.get(u'who.httponly', True)) # Set secure based on config value. Default is False secure = _bool(config.get(u'who.secure', False)) # Set samesite based on config value. Default is lax samesite = config.get(u'who.samesite', 'lax').lower() if samesite == 'none' and not secure: raise ValueError( 'SameSite=None requires the Secure attribute,' 'please set who.secure=True') # back to repoze boilerplate if (secret is None and secretfile is None): raise ValueError(u"One of 'secret' or 'secretfile' must not be None.") if (secret is not None and secretfile is not None): raise ValueError(u"Specify only one of 'secret' or 'secretfile'.") if secretfile: secretfile = os.path.abspath(os.path.expanduser(secretfile)) if not os.path.exists(secretfile): raise ValueError(u"No such 'secretfile': %s" % secretfile) secret = open(secretfile).read().strip() if timeout: timeout = int(timeout) if reissue_time: reissue_time = int(reissue_time) if userid_checker is not None: userid_checker = resolveDotted(userid_checker) plugin = CkanAuthTktCookiePlugin(httponly, samesite, secret, cookie_name, secure, _bool(include_ip), timeout, reissue_time, userid_checker) return plugin
def make_plugin(audiences, rememberer_name=None, postback_url=None, assertion_field=None, came_from_field=None, csrf_field=None, csrf_cookie_name=None, challenge_body=None, verifier=None, check_https=None, check_referer=None, **kwds): """Make a BrowserIDPlugin using values from a .ini config file. This is a helper function for loading a BrowserIDPlugin via the repoze.who .ini config file system. It converts its arguments from strings to the appropriate type then passes them on to the plugin. """ if not audiences: audiences = None elif isinstance(audiences, basestring): audiences = audiences.split() if isinstance(challenge_body, basestring): try: challenge_body = resolveDotted(challenge_body) except (ValueError, ImportError): with open(challenge_body, "rb") as f: challenge_body = f.read() if isinstance(verifier, basestring): verifier = resolveDotted(verifier) if callable(verifier): verifier_kwds = {} for key, value in kwds.iteritems(): if key.startswith("verifier_"): verifier_kwds[key[len("verifier_"):]] = value verifier = verifier(**verifier_kwds) if isinstance(check_https, basestring): check_https = str2bool(check_https) if isinstance(check_referer, basestring): check_referer = str2bool(check_referer) plugin = BrowserIDPlugin(audiences, rememberer_name, postback_url, assertion_field, came_from_field, csrf_field, csrf_cookie_name, challenge_body, verifier, check_https, check_referer) return plugin
def from_settings(cls, settings, prefix="who."): """Create a new WhoAuthenticationPolicy from app settings dict.""" api_factory = api_factory_from_settings(settings, prefix) callback = settings.get(prefix + "callback") if callback is not None: callback = resolveDotted(callback) if callback is not None: assert callable(callback) return cls(api_factory, callback)
def _base_plugin_maker(user_class=None): """ Turn ``userclass`` into Python object. """ if user_class is None: raise ValueError('user_class must not be None') return resolveDotted(user_class)
def resolveRegistrationForm(): custom_schema = request.environ["fi.infigo.account"].config["registration"].get("schema", None) if custom_schema: from repoze.who.utils import resolveDotted klass = resolveDotted(custom_schema) return klass() return RegistrationForm()
def make_rad_authenticator(dbsession, rsm, asm, dommodel, dam): "return radius authenticator" for param in [('dbsession', dbsession), ('rsm', rsm), ('asm', asm), ('dommodel', dommodel), ('dam', dam)]: check_param(param[0], param[1]) session = resolveDotted(dbsession) radmodel = resolveDotted(rsm) authmodel = resolveDotted(asm) dmodel = resolveDotted(dommodel) damodel = resolveDotted(dam) authenticator = BaruwaRadiusAuthPlugin(session, radmodel, authmodel, dmodel, damodel) return authenticator
def make_rad_authenticator(dbsession, radsettingsmodel, authsettingsmodel, domainmodel, domainaliasmodel): "return radius authenticator" for param in [('dbsession', dbsession), ('radsettingsmodel', radsettingsmodel), ('authsettingsmodel', authsettingsmodel), ('domainmodel', domainmodel), ('domainaliasmodel', domainaliasmodel)]: check_param(param[0], param[1]) session = resolveDotted(dbsession) radmodel = resolveDotted(radsettingsmodel) authmodel = resolveDotted(authsettingsmodel) dmodel = resolveDotted(domainmodel) damodel = resolveDotted(domainaliasmodel) authenticator = BaruwaRadiusAuthPlugin(session, radmodel, authmodel, dmodel, damodel) return authenticator
def from_settings(cls, settings, prefix="who."): """Create a new WhoAuthenticationPolicy from app settings dict.""" log.debug('from_settings: START') api_factory = api_factory_from_settings(settings, prefix) log.debug('from_settings -- API_FACTORY: %s ' % api_factory) callback = settings.get(prefix + "callback") if callback is not None: callback = resolveDotted(callback) if callback is not None: assert callable(callback) return cls(api_factory, callback)
def make_sa_authenticator(user_class=None, dbsession=None, user_name_translation=None, validate_password_translation=None): """Setup an SQLAlchemy authenticator""" if user_class is None: raise ValueError('user_class must not be None') if dbsession is None: raise ValueError('user_class must not be None') user_model = resolveDotted(user_class) dbsession_object = resolveDotted(dbsession) authenticator = SQLAlchemyAuthenticatorPlugin(user_model, dbsession_object) if user_name_translation: authenticator.translations['user_name'] = user_name_translation if validate_password_translation: authenticator.translations['validate_password'] = \ validate_password_translation return authenticator
def make_plugin(postback_url=None, came_from_field=None, challenge_body=None, rememberer_name=None, verifier_url=None, urlopen=None, audience=None): """Make a BrowserIDPlugin using values from a .ini config file. This is a helper function for loading a BrowserIDPlugin via the repoze.who .ini config file system. It converts its arguments from strings to the appropriate type then passes them on to the plugin. """ if isinstance(challenge_body, basestring): try: challenge_body = resolveDotted(challenge_body) except (ValueError, ImportError): with open(challenge_body, "rb") as f: challenge_body = f.read() if isinstance(urlopen, basestring): urlopen = resolveDotted(urlopen) if urlopen is not None: assert callable(urlopen) plugin = BrowserIDPlugin(postback_url, came_from_field, challenge_body, rememberer_name, verifier_url, urlopen, audience) return plugin
def make_plugin(secret=None, secretfile=None, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, userid_checker=None): from repoze.who.utils import resolveDotted # ckan specifics: # Get secret from beaker setting if necessary if secret is None or secret == 'somesecret': secret = config['beaker.session.secret'] # Session timeout and reissue time for auth cookie if timeout is None and config.get('who.timeout'): timeout = config.get('who.timeout') if reissue_time is None and config.get('who.reissue_time'): reissue_time = config.get('who.reissue_time') if timeout is not None and reissue_time is None: reissue_time = int(math.ceil(int(timeout) * 0.1)) # Set httponly based on config value. Default is True httponly = config.get('who.httponly', True) # Set secure based on config value. Default is False secure = config.get('who.secure', False) # back to repoze boilerplate if (secret is None and secretfile is None): raise ValueError("One of 'secret' or 'secretfile' must not be None.") if (secret is not None and secretfile is not None): raise ValueError("Specify only one of 'secret' or 'secretfile'.") if secretfile: secretfile = os.path.abspath(os.path.expanduser(secretfile)) if not os.path.exists(secretfile): raise ValueError("No such 'secretfile': %s" % secretfile) secret = open(secretfile).read().strip() if timeout: timeout = int(timeout) if reissue_time: reissue_time = int(reissue_time) if userid_checker is not None: userid_checker = resolveDotted(userid_checker) plugin = CkanAuthTktCookiePlugin(_bool(httponly), secret, cookie_name, _bool(secure), _bool(include_ip), timeout, reissue_time, userid_checker) return plugin
def make_plugin(plugin_cls, **kwargs): '''Instantiate a plugin Example configuration: [plugin:modeled_user] use = repoze.who.plugins.sqla.user:make_plugin user_cls = helloworld.model:User session_factory = helloworld.model:Session login_attribute = email ''' user_cls = resolveDotted(kwargs['user_cls']) verifyClass(IUserPassword, user_cls, tentative=True) session_factory = resolveDotted(kwargs['session_factory']) if not callable(session_factory): raise ValueError('The session factory should be callable!') login_attribute = kwargs.get('login_attribute') return plugin_cls(user_cls, session_factory, login_attribute)
def make_plugin(realm='', nonce_manager=None, domain=None, qop=None, get_password=None, get_pwdhash=None): """Make a DigestAuthPlugin using values from a .ini config file. This is a helper function for loading a DigestAuthPlugin via the repoze.who .ini config file system. It converts its arguments from strings to the appropriate type then passes them on to the plugin. """ if isinstance(nonce_manager, basestring): nonce_manager = resolveDotted(nonce_manager) if callable(nonce_manager): nonce_manager = nonce_manager() if isinstance(get_password, basestring): get_password = resolveDotted(get_password) if get_password is not None: assert callable(get_password) if isinstance(get_pwdhash, basestring): get_pwdhash = resolveDotted(get_pwdhash) if get_pwdhash is not None: assert callable(get_pwdhash) plugin = DigestAuthPlugin(realm, nonce_manager, domain, qop, get_password, get_pwdhash) return plugin
def find_plugin_translations(translations={}): """ Process global translations for :mod:`repoze.who`/:mod:`repoze.what` SQLAlchemy plugins. :param translations: The translation dictionary. :type translations: dict :return: The respective translations for the group and permission adapters, the authenticator and the MD provider. :rtype: dict """ group_adapter = {} permission_adapter = {} authenticator = {} mdprovider = {} if 'validate_password' in translations: authenticator['validate_password'] = translations['validate_password'] if 'dummy_validate_password' in translations: authenticator['dummy_validate_password'] = \ resolveDotted(translations['dummy_validate_password']) if 'user_name' in translations: group_adapter['item_name'] = translations['user_name'] authenticator['user_name'] = translations['user_name'] mdprovider['user_name'] = translations['user_name'] if 'users' in translations: group_adapter['items'] = translations['users'] if 'group_name' in translations: group_adapter['section_name'] = translations['group_name'] permission_adapter['item_name'] = translations['group_name'] if 'groups' in translations: group_adapter['sections'] = translations['groups'] permission_adapter['items'] = translations['groups'] if 'permission_name' in translations: permission_adapter['section_name'] = translations['permission_name'] if 'permissions' in translations: permission_adapter['sections'] = translations['permissions'] final_translations = { 'group_adapter': group_adapter, 'permission_adapter': permission_adapter, 'authenticator': authenticator, 'mdprovider': mdprovider } return final_translations
def find_plugin_translations(translations={}): """ Process global translations for :mod:`repoze.who`/:mod:`repoze.what` SQLAlchemy plugins. :param translations: The translation dictionary. :type translations: dict :return: The respective translations for the group and permission adapters, the authenticator and the MD provider. :rtype: dict """ group_adapter = {} permission_adapter = {} authenticator = {} mdprovider = {} if 'validate_password' in translations: authenticator['validate_password'] = translations['validate_password'] if 'dummy_validate_password' in translations: authenticator['dummy_validate_password'] = \ resolveDotted(translations['dummy_validate_password']) if 'user_name' in translations: group_adapter['item_name'] = translations['user_name'] authenticator['user_name'] = translations['user_name'] mdprovider['user_name'] = translations['user_name'] if 'users' in translations: group_adapter['items'] = translations['users'] if 'group_name' in translations: group_adapter['section_name'] = translations['group_name'] permission_adapter['item_name'] = translations['group_name'] if 'groups' in translations: group_adapter['sections'] = translations['groups'] permission_adapter['items'] = translations['groups'] if 'permission_name' in translations: permission_adapter['section_name'] = translations['permission_name'] if 'permissions' in translations: permission_adapter['sections'] = translations['permissions'] final_translations = { 'group_adapter': group_adapter, 'permission_adapter': permission_adapter, 'authenticator': authenticator, 'mdprovider': mdprovider} return final_translations
def make_plugin( secret=None, secretfile=None, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, userid_checker=None, digest_algo=auth_tkt.DEFAULT_DIGEST, ): from repoze.who.utils import resolveDotted if (secret is None and secretfile is None): raise ValueError("One of 'secret' or 'secretfile' must not be None.") if (secret is not None and secretfile is not None): raise ValueError("Specify only one of 'secret' or 'secretfile'.") if secretfile: secretfile = os.path.abspath(os.path.expanduser(secretfile)) if not os.path.exists(secretfile): raise ValueError("No such 'secretfile': %s" % secretfile) with open(secretfile) as f: secret = f.read().strip() if timeout: timeout = int(timeout) if reissue_time: reissue_time = int(reissue_time) if userid_checker is not None: userid_checker = resolveDotted(userid_checker) if isinstance(digest_algo, str): try: digest_algo = getattr(hashlib, digest_algo) except AttributeError: raise ValueError("No such 'digest_algo': %s" % digest_algo) plugin = AuthTktCookiePlugin( secret, cookie_name, _bool(secure), _bool(include_ip), timeout, reissue_time, userid_checker, digest_algo, ) return plugin
def test_it(self): # --- Setting it up --- dummy_fn = 'tests.fixture.model:dummy_validate_password' translations = { 'validate_password': '******', 'user_name': 'member_name', 'users': 'members', 'group_name': 'team_name', 'groups': 'teams', 'permission_name': 'perm_name', 'permissions': 'perms', 'dummy_validate_password': dummy_fn } plugin_translations = find_plugin_translations(translations) # --- Testing it --- # Group translations group_translations = { 'item_name': translations['user_name'], 'items': translations['users'], 'section_name': translations['group_name'], 'sections': translations['groups'], } self.assertEqual(group_translations, plugin_translations['group_adapter']) # Permission translations perm_translations = { 'item_name': translations['group_name'], 'items': translations['groups'], 'section_name': translations['permission_name'], 'sections': translations['permissions'], } self.assertEqual(perm_translations, plugin_translations['permission_adapter']) # Authenticator translations auth_translations = { 'user_name': translations['user_name'], 'validate_password': translations['validate_password'], 'dummy_validate_password': resolveDotted(dummy_fn) } self.assertEqual(auth_translations, plugin_translations['authenticator']) # MD Provider translations md_translations = {'user_name': translations['user_name']} self.assertEqual(md_translations, plugin_translations['mdprovider'])
def make_plugin(secret=None, secretfile=None, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, userid_checker=None, digest_algo=auth_tkt.DEFAULT_DIGEST, ): from repoze.who.utils import resolveDotted if (secret is None and secretfile is None): raise ValueError("One of 'secret' or 'secretfile' must not be None.") if (secret is not None and secretfile is not None): raise ValueError("Specify only one of 'secret' or 'secretfile'.") if secretfile: secretfile = os.path.abspath(os.path.expanduser(secretfile)) if not os.path.exists(secretfile): raise ValueError("No such 'secretfile': %s" % secretfile) with open(secretfile) as f: secret = f.read().strip() if timeout: timeout = int(timeout) if reissue_time: reissue_time = int(reissue_time) if userid_checker is not None: userid_checker = resolveDotted(userid_checker) if isinstance(digest_algo, str): try: digest_algo = getattr(hashlib, digest_algo) except AttributeError: raise ValueError("No such 'digest_algo': %s" % digest_algo) plugin = AuthTktCookiePlugin(secret, cookie_name, _bool(secure), _bool(include_ip), timeout, reissue_time, userid_checker, digest_algo, ) return plugin
def make_plugin( serv_url, secret=None, secretfile=None, cookie_name='auth_tkt', secure=False, include_ip=True, timeout=None, reissue_time=None, userid_checker=None, ): ''' Build the identifier plugin ''' if (secret is None and secretfile is None): raise ValueError("One of 'secret' or 'secretfile' must not be None.") if (secret is not None and secretfile is not None): raise ValueError("Specify only one of 'secret' or 'secretfile'.") if secretfile: secretfile = os.path.abspath(os.path.expanduser(secretfile)) if not os.path.exists(secretfile): raise ValueError("No such 'secretfile': %s" % secretfile) secret = open(secretfile).read().strip() if timeout: timeout = int(timeout) if reissue_time: reissue_time = int(reissue_time) if userid_checker is not None: userid_checker = resolveDotted(userid_checker) plugin = CustomCookiePlugin( secret, serv_url, cookie_name, _bool(secure), _bool(include_ip), timeout, reissue_time, userid_checker, ) return plugin
def make_plugin(serv_url, secret=None, secretfile=None, cookie_name='auth_tkt', secure=False, include_ip=True, timeout=None, reissue_time=None, userid_checker=None, ): ''' Build the identifier plugin ''' if (secret is None and secretfile is None): raise ValueError("One of 'secret' or 'secretfile' must not be None.") if (secret is not None and secretfile is not None): raise ValueError("Specify only one of 'secret' or 'secretfile'.") if secretfile: secretfile = os.path.abspath(os.path.expanduser(secretfile)) if not os.path.exists(secretfile): raise ValueError("No such 'secretfile': %s" % secretfile) secret = open(secretfile).read().strip() if timeout: timeout = int(timeout) if reissue_time: reissue_time = int(reissue_time) if userid_checker is not None: userid_checker = resolveDotted(userid_checker) plugin = CustomCookiePlugin(secret, serv_url, cookie_name, _bool(secure), _bool(include_ip), timeout, reissue_time, userid_checker, ) return plugin
def authenticate(self, environ, identity): "Authenticate identity" try: if check_failed_logins(environ): raise TypeError login = identity['login'] username, domain = login.split('@') ldapsettings = self.dbsession.query(self.ldapsettingsmodel, self.authsettingsmodel.address, self.authsettingsmodel.port, self.authsettingsmodel.split_address, self.domainmodel.name)\ .join(self.authsettingsmodel)\ .join(self.domainmodel)\ .filter(self.authsettingsmodel.enabled == True)\ .filter(self.domainmodel.status == True)\ .filter(or_(self.domainmodel.name == domain, func._(and_(\ self.domainmodel.id == self.alias.domain_id, self.alias.name == domain, self.alias.status == True) ) )).all() (settings, address, port, split_address, domain_name) = ldapsettings[0] ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 5) ldap_uri = make_ldap_uri(address, port) ldap_connection = make_ldap_connection(ldap_uri) kwargs = dict(naming_attribute=settings.nameattribute, returned_id=self.returned_id, bind_dn=settings.binddn, bind_pass=settings.bindpw, start_tls=settings.usetls) if domain != domain_name: # override alias domain domain = domain_name if settings.usesearch: ldap_module = 'LDAPSearchAuthenticatorPlugin' # build_search_filters(kwargs, settings.search_scope, # settings.searchfilter, domain, # login, username) kwargs['search_scope'] = settings.search_scope if settings.searchfilter != '': params = [] domaindn = ','.join( ['dc=' + part for part in domain.split('.')]) mapping = { '%n': login, '%u': username, '%d': domain, '%D': domaindn } searchfilter = escape_filter_chars(settings.searchfilter) for key in ['%n', '%u', '%d', '%D']: for _ in xrange(searchfilter.count(key)): searchfilter = searchfilter.replace(key, '%s', 1) params.append(mapping[key]) searchfilter = filter_format(searchfilter, params) kwargs['filterstr'] = searchfilter else: ldap_module = 'LDAPAuthenticatorPlugin' if split_address: identity['login'] = username else: # use main domain name not alias reset above identity['login'] = "******" % (username, domain) auth = resolveDotted('repoze.who.plugins.ldap:%s' % ldap_module) ldap_auth = auth(ldap_connection, settings.basedn, **kwargs) userid = ldap_auth.authenticate(environ, identity) fulladdr = "%s@%s" % (username, domain) return userid if userid is None or '@' in userid else fulladdr except (KeyError, TypeError, ValueError, AttributeError, NoResultFound, IndexError, ldap.LDAPError): return None
def make_authenticator_plugin(query=None, conn_factory=None, compare_fn=None, **kw): from repoze.who.utils import resolveDotted if query is None: raise ValueError('query must be specified') if conn_factory is None: raise ValueError('conn_factory must be specified') try: conn_factory = resolveDotted(conn_factory)(**kw) except Exception, why: raise ValueError('conn_factory could not be resolved: %s' % why) if compare_fn is not None: compare_fn = resolveDotted(compare_fn) return SQLAuthenticatorPlugin(query, conn_factory, compare_fn) def make_metadata_plugin(name=None, query=None, conn_factory=None, filter=None, **kw): from repoze.who.utils import resolveDotted if name is None: raise ValueError('name must be specified') if query is None: raise ValueError('query must be specified') if conn_factory is None: raise ValueError('conn_factory must be specified')
del identity['__userid'] identity[self.name] = result def make_authenticator_plugin(query=None, conn_factory=None, compare_fn=None, **kw): from repoze.who.utils import resolveDotted if query is None: raise ValueError('query must be specified') if conn_factory is None: raise ValueError('conn_factory must be specified') try: conn_factory = resolveDotted(conn_factory)(**kw) except Exception, why: raise ValueError('conn_factory could not be resolved: %s' % why) if compare_fn is not None: compare_fn = resolveDotted(compare_fn) return SQLAuthenticatorPlugin(query, conn_factory, compare_fn) def make_metadata_plugin(name=None, query=None, conn_factory=None, filter=None, **kw): from repoze.who.utils import resolveDotted if name is None: raise ValueError('name must be specified') if query is None: raise ValueError('query must be specified') if conn_factory is None: raise ValueError('conn_factory must be specified') try: conn_factory = resolveDotted(conn_factory)(**kw) except Exception, why: raise ValueError('conn_factory could not be resolved: %s' % why)
def make_authenticator_plugin(query=None, conn_factory=None, compare_fn=None, **kw): """ Differs from repoze.who.plugins.sql.make_authenticator_plugin only in that kw is passed to SQLAuthenticatorPlugin. @type query: basestring @param query: SQL query to return the username and p @type conn_factory: function @param conn_factory: database connection factory @type compare_fn: function @param compare_fn: function to compare supplied and stored passwords @type kw: dict @param kw: additional configuration options that are passed to the SQLAuthenticatorPlugin constructor """ from repoze.who.utils import resolveDotted if query is None: raise ValueError('query must be specified') if conn_factory is None: raise ValueError('conn_factory must be specified') try: conn_factory = resolveDotted(conn_factory)(**kw) except Exception, why: raise ValueError('conn_factory could not be resolved: %s' % why) if compare_fn is not None: compare_fn = resolveDotted(compare_fn) return SQLAuthenticatorPlugin(query, conn_factory, compare_fn, **kw)
def authenticate(self, environ, identity): "Authenticate identity" try: if check_failed_logins(environ): raise TypeError login = identity['login'] username, domain = login.split('@') ldapsettings = self.dbsession.query(self.ldapsettingsmodel, self.authsettingsmodel.address, self.authsettingsmodel.port, self.authsettingsmodel.split_address, self.domainmodel.name)\ .join(self.authsettingsmodel)\ .join(self.domainmodel)\ .filter(self.authsettingsmodel.enabled == True)\ .filter(self.domainmodel.status == True)\ .filter(or_(self.domainmodel.name == domain, func._(and_(\ self.domainmodel.id == self.alias.domain_id, self.alias.name == domain, self.alias.status == True) ) )).all() (settings, address, port, split_address, domain_name) = ldapsettings[0] ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 5) ldap_uri = make_ldap_uri(address, port) ldap_connection = make_ldap_connection(ldap_uri) kwargs = dict(naming_attribute=settings.nameattribute, returned_id=self.returned_id, bind_dn=settings.binddn, bind_pass=settings.bindpw, start_tls=settings.usetls) if domain != domain_name: # override alias domain domain = domain_name if settings.usesearch: ldap_module = 'LDAPSearchAuthenticatorPlugin' # build_search_filters(kwargs, settings.search_scope, # settings.searchfilter, domain, # login, username) kwargs['search_scope'] = settings.search_scope if settings.searchfilter != '': params = [] domaindn = ','.join(['dc=' + part for part in domain.split('.')]) mapping = { '%n':login, '%u':username, '%d':domain, '%D': domaindn } searchfilter = escape_filter_chars(settings.searchfilter) for key in ['%n', '%u', '%d', '%D']: for _ in xrange(searchfilter.count(key)): searchfilter = searchfilter.replace(key, '%s', 1) params.append(mapping[key]) searchfilter = filter_format(searchfilter, params) kwargs['filterstr'] = searchfilter else: ldap_module = 'LDAPAuthenticatorPlugin' if split_address: identity['login'] = username else: # use main domain name not alias reset above identity['login'] = "******" % (username, domain) auth = resolveDotted('repoze.who.plugins.ldap:%s' % ldap_module) ldap_auth = auth(ldap_connection, settings.basedn, **kwargs) userid = ldap_auth.authenticate(environ, identity) fulladdr = "%s@%s" % (username, domain) return userid if userid is None or '@' in userid else fulladdr except (KeyError, TypeError, ValueError, AttributeError, NoResultFound, IndexError, ldap.LDAPError): return None
def _check_auth(self, app, options): """ Check that the ``app`` is secured with Repoze auth using the expected ``options``. """ # === Checking the most important part: The form plugin's settings. main_identifier = app.name_registry.get("main_identifier") challenger = app.name_registry['form'] if options['form_identifies']: assert main_identifier == challenger, "The form identifies too" if options.get("form_plugin"): # A custom form was set: self.assertEqual(form_plugin, main_identifier) else: # The default form plugin must have been used: self._in_registry(app, "form", FriendlyFormPlugin) # Checking that its options are correct: self.assertEqual(challenger.login_form_url, options['login_url']) self.assertEqual(challenger.login_handler_path, options['login_handler']) self.assertEqual(challenger.post_login_url, options['post_login_url']) self.assertEqual(challenger.logout_handler_path, options['logout_handler']) self.assertEqual(challenger.post_logout_url, options['post_logout_url']) self.assertEqual(challenger.login_counter_name, options['login_counter_name']) self.assertEqual(challenger.charset, options['charset']) # === Checking the authenticator: self._in_registry(app, "sqlauth", SQLAlchemyAuthenticatorPlugin) authenticator = app.name_registry['sqlauth'] self.assertEqual(authenticator.user_class, options['user_class']) self.assertEqual(authenticator.translations['user_name'], options['translations']['user_name']) self.assertEqual(authenticator.translations['validate_password'], options['translations']['validate_password']) dummy_fn = options['translations']['dummy_validate_password'] if dummy_fn is not None: dummy_fn = resolveDotted(dummy_fn) self.assertEqual(authenticator.translations['dummy_validate_password'], dummy_fn) self.assertEqual(authenticator.dbsession, options['dbsession']) # === Checking the metadata provider: self._in_registry(app, "sql_user_md", SQLAlchemyUserMDPlugin) mdprovider = app.name_registry['sql_user_md'] self.assertEqual(mdprovider.user_class, options['user_class']) self.assertEqual(mdprovider.translations['user_name'], options['translations']['user_name']) self.assertEqual(mdprovider.dbsession, options['dbsession']) # === Checking the cookie plugin: self._in_registry(app, "cookie", AuthTktCookiePlugin) cookie = app.name_registry['cookie'] self.assertEqual(cookie.cookie_name, options['cookie_name']) self.assertEqual(cookie.secret, options['cookie_secret']) self.assertEqual(cookie.timeout, options['cookie_timeout']) self.assertEqual(cookie.reissue_time, options['cookie_reissue_time']) # === Checking the repoze.what settings: self._in_registry(app, "authorization_md", AuthorizationMetadata) authz_md = app.name_registry['authorization_md'] group_adapters = authz_md.group_adapters permission_adapters = authz_md.permission_adapters if options['group_class'] and options['permission_class']: # The group/permission pattern is being used. sql_groups = group_adapters['sql_auth'] sql_permissions = permission_adapters['sql_auth'] # Checking all the settings in the SQLAlchemy adapters: self.assertEquals(sql_groups.children_class, options['user_class']) self.assertEquals(sql_groups.parent_class, sql_permissions.children_class, options['group_class']) self.assertEquals(sql_permissions.parent_class, options['permission_class']) self.assertEquals(options['dbsession'], sql_groups.dbsession, sql_permissions.dbsession) # Finally, let's check their translations: self.assertEqual(sql_groups.translations['items'], options['translations']['users']) self.assertEqual(sql_groups.translations['item_name'], options['translations']['user_name']) self.assertEquals(sql_groups.translations['sections'], sql_permissions.translations['items'], options['translations']['groups']) self.assertEquals(sql_groups.translations['section_name'], sql_permissions.translations['item_name'], options['translations']['group_name']) self.assertEqual(sql_permissions.translations['sections'], options['translations']['permissions']) self.assertEqual(sql_permissions.translations['section_name'], options['translations']['permission_name']) else: self.assertEquals(permission_adapters, group_adapters, None)
def make_sa_authenticator(user_class=None, dbsession=None, user_name_translation=None, validate_password_translation=None, dummy_validate_password_translation=None): """ Configure :class:`SQLAlchemyAuthenticatorPlugin`. :param user_class: The SQLAlchemy/Elixir class for the users. :type user_class: str :param dbsession: The SQLAlchemy/Elixir session. :type dbsession: str :param user_name_translation: The translation for ``user_name``, if any. :type user_name_translation: str :param validate_password_translation: The translation for ``validate_password``, if any. :type validate_password_translation: str :param dummy_validate_password_translation: The translation for ``dummy_validate_password``, if any. :type dummy_validate_password_translation: function :return: The authenticator. :rtype: SQLAlchemyAuthenticatorPlugin Example from an ``*.ini`` file:: # ... [plugin:sa_auth] use = repoze.who.plugins.sa:make_sa_authenticator user_class = yourcoolproject.model:User dbsession = yourcoolproject.model:DBSession # ... Or, if you need translations:: # ... [plugin:sa_auth] use = repoze.who.plugins.sa:make_sa_authenticator user_class = yourcoolproject.model:User dbsession = yourcoolproject.model:DBSession user_name_translation = username validate_password_translation = verify_password dummy_validate_password_translation = yourcoolproject.security:validate # ... .. versionadded:: 1.0.1 Support for ``dummy_validate_password_translation`` was added. """ user_model, dbsession_object = _base_plugin_maker(user_class, dbsession) authenticator = SQLAlchemyAuthenticatorPlugin(user_model, dbsession_object) if user_name_translation: authenticator.translations['user_name'] = user_name_translation if validate_password_translation: authenticator.translations['validate_password'] = \ validate_password_translation if dummy_validate_password_translation: authenticator.translations['dummy_validate_password'] = \ resolveDotted(dummy_validate_password_translation) return authenticator