a fWc@sdZddlmZddlZddlZeeZddlZddl Z ddl m Z ddl m Z ddlmZmZmZddlmZmZddlmZmZmZmZmZmZmZmZdd lm Z dd l!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,dd l-m.Z.m/Z/gd Z0e1Z2d dZ3e4dgZ5e6e7e7e7e3e7dZ8ddZ9e:d ddZ;e4ddgZGddde1Z?Gddde1Z@Gddde@ZAdS)!z-passlib.context - CryptContext implementation)with_statementN)warn)exc)ExpectedStringErrorExpectedTypeErrorPasslibConfigWarning)get_crypt_handler_validate_handler_name)handlersto_bytes to_unicode splitcommaas_booltimerrng getrandstr) BASE64_CHARS) iteritems num_typesirangePY2PY3unicodeSafeConfigParserNativeStringIOBytesIOunicode_or_bytes_typesnative_string_types)deprecated_methodmemoized_property) CryptContextLazyCryptContext CryptPolicycCsF|drt|ddSz t|WSty@t|YS0dS)z>parse vary_rounds string to percent as [0,1) float, or integer%{Gz?N)endswithfloatrstripint ValueErrorvaluer,3/usr/lib/python3.9/site-packages/passlib/context.py_coerce_vary_rounds*s    r.Zsalt)Z min_roundsZ max_roundsZdefault_rounds vary_roundsZ salt_sizecCst|jd|uS)z3detect if handler is registered or a custom handlerN)rnamehandlerr,r,r-_is_handler_registeredCsr3cCsdS)z dummy function patched into handler.needs_update() by _CryptConfig when hash alg has been deprecated for context. Tr,)hashsecretr,r,r-_always_needs_updateGsr6Ztruncate_errorr/zaThe CryptPolicy class has been deprecated as of Passlib 1.6, and will be removed in Passlib 1.8. c@seZdZdZed)ddZed*ddZed+d d Zed,d d Zd dZ dZ dZ ddZ ddZ ddZd-ddZd.ddZd/ddZd0ddZd1dd Zd2d!d"Zd3d#d$Zd4d%d&Zd5d'd(ZdS)6r"a .. deprecated:: 1.6 This class has been deprecated, and will be removed in Passlib 1.8. All of its functionality has been rolled into :class:`CryptContext`. This class previously stored the configuration options for the CryptContext class. In the interest of interface simplification, all of this class' functionality has been rolled into the CryptContext class itself. The documentation for this class is now focused on documenting how to migrate to the new api. Additionally, where possible, the deprecation warnings issued by the CryptPolicy methods will list the replacement call that should be used. Constructors ============ CryptPolicy objects can be constructed directly using any of the keywords accepted by :class:`CryptContext`. Direct uses of the :class:`!CryptPolicy` constructor should either pass the keywords directly into the CryptContext constructor, or to :meth:`CryptContext.update` if the policy object was being used to update an existing context object. In addition to passing in keywords directly, CryptPolicy objects can be constructed by the following methods: .. automethod:: from_path .. automethod:: from_string .. automethod:: from_source .. automethod:: from_sources .. automethod:: replace Introspection ============= All of the informational methods provided by this class have been deprecated by identical or similar methods in the :class:`CryptContext` class: .. automethod:: has_schemes .. automethod:: schemes .. automethod:: iter_handlers .. automethod:: get_handler .. automethod:: get_options .. automethod:: handler_is_deprecated .. automethod:: get_min_verify_time Exporting ========= .. automethod:: iter_config .. automethod:: to_dict .. automethod:: to_file .. automethod:: to_string .. note:: CryptPolicy are immutable. Use the :meth:`replace` method to mutate existing instances. .. deprecated:: 1.6 passlibutf-8cCs&ttdtdd|t|||dS)aWcreate a CryptPolicy instance from a local file. .. deprecated:: 1.6 Creating a new CryptContext from a file, which was previously done via ``CryptContext(policy=CryptPolicy.from_path(path))``, can now be done via ``CryptContext.from_path(path)``. See :meth:`CryptContext.from_path` for details. Updating an existing CryptContext from a file, which was previously done ``context.policy = CryptPolicy.from_path(path)``, can now be done via ``context.load_path(path)``. See :meth:`CryptContext.load_path` for details. zInstead of ``CryptPolicy.from_path(path)``, use ``CryptContext.from_path(path)`` or ``context.load_path(path)`` for an existing CryptContext. stacklevel_internal_context)r _preambleDeprecationWarningr from_path)clspathsectionencodingr,r,r-r@s zCryptPolicy.from_pathcCs&ttdtdd|t|||dS)aUcreate a CryptPolicy instance from a string. .. deprecated:: 1.6 Creating a new CryptContext from a string, which was previously done via ``CryptContext(policy=CryptPolicy.from_string(data))``, can now be done via ``CryptContext.from_string(data)``. See :meth:`CryptContext.from_string` for details. Updating an existing CryptContext from a string, which was previously done ``context.policy = CryptPolicy.from_string(data)``, can now be done via ``context.load(data)``. See :meth:`CryptContext.load` for details. zInstead of ``CryptPolicy.from_string(source)``, use ``CryptContext.from_string(source)`` or ``context.load(source)`` for an existing CryptContext.r9r:r<)rr>r?r from_string)rAsourcerCrDr,r,r-rEs zCryptPolicy.from_stringTcs|rttdtddttr$SttrB|tfidStttfsdt dt fn@t fdddDs d s|t dS|tdSd S) acreate a CryptPolicy instance from some source. this method autodetects the source type, and invokes the appropriate constructor automatically. it attempts to detect whether the source is a configuration string, a filepath, a dictionary, or an existing CryptPolicy instance. .. deprecated:: 1.6 Create a new CryptContext, which could previously be done via ``CryptContext(policy=CryptPolicy.from_source(source))``, should now be done using an explicit method: the :class:`CryptContext` constructor itself, :meth:`CryptContext.from_path`, or :meth:`CryptContext.from_string`. Updating an existing CryptContext, which could previously be done via ``context.policy = CryptPolicy.from_source(source)``, should now be done using an explicit method: :meth:`CryptContext.update`, or :meth:`CryptContext.load`. zInstead of ``CryptPolicy.from_source()``, use ``CryptContext.from_string(path)`` or ``CryptContext.from_path(source)``, as appropriate.r9r:r<zAsource must be CryptPolicy, dict, config string, or file path: %rc3s|]}|vVqdSNr,).0crFr,r- z*CryptPolicy.from_source..z z ./;:N)rr>r? isinstancer"dictr bytesr TypeErrortypeanystriprEr@)rArF_warnr,rJr- from_sources"   zCryptPolicy.from_sourcecCs|rttdtddt|dkr*tdt|dkrH|j|dddSi}|D]"}||j|ddjjd d qP|t fi|d S) acreate a CryptPolicy instance by merging multiple sources. each source is interpreted as by :meth:`from_source`, and the results are merged together. .. deprecated:: 1.6 Instead of using this method to merge multiple policies together, a :class:`CryptContext` instance should be created, and then the multiple sources merged together via :meth:`CryptContext.load`. zwInstead of ``CryptPolicy.from_sources()``, use the various CryptContext constructors followed by ``context.update()``.r9r:rzno sources specifiedFrTTresolver<) rr>r?lenr)rUupdate_contextto_dictr )rAsourcesrTkwdsrFr,r,r- from_sourcess    zCryptPolicy.from_sourcescOs\|jrttdtddnttdtdd|g}|r@|||rN||tj|ddS)zcreate a new CryptPolicy, optionally updating parts of the existing configuration. .. deprecated:: 1.6 Callers of this method should :meth:`CryptContext.update` or :meth:`CryptContext.copy` instead. zXInstead of ``context.policy.replace()``, use ``context.update()`` or ``context.copy()``.r9r:zzInstead of ``CryptPolicy().replace()``, create a CryptContext instance and use ``context.update()`` or ``context.copy()``.FrW) _stub_policyrr>r?extendappendr"r`)selfargsr_r^r,r,r-replaces"  zCryptPolicy.replaceNFcOsx|dd}|r&||_|dd|_nN|rRt|dkr>td|rJtd|d}ttdtd d tfi||_dS) Nr=raFrVz%only one positional argument acceptedz&cannot specify positional arg and kwdsrzInstead of constructing a CryptPolicy instance, create a CryptContext directly, or use ``context.update()`` and ``context.load()`` to reconfigure existing CryptContext instances.r9r:) popr\rarZrPrr>r?r )rdrer_contextr,r,r-__init__1s"  zCryptPolicy.__init__cCs:|jrttdtddnttdtddt|jS)zreturn True if policy defines *any* schemes for use. .. deprecated:: 1.6 applications should use ``bool(context.schemes())`` instead. see :meth:`CryptContext.schemes`. zMInstead of ``context.policy.has_schemes()``, use ``bool(context.schemes())``.r9r:zoInstead of ``CryptPolicy().has_schemes()``, create a CryptContext instance and use ``bool(context.schemes())``.)rarr>r?boolr\schemesrdr,r,r- has_schemesJszCryptPolicy.has_schemescCs<|jrttdtddnttdtdd|jjdddS)zreturn iterator over handlers defined in policy. .. deprecated:: 1.6 applications should use ``context.schemes(resolve=True))`` instead. see :meth:`CryptContext.schemes`. zUInstead of ``context.policy.iter_handlers()``, use ``context.schemes(resolve=True)``.r9r:zwInstead of ``CryptPolicy().iter_handlers()``, create a CryptContext instance and use ``context.schemes(resolve=True)``.TrY unconfigured)rarr>r?r\rkrlr,r,r- iter_handlers^szCryptPolicy.iter_handlerscCs@|jrttdtddnttdtddt|jj|ddS)zreturn list of schemes defined in policy. .. deprecated:: 1.6 applications should use :meth:`CryptContext.schemes` instead. zCInstead of ``context.policy.schemes()``, use ``context.schemes()``.r9r:zeInstead of ``CryptPolicy().schemes()``, create a CryptContext instance and use ``context.schemes()``.Trn)rarr>r?listr\rkrdrYr,r,r-rkrszCryptPolicy.schemescCsf|jrttdtddnttdtddz|jj||ddWSty`|rVnYdSYn0dS)a8return handler as specified by name, or default handler. .. deprecated:: 1.6 applications should use :meth:`CryptContext.handler` instead, though note that the ``required`` keyword has been removed, and the new method will always act as if ``required=True``. zGInstead of ``context.policy.get_handler()``, use ``context.handler()``.r9r:ziInstead of ``CryptPolicy().get_handler()``, create a CryptContext instance and use ``context.handler()``.TroN)rarr>r?r\r2KeyError)rdr0categoryrequiredr,r,r- get_handlers" zCryptPolicy.get_handlercCstdtdddS)arget min_verify_time setting for policy. .. deprecated:: 1.6 min_verify_time option will be removed entirely in passlib 1.8 .. versionchanged:: 1.7 this method now always returns the value automatically calculated by :meth:`CryptContext.min_verify_time`, any value specified by policy is ignored. znget_min_verify_time() and min_verify_time option is deprecated and ignored, and will be removed in Passlib 1.8r9r:r)rr?)rdrur,r,r-get_min_verify_times zCryptPolicy.get_min_verify_timecCsP|jrttdtddnttdtddt|dr<|j}|jj||dS)aLreturn dictionary of options specific to a given handler. .. deprecated:: 1.6 this method has no direct replacement in the 1.6 api, as there is not a clearly defined use-case. however, examining the output of :meth:`CryptContext.to_dict` should serve as the closest alternative. z=``context.policy.get_options()`` will no longer be available.r9r:z<``CryptPolicy().get_options()`` will no longer be available.r0r) rarr>r?hasattrr0r\_config_get_record_options_with_flagrdr0rur,r,r- get_optionss  zCryptPolicy.get_optionscCsL|jrttdtddnttdtddt|dr<|j}|j||jS)aBcheck if handler has been deprecated by policy. .. deprecated:: 1.6 this method has no direct replacement in the 1.6 api, as there is not a clearly defined use-case. however, examining the output of :meth:`CryptContext.to_dict` should serve as the closest alternative. zG``context.policy.handler_is_deprecated()`` will no longer be available.r9r:zF``CryptPolicy().handler_is_deprecated()`` will no longer be available.r0) rarr>r?ryr0r\r2 deprecatedr|r,r,r-handler_is_deprecateds  z!CryptPolicy.handler_is_deprecatedcsz|jrttdtddnttdtdd|j|rPfddddd }njd d fd d j|DS)ziterate over key/value pairs representing the policy object. .. deprecated:: 1.6 applications should use :meth:`CryptContext.to_dict` instead. zOInstead of ``context.policy.iter_config()``, use ``context.to_dict().items()``.r9r:zqInstead of ``CryptPolicy().iter_config()``, create a CryptContext instance and use ``context.to_dict().items()``.cs|ddS)N__.)_render_config_keyrf)key)rhr,r- render_keysz+CryptPolicy.iter_config..render_keycSst|ttfrd|}|S)N, )rMrqtuplejoinr*r,r,r- render_values z-CryptPolicy.iter_config..render_valueFcSs|SrGr,r*r,r,r-rLz)CryptPolicy.iter_config..c3s"|]\}}||fVqdSrGr,rHrr+)rrr,r-rKsz*CryptPolicy.iter_config..)rarr>r?r\rrz iter_config)rdZinirYr,)rhrrr-rs*   zCryptPolicy.iter_configcCs8|jrttdtddnttdtdd|j|S)zexport policy object as dictionary of options. .. deprecated:: 1.6 applications should use :meth:`CryptContext.to_dict` instead. zCInstead of ``context.policy.to_dict()``, use ``context.to_dict()``.r9r:zeInstead of ``CryptPolicy().to_dict()``, create a CryptContext instance and use ``context.to_dict()``.)rarr>r?r\r]rrr,r,r-r]szCryptPolicy.to_dictcCsV|jrttdtddnttdtdd|jj|d}trH|d}||dS)zexport policy to file. .. deprecated:: 1.6 applications should use :meth:`CryptContext.to_string` instead, and then write the output to a file as desired. zYInstead of ``context.policy.to_file(stream)``, use ``stream.write(context.to_string())``.r9r:z{Instead of ``CryptPolicy().to_file(stream)``, create a CryptContext instance and use ``stream.write(context.to_string())``.rCr8N) rarr>r?r\ to_stringrencodewrite)rdstreamrCoutr,r,r-to_files zCryptPolicy.to_filecCsL|jrttdtddnttdtdd|jj|d}|rH||}|S)zexport policy to file. .. deprecated:: 1.6 applications should use :meth:`CryptContext.to_string` instead. zGInstead of ``context.policy.to_string()``, use ``context.to_string()``.r9r:ziInstead of ``CryptPolicy().to_string()``, create a CryptContext instance and use ``context.to_string()``.r)rarr>r?r\rr)rdrCrDrr,r,r-r.s zCryptPolicy.to_string)r7r8)r7r8)T)T)F)NNF)N)N)N)FF)F)r7)r7N)__name__ __module__ __qualname____doc__ classmethodr@rErUr`rfr\rarirmrprkrwrxr}rrr]rrr,r,r,r-r"Xs0<   '        $  r"c@seZdZdZdZdZdZdZdZdZ dZ dZ dZ ddZ ddZddZd d Zd d Zifd dZddZifddZddZeddZddZddZddZddZdd Zed1d"d#Zd$d%Zd&d'Zd2d(d)Z d3d+d,Z!e"d-d.Z#d4d/d0Z$dS)5 _CryptConfigaparses, validates, and stores CryptContext config this is a helper used internally by CryptContext to handle parsing, validation, and serialization of its config options. split out from the main class, but not made public since that just complicates interface too much (c.f. CryptPolicy) :arg source: config as dict mapping ``(cat,scheme,option) -> value`` NcCs.||d||||dS)NNNrk)_init_scheme_listget _init_options_init_default_schemes _init_records)rdrFr,r,r-rizs z_CryptConfig.__init__cCsg}g}t|trt|}|p dD]v}t|drD|}|j}t|n*t|tr^t|}|j}ntdt|||vrt d|f| || |q"t ||_ t ||_ dS)z,initialize .handlers and .schemes attributesr,r0z+scheme must be name or CryptHandler, not %rz$multiple handlers with same name: %rN)rMrr ryr0r rrPrQrtrcrr rk)rddatar rkelemr2schemer,r,r-rs.        z_CryptConfig._init_scheme_listc Cs|j}|j}i|_}i|_}t}t|D]H\\}}} } |||} |s`|s`| tvr`d}|r|| | \} } |dkr| tvrtd| ft | dkrtdt z ||} Wn"t y|| | ii||<Yn80z | |} Wn t y| | i| |<Yn 0| | | <q.|r&| dkr&t d||| | \} } | dkrBq.z || } Wn t yn|| i|| <Yq.0| | |<q.| dt t||_dS)zYload config dict into internal representation, and init .categories attr allz}The '%s' option should be configured per-algorithm, and not set globally in the context; This will be an error in Passlib 2.0zThe 'all' scheme is deprecated as of Passlib 1.7, and will be removed in Passlib 2.0; Please configure options on a per-algorithm basis.rkz4'schemes' context option is not allowed per categorymin_verify_timeN)_norm_scheme_option_norm_context_option_scheme_options_context_optionssetradd_global_settingsrrr?rtdiscardrsorted categories)rdrFZnorm_scheme_optionZnorm_context_optionscheme_optionscontext_optionsrcatrrr+Zexplicit_scheme category_mapZ option_mapr,r,r-rsV           z_CryptConfig._init_optionscCs>|tvrtd|ft|tr6t|}|r6||}||fS)Nz3%r option not allowed in CryptContext configuration)_forbidden_scheme_optionsrtrMr_coerce_scheme_optionsr)rdrr+funcr,r,r-rs  z _CryptConfig._norm_scheme_optioncCs&|j}|dkrLt|dr |j}nt|ts6t|dd|rJ||vrJtdn|dkrt|trht|}nt|tt fst|ddd|vrt |dkrt d n:|r|D]0}t|tst|dd ||vrtd |fqnB|d krt d t n.|dkrt dt n|dkrtd|f||fS)Ndefaultr0strz"default scheme not found in policyr~z str or seqautorVzvalue for specific context option. .. warning:: treat return value as readonly! )rr)rdrZ_defaultr,r,r-get_context_optionmap&sz"_CryptConfig.get_context_optionmapcCsrz|j|}Wnty"YdS0|d}|rjz ||}WntyPYn0|dusb||krj|dfS|dfS)zreturn value of specific option, handling category inheritance. also returns flag indicating whether value is category-specific. )NFNTF)rrtr)rdrurrr+altr,r,r-get_context_option_with_flag-s    z)_CryptConfig.get_context_option_with_flagcCs,z|j||WSty&|YS0dS)zsreturn all options for (scheme,category) combination .. warning:: treat return value as readonly! N)rrt)rdrrurr,r,r-_get_scheme_optionmapCs z"_CryptConfig._get_scheme_optionmapcCs|j|j|SrG)r rkindex)rdrr,r,r-get_base_handlerMsz_CryptConfig.get_base_handlercCs |j}d|jvr|tjj7}|S)Nrounds) setting_kwdsuhZ HasRoundsZusing_rounds_kwds)r2rr,r,r-expand_settingsPs  z_CryptConfig.expand_settingsc Cs|j}|dd}d}|r4|}||d||||}t||D]}||qR|rt||D]}||qt||d} || |r|| ||||||krd}||fS)zreturn composite dict of all options set for scheme. includes options inherited from 'all' and from default category. result can be modified. returns (kwds, has_cat_specific_options) rNFT)rcopyr[rrr differencerg) rdrru get_optionmapr_has_cat_optionsZdefkwdsZallowed_settingsrotherr,r,r-get_scheme_options_with_flagYs(     z)_CryptConfig.get_scheme_options_with_flagc Cs|j}|d}|_|d}|j}|s.dS|dp:d}|d}|sr|D]}||vrN||d<qqNtdn||vrtd|jD]`}|||} |||} | s|D]}|| vr|||<qqtd|q| | vrtd|qdS) zinitialize maps containing default scheme for each category. have to do this after _init_options(), since the default scheme is affected by the list of deprecated schemes. rr~Nr,z,must have at least one non-deprecated schemez#default scheme cannot be deprecatedz     z"_CryptConfig._init_default_schemescCs:|j}z ||WSty"Yn0|js2td|dS)z+return default scheme for specific categoryz9no hash schemes configured for this CryptContext instanceN)rrtrk)rdrudefaultsr,r,r-default_schemes  z_CryptConfig.default_schemecsRdfdd}|dp$d}|rJ||}|durJ||krJ|dfS|dfS)z/is scheme deprecated under particular category?r~cs@|d}|durdSd|vr4|kS|vSdS)Nr)rr)rrFZdepmaprrdr,r-tests z2_CryptConfig.is_deprecated_with_flag..testNFT)r)rdrrurr+rr,rr-is_deprecated_with_flags  z$_CryptConfig.is_deprecated_with_flagc Csi|_i}|_t}|_|j}d|j}|jD]V}|j}||j|D]:}|||\}} |dusj| rL|j ||fi||||f<qLq2dS)NrG) _record_lists_recordsr context_kwdsr{rr r0r[_create_record) rdZrecordsZall_context_kwdsr}rr2rrr_rr,r,r-rs      z_CryptConfig._init_recordsFc Ksz|jfddi|}Wndty|}zLtdt|}|rf|d|vrf|d}td|j|fWYd}~n d}~00||_||_ |S)NZrelaxedTz&.* unexpected keyword argument '(.*)'$rVz'keyword not supported by %s handler: %r) usingrPrematchrgrouprtr0_Context__orig_handlerr~)r2rur~settingssubclserrmrr,r,r-rs z_CryptConfig._create_recordcCs<|||\}}|||\}}|r,d|d<|r4d}||fS)areturn composite dict of options for given scheme + category. this is currently a private method, though some variant of its output may eventually be made public. given a scheme & category, it returns two things: a set of all the keyword options to pass to :meth:`_create_record`, and a bool flag indicating whether any of these options were specific to the named category. if this flag is false, the options are identical to the options for the default category. the options dict includes all the scheme-specific settings, as well as optional *deprecated* keyword. Tr~)rr)rdrrur_rr+Z not_inheritedr,r,r-r{sz*_CryptConfig._get_record_options_with_flagcCsz|j||fWSty"Yn0|durbt|tsbtrVt|trV|||dSt|dd|durt|tst|dd|s| |}|||}|jd|f<|S|rz$|j}||df}|||f<|WStyYn0td|fdS)z5return record for specific scheme & category (cached)Nr8z str or Nonerurz'crypt algorithm not found in policy: %r) rrtrMrrr get_recordrrr)rdrrurrecordcacher,r,r-rs0     z_CryptConfig.get_recordcsDz jWStyYn0fddjD}j<|S)zxreturn list of records for category (cached) this is an internal helper used only by identify_record() csg|]}|qSr,)rrHrrurdr,r- Psz1_CryptConfig._get_record_list..)rrtrk)rdrur+r,rr-_get_record_listDs   z_CryptConfig._get_record_listTcCs\t|tst|d||D]}||r|Sq|s>dS|jsNtdn tddS)z?internal helper to identify appropriate custom handler for hashr4Nzno crypt algorithms supportedzhash could not be identified) rMrrridentifyrkrtrZUnknownHashError)rdr4rurvrr,r,r-identify_recordVs     z_CryptConfig.identify_recordcCs*|dD]}|jr |Sq tddS)NzLno disabled hasher present (perhaps add 'unix_disabled' to list of schemes?))r is_disabled RuntimeError)rdrr,r,r-disabled_recordns z_CryptConfig.disabled_recordc cs|j}|j}t|}t|}d|vr.|d|r8|jn|j}|rPdt|fVd|jD]}|D]J}z|||}WntyYqb0t |trt|}|d|f|fVqb|D]J} z|| |} WntyYq0t| D]}|| |f| |fVqqqZdS)aregenerate original config. this is an iterator which yields ``(cat,scheme,option),value`` items, in the order they generally appear inside an INI file. if interpreted as a dictionary, it should match the original keywords passed to the CryptContext (aside from any canonization). it's mainly used as the internal backend for most of the public serialization methods. rkrrGN) rrrremover rkrqrrtrM) rdrYrrZ scheme_keysZ context_keysr+rrrr_r,r,r-rys2      z_CryptConfig.iter_config)NF)N)T)F)%rrrrrrr rkrrrrrrirrrrrrrr staticmethodrrrrrrrr{rrrrrrr,r,r,r-rKsF&I +   ++  +   rc@s&eZdZdZdZdZdZeddZedlddZ edmd d Z d d Z d dZ ddZ dedfddZddZddZddZeeeddZeddZdndd Zdod!d"Zed#d$Zd%d&Zdpd'd(Zdqd)d*Zdrd+d,Zd-d.Zed/d0Zed1d2Z ed3d4Z!dsd5d6Z"d7d8Z#dtd9d:Z$d;Z%dZ(dZ)d?Z*d@dAZ+dudBdCZ,dDdEZ-dvdFdGZ.e/dHdIdJdKdwdLdMZ0e/dNdIdOdxdPdQZ1e/dNdIdOdydRdSZ2dzdTdUZ3d{dVdWZ4e/dNdIdXdKdYdZZ5d|d[d\Z6d}d]d^Z7d_Z8e9d`daZ:dbdcZ;d~dddeZdjdkZ?dS)r a-Helper for hashing & verifying passwords using multiple algorithms. Instances of this class allow applications to choose a specific set of hash algorithms which they wish to support, set limits and defaults for the rounds and salt sizes those algorithms should use, flag which algorithms should be deprecated, and automatically handle migrating users to stronger hashes when they log in. Basic usage:: >>> ctx = CryptContext(schemes=[...]) See the Passlib online documentation for details and full documentation. NcCs>t|tr|fi|St||r&|S|}|||SdS)z2internal helper - accepts string, dict, or contextN)rMrNload)rArFrdr,r,r- _norm_sources   zCryptContext._norm_sourcer7r8cCs4t|tst|dd|dd}|j|||d|S)acreate new CryptContext instance from an INI-formatted string. :type source: unicode or bytes :arg source: string containing INI-formatted content. :type section: str :param section: option name of section to read from, defaults to ``"passlib"``. :type encoding: str :arg encoding: optional encoding used when source is bytes, defaults to ``"utf-8"``. :returns: new :class:`CryptContext` instance, configured based on the parameters in the *source* string. Usage example:: >>> from passlib.context import CryptContext >>> context = CryptContext.from_string(''' ... [passlib] ... schemes = sha256_crypt, des_crypt ... sha256_crypt__default_rounds = 30000 ... ''') .. versionadded:: 1.6 .. seealso:: :meth:`to_string`, the inverse of this constructor. zunicode or bytesrFF _autoloadrCrD)rMrrr)rArFrCrDrdr,r,r-rEs !   zCryptContext.from_stringcCs|dd}|j|||d|S)acreate new CryptContext instance from an INI-formatted file. this functions exactly the same as :meth:`from_string`, except that it loads from a local file. :type path: str :arg path: path to local file containing INI-formatted config. :type section: str :param section: option name of section to read from, defaults to ``"passlib"``. :type encoding: str :arg encoding: encoding used to load file, defaults to ``"utf-8"``. :returns: new CryptContext instance, configured based on the parameters stored in the file *path*. .. versionadded:: 1.6 .. seealso:: :meth:`from_string` for an equivalent usage example. Frr) load_path)rArBrCrDrdr,r,r-r@ s zCryptContext.from_pathcKs*tdd}|||r&|j|dd|S)a6Return copy of existing CryptContext instance. This function returns a new CryptContext instance whose configuration is exactly the same as the original, with the exception that any keywords passed in will take precedence over the original settings. As an example:: >>> from passlib.context import CryptContext >>> # given an existing context... >>> ctx1 = CryptContext(["sha256_crypt", "md5_crypt"]) >>> # copy can be used to make a clone, and update >>> # some of the settings at the same time... >>> ctx2 = custom_app_context.copy(default="md5_crypt") >>> # and the original will be unaffected by the change >>> ctx1.default_scheme() "sha256_crypt" >>> ctx2.default_scheme() "md5_crypt" .. versionadded:: 1.6 This method was previously named :meth:`!replace`. That alias has been deprecated, and will be removed in Passlib 1.8. .. seealso:: :meth:`update` FrTr[)r r)rdr_rr,r,r-r,s  zCryptContext.copycKs|jfi|S)zG alias for :meth:`copy`, to match PasswordHash.using() )rrdr_r,r,r-rRszCryptContext.usingcKstdtdd|jfi|S)z deprecated alias of :meth:`copy`zCryptContext().replace() has been deprecated in Passlib 1.6, and will be removed in Passlib 1.8, it has been renamed to CryptContext().copy()r9r:)rr?rrr,r,r-rfXszCryptContext.replaceTcKsv|dur||d<|turbtdt|dur6||qrt|trX||j||qrtdn|rr||ndS)NrkzThe CryptContext ``policy`` keyword has been deprecated as of Passlib 1.6, and will be removed in Passlib 1.8; please use ``CryptContext.from_string()` or ``CryptContext.from_path()`` instead.z%policy must be a CryptPolicy instance) _UNSETrr?rrMr"r\r[rP)rdrkpolicyrr_r,r,r-rics      zCryptContext.__init__cCs dt|S)Nz)idrlr,r,r-__repr__szCryptContext.__repr__cCst|ddS)NT)r=ra)r"rrlr,r,r- _get_policys zCryptContext._get_policycCs2tdtddt|tr&||jntddS)NzThe CryptPolicy class and the ``context.policy`` attribute have been deprecated as of Passlib 1.6, and will be removed in Passlib 1.8; please use the ``context.load()`` and ``context.update()`` methods instead.r9r:zexpected CryptPolicy instance)rr?rMr"rr\rP)rdrr,r,r- _set_policys  zCryptContext._set_policyzC[deprecated] returns CryptPolicy instance tied to this CryptContext)doccCs2t}tr|||n |||t||S)z.helperZrt)rDN)r8asciirbr8)ropenreaddecoderr) rdrBr[rCrDrrZfhtmpr,rr-rs ( ( zCryptContext.load_pathcs d}t|trFtr"t||dd}nt|d|dd}|t||d}n8t|trht|j j dd}d}nt |d s~t |d d|r|j tfd d t|D}|r|j d ur|sd S|}t|j j dd}||t|}||_ ||j|_|j|_|jr|jdd nd |_d S)aLoad new configuration into CryptContext, replacing existing config. :arg source: source of new configuration to load. this value can be a number of different types: * a :class:`!dict` object, or compatible Mapping the key/value pairs will be interpreted the same keywords for the :class:`CryptContext` class constructor. * a :class:`!unicode` or :class:`!bytes` string this will be interpreted as an INI-formatted file, and appropriate key/value pairs will be loaded from the specified *section*. * another :class:`!CryptContext` object. this will export a snapshot of its configuration using :meth:`to_dict`. :type update: bool :param update: By default, :meth:`load` will replace the existing configuration entirely. If ``update=True``, it will preserve any existing configuration options that are not overridden by the new source, much like the :meth:`update` method. :type section: str :param section: When parsing an INI-formatted string, :meth:`load` will look for a section named ``"passlib"``. This option allows an alternate section name to be used. Ignored when loading from a dictionary. :type encoding: str :param encoding: Encoding to use when **source** is bytes. Defaults to ``"utf-8"``. Ignored when loading from a dictionary. .. deprecated:: 1.8 This keyword, and support for bytes input, will be dropped in Passlib 2.0 :raises TypeError: * If the source cannot be identified. * If an unknown / malformed keyword is encountered. :raises ValueError: If an invalid keyword value is encountered. .. note:: If an error occurs during a :meth:`!load` call, the :class:`!CryptContext` instance will be restored to the configuration it was in before the :meth:`!load` call was made; this is to ensure it is *never* left in an inconsistent state due to a load error. .. versionadded:: 1.6 TrF)paramr8)Zsource_encodingrz&rXFrzstring or dictc3s|]\}}||fVqdSrGr,rparser,r-rK/sz$CryptContext.load..N_strip_unused_context_kwds)rMrrr r rrr rNrzrryr_parse_config_keyrr[r_reset_dummy_verifyr _get_recordr_identify_recordr__dict__rgr)rdrFr[rCrDZ parse_keysrconfigr,rr-rsD@       zCryptContext.loadcCs|ddd}t|}|dkr8dd|d}}}n8|dkrNd}|\}}n"|dkrb|\}}}ntd|f|d kr~d}n|s|durtd ||d krd}n|s|durtd ||std ||||fS)z>helper used to parse ``cat__scheme__option`` keys into a tuplerrrVNrr9z)keys must have less than 3 separators: %rrzempty category: %rrhzempty scheme: %rzempty option: %r)rfsplitrZrP)Zckeypartscountrrrr,r,r-r Is.       zCryptContext._parse_config_keycOsN|r8t|dkrtd|r$td|j|dddn|rJ|j|dddS)aHelper for quickly changing configuration. This acts much like the :meth:`!dict.update` method: it updates the context's configuration, replacing the original value(s) for the specified keys, and preserving the rest. It accepts any :ref:`keyword ` accepted by the :class:`!CryptContext` constructor. .. versionadded:: 1.6 .. seealso:: :meth:`copy` rVz(expected at most one positional argumentz.positional arg and keywords mutually exclusiverTrN)rZrPrrdrer_r,r,r-r[gs zCryptContext.updatecs.jj}|r&tfdd|DS|SdS)a;return schemes loaded into this CryptContext instance. :type resolve: bool :arg resolve: if ``True``, will return a tuple of :class:`~passlib.ifc.PasswordHash` objects instead of their names. :returns: returns tuple of the schemes configured for this context via the *schemes* option. .. versionadded:: 1.6 This was previously available as ``CryptContext().policy.schemes()`` .. seealso:: the :ref:`schemes ` option for usage example. c3s|]}j|dVqdS)rsNr1rrurdror,r-rKsz'CryptContext.schemes..N)rzrkr)rdrYrurorkr,rr-rks zCryptContext.schemescCs|jd||d}|r|S|jS)ahreturn name of scheme that :meth:`hash` will use by default. :type resolve: bool :arg resolve: if ``True``, will return a :class:`~passlib.ifc.PasswordHash` object instead of the name. :type category: str or None :param category: Optional :ref:`user category `. If specified, this will return the catgory-specific default scheme instead. :returns: name of the default scheme. .. seealso:: the :ref:`default ` option for usage example. .. versionadded:: 1.6 .. versionchanged:: 1.7 This now returns a hasher configured with any CryptContext-specific options (custom rounds settings, etc). Previously this returned the base hasher from :mod:`passlib.hash`. Nrs)r2r0)rdrurYrohasherr,r,r-rszCryptContext.default_schemecCsZz"|||}|r|jWS|WSWnty4Yn0|jjrNtd|fntddS)ahelper to resolve name of scheme -> :class:`~passlib.ifc.PasswordHash` object used by scheme. :arg scheme: This should identify the scheme to lookup. If omitted or set to ``None``, this will return the handler for the default scheme. :arg category: If a user category is specified, and no scheme is provided, it will use the default for that category. Otherwise this parameter is ignored. :param unconfigured: By default, this returns a handler object whose .hash() and .needs_update() methods will honor the configured provided by CryptContext. See ``unconfigured=True`` to get the underlying handler from before any context-specific configuration was applied. :raises KeyError: If the scheme does not exist OR is not being used within this context. :returns: :class:`~passlib.ifc.PasswordHash` object used to implement the named scheme within this context (this will usually be one of the objects from :mod:`passlib.hash`) .. versionadded:: 1.6 This was previously available as ``CryptContext().policy.get_handler()`` .. versionchanged:: 1.7 This now returns a hasher configured with any CryptContext-specific options (custom rounds settings, etc). Previously this returned the base hasher from :mod:`passlib.hash`. z;crypt algorithm not found in this CryptContext instance: %rz8no crypt algorithms loaded in this CryptContext instanceN)r rrtrzr )rdrrurorr,r,r-r2s&   zCryptContext.handlercCstdd|jjDS)zCcheck if any handlers in this context aren't in the global registrycss|]}t|s|VqdSrG)r3rHr2r,r,r-rK2sz:CryptContext._get_unregistered_handlers..)rrzr rlr,r,r-_get_unregistered_handlers0sz'CryptContext._get_unregistered_handlerscCs|jjS)z return :class:`!set` containing union of all :ref:`contextual keywords ` supported by the handlers in this context. .. versionadded:: 1.6.6 )rzrrlr,r,r-r5szCryptContext.context_kwdscCs8|\}}}|r d||pd|fS|r0d||fS|SdS)z*convert 3-part config key to single stringz %s__%s__%srhz%s__%sNr,)rrroptionr,r,r-rBs   zCryptContext._render_config_keycCsft|ttfrd|}n@t|trZt|trR|ddkrR|rLd|dnd}nt|}|ddS)z,render value to string suitable for INI filerr9r/z%.2f0r#z%%) rMrqrrrr&r'rrf)rr+r,r,r-_render_ini_valueMs  zCryptContext._render_ini_valuecs$|jtfdd|j|DS)agReturn current configuration as a dictionary. :type resolve: bool :arg resolve: if ``True``, the ``schemes`` key will contain a list of a :class:`~passlib.ifc.PasswordHash` objects instead of just their names. This method dumps the current configuration of the CryptContext instance. The key/value pairs should be in the format accepted by the :class:`!CryptContext` class constructor, in fact ``CryptContext(**myctx.to_dict())`` will create an exact copy of ``myctx``. As an example:: >>> # you can dump the configuration of any crypt context... >>> from passlib.apps import ldap_nocrypt_context >>> ldap_nocrypt_context.to_dict() {'schemes': ['ldap_salted_sha1', 'ldap_salted_md5', 'ldap_sha1', 'ldap_md5', 'ldap_plaintext']} .. versionadded:: 1.6 This was previously available as ``CryptContext().policy.to_dict()`` .. seealso:: the :ref:`context-serialization-example` example in the tutorial. c3s|]\}}||fVqdSrGr,rrr,r-rKsz'CryptContext.to_dict..)rrNrzrrrr,rr-r]bs  zCryptContext.to_dictcCsN|j}|j}|||jD](\}}|||}||}||||q dS)z(helper to write to ConfigParser instanceN)rrZ add_sectionrzrr)rdparserrCrrkvr,r,r-_write_to_parsers  zCryptContext._write_to_parsercCsft}|||t}|||}|rL|dddd|D|}tsb|d}|S)aHserialize to INI format and return as unicode string. :param section: name of INI section to output, defaults to ``"passlib"``. :returns: CryptContext configuration, serialized to a INI unicode string. This function acts exactly like :meth:`to_dict`, except that it serializes all the contents into a single human-readable string, which can be hand edited, and/or stored in a file. The output of this method is accepted by :meth:`from_string`, :meth:`from_path`, and :meth:`load`. As an example:: >>> # you can dump the configuration of any crypt context... >>> from passlib.apps import ldap_nocrypt_context >>> print ldap_nocrypt_context.to_string() [passlib] schemes = ldap_salted_sha1, ldap_salted_md5, ldap_sha1, ldap_md5, ldap_plaintext .. versionadded:: 1.6 This was previously available as ``CryptContext().policy.to_string()`` .. seealso:: the :ref:`context-serialization-example` example in the tutorial. z# NOTE: the %s handler(s) are not registered with Passlib, # this string may not correctly reproduce the current configuration. rcss|]}t|jVqdSrG)reprr0rr,r,r-rKrLz)CryptContext.to_string..r8) rrrrrrgetvaluerr)rdrCrbufZ unregisteredrr,r,r-rs   zCryptContext.to_string r9r$rcCs |dSrG)r rlr,r,r-reset_min_verify_timesz"CryptContext.reset_min_verify_timecCs4|r$t|tst|d|||S|||SdS)zCreturn record based on scheme, or failing that, by identifying hashr4N)rMrrr r rdr4rrur,r,r-_get_or_identify_records    z$CryptContext._get_or_identify_recordcCs2|sdS|jj|j}|D]}||dqdS)af helper which removes any context keywords from **kwds** that are known to be used by another scheme in this context, but are NOT supported by handler specified by **record**. .. note:: as optimization, load() will set this method to None on a per-instance basis if there are no context kwds. N)rzrrrg)rdr_rZ unused_kwdsrr,r,r-rs z'CryptContext._strip_unused_context_kwdscCs4|durtdt||||}|jp2|j||dS)a Check if hash needs to be replaced for some reason, in which case the secret should be re-hashed. This function is the core of CryptContext's support for hash migration: This function takes in a hash string, and checks the scheme, number of rounds, and other properties against the current policy. It returns ``True`` if the hash is using a deprecated scheme, or is otherwise outside of the bounds specified by the policy (e.g. the number of rounds is lower than :ref:`min_rounds ` configuration for that algorithm). If so, the password should be re-hashed using :meth:`hash` Otherwise, it will return ``False``. :type hash: unicode or bytes :arg hash: The hash string to examine. :type scheme: str or None :param scheme: Optional scheme to use. Scheme must be one of the ones configured for this context (see the :ref:`schemes ` option). If no scheme is specified, it will be identified based on the value of *hash*. .. deprecated:: 1.7 Support for this keyword is deprecated, and will be removed in Passlib 2.0. :type category: str or None :param category: Optional :ref:`user category `. If specified, this will cause any category-specific defaults to be used when determining if the hash needs to be updated (e.g. is below the minimum rounds). :type secret: unicode, bytes, or None :param secret: Optional secret associated with the provided ``hash``. This is not required, or even currently used for anything... it's for forward-compatibility with any future update checks that might need this information. If provided, Passlib assumes the secret has already been verified successfully against the hash. .. versionadded:: 1.6 :returns: ``True`` if hash should be replaced, otherwise ``False``. :raises ValueError: If the hash did not match any of the configured :meth:`schemes`. .. versionadded:: 1.6 This method was previously named :meth:`hash_needs_update`. .. seealso:: the :ref:`context-migration-example` example in the tutorial. NzqCryptContext.needs_update(): 'scheme' keyword is deprecated as of Passlib 1.7, and will be removed in Passlib 2.0r5)rr?r'r~ needs_update)rdr4rrur5rr,r,r-r)s ;zCryptContext.needs_updatez1.6z2.0zCryptContext.needs_update())r~removedZ replacementcCs||||S)aLegacy alias for :meth:`needs_update`. .. deprecated:: 1.6 This method was renamed to :meth:`!needs_update` in version 1.6. This alias will be removed in version 2.0, and should only be used for compatibility with Passlib 1.3 - 1.5. )r)r&r,r,r-hash_needs_updateFs zCryptContext.hash_needs_updatez1.7)r~r*cKs0|||}|j}|r ||||jfi|S)zGenerate a config string for specified scheme. .. deprecated:: 1.7 This method will be removed in version 2.0, and should only be used for compatibility with Passlib 1.3 - 1.6. )r r genconfig)rdrrurr strip_unusedr,r,r-r,Qs  zCryptContext.genconfigcKs6||||}|j}|r"||||j||fi|S)zGenerate hash for the specified secret using another hash. .. deprecated:: 1.7 This method will be removed in version 2.0, and should only be used for compatibility with Passlib 1.3 - 1.6. )r'rgenhash)rdr5rrrur_rr-r,r,r-r.`s  zCryptContext.genhashcCs8||||}|durdS|r.|r(|jS|Sn|jSdS)aAttempt to identify which algorithm the hash belongs to. Note that this will only consider the algorithms currently configured for this context (see the :ref:`schemes ` option). All registered algorithms will be checked, from first to last, and whichever one positively identifies the hash first will be returned. :type hash: unicode or bytes :arg hash: The hash string to test. :type category: str or None :param category: Optional :ref:`user category `. Ignored by this function, this parameter is provided for symmetry with the other methods. :type resolve: bool :param resolve: If ``True``, returns the hash handler itself, instead of the name of the hash. :type required: bool :param required: If ``True``, this will raise a ValueError if the hash cannot be identified, instead of returning ``None``. :returns: The handler which first identifies the hash, or ``None`` if none of the algorithms identify the hash. N)r rr0)rdr4rurYrvrorr,r,r-ros"zCryptContext.identifycKsD|durtdt|||}|j}|r2||||j|fi|S)aZrun secret through selected algorithm, returning resulting hash. :type secret: unicode or bytes :arg secret: the password to hash. :type scheme: str or None :param scheme: Optional scheme to use. Scheme must be one of the ones configured for this context (see the :ref:`schemes ` option). If no scheme is specified, the configured default will be used. .. deprecated:: 1.7 Support for this keyword is deprecated, and will be removed in Passlib 2.0. :type category: str or None :param category: Optional :ref:`user category `. If specified, this will cause any category-specific defaults to be used when hashing the password (e.g. different default scheme, different default rounds values, etc). :param \*\*kwds: All other keyword options are passed to the selected algorithm's :meth:`PasswordHash.hash() ` method. :returns: The secret as encoded by the specified algorithm and options. The return value will always be a :class:`!str`. :raises TypeError, ValueError: * If any of the arguments have an invalid type or value. This includes any keywords passed to the underlying hash's :meth:`PasswordHash.hash() ` method. .. seealso:: the :ref:`context-basic-example` example in the tutorial NziCryptContext.hash(): 'scheme' keyword is deprecated as of Passlib 1.7, and will be removed in Passlib 2.0)rr?r rr4)rdr5rrur_rr-r,r,r-r4s+  zCryptContext.hashzCryptContext.hash()cOs|j|i|S)a Legacy alias for :meth:`hash`. .. deprecated:: 1.7 This method was renamed to :meth:`!hash` in version 1.7. This alias will be removed in version 2.0, and should only be used for compatibility with Passlib 1.3 - 1.6. )r4rr,r,r-encrypts zCryptContext.encryptcKs\|durtdt|dur&|dS||||}|j}|rH||||j||fi|S)averify secret against an existing hash. If no scheme is specified, this will attempt to identify the scheme based on the contents of the provided hash (limited to the schemes configured for this context). It will then check whether the password verifies against the hash. :type secret: unicode or bytes :arg secret: the secret to verify :type hash: unicode or bytes :arg hash: hash string to compare to if ``None`` is passed in, this will be treated as "never verifying" :type scheme: str :param scheme: Optionally force context to use specific scheme. This is usually not needed, as most hashes can be unambiguously identified. Scheme must be one of the ones configured for this context (see the :ref:`schemes ` option). .. deprecated:: 1.7 Support for this keyword is deprecated, and will be removed in Passlib 2.0. :type category: str or None :param category: Optional :ref:`user category ` string. This is mainly used when generating new hashes, it has little effect when verifying; this keyword is mainly provided for symmetry. :param \*\*kwds: All additional keywords are passed to the appropriate handler, and should match its :attr:`~passlib.ifc.PasswordHash.context_kwds`. :returns: ``True`` if the password matched the hash, else ``False``. :raises ValueError: * if the hash did not match any of the configured :meth:`schemes`. * if any of the arguments have an invalid value (this includes any keywords passed to the underlying hash's :meth:`PasswordHash.verify() ` method). :raises TypeError: * if any of the arguments have an invalid type (this includes any keywords passed to the underlying hash's :meth:`PasswordHash.verify() ` method). .. seealso:: the :ref:`context-basic-example` example in the tutorial NkCryptContext.verify(): 'scheme' keyword is deprecated as of Passlib 1.7, and will be removed in Passlib 2.0F)rr? dummy_verifyr'rverify)rdr5r4rrur_rr-r,r,r-r2s; zCryptContext.verifyc Ks|durtdt|dur&|dS||||}|j}|rV|rV|}|||n|}|j||fi|srdS|js|j||drd|j |fd|i|fSdSdS)a verify password and re-hash the password if needed, all in a single call. This is a convenience method which takes care of all the following: first it verifies the password (:meth:`~CryptContext.verify`), if this is successfull it checks if the hash needs updating (:meth:`~CryptContext.needs_update`), and if so, re-hashes the password (:meth:`~CryptContext.hash`), returning the replacement hash. This series of steps is a very common task for applications which wish to update deprecated hashes, and this call takes care of all 3 steps efficiently. :type secret: unicode or bytes :arg secret: the secret to verify :type secret: unicode or bytes :arg hash: hash string to compare to. if ``None`` is passed in, this will be treated as "never verifying" :type scheme: str :param scheme: Optionally force context to use specific scheme. This is usually not needed, as most hashes can be unambiguously identified. Scheme must be one of the ones configured for this context (see the :ref:`schemes ` option). .. deprecated:: 1.7 Support for this keyword is deprecated, and will be removed in Passlib 2.0. :type category: str or None :param category: Optional :ref:`user category `. If specified, this will cause any category-specific defaults to be used if the password has to be re-hashed. :param \*\*kwds: all additional keywords are passed to the appropriate handler, and should match that hash's :attr:`PasswordHash.context_kwds `. :returns: This function returns a tuple containing two elements: ``(verified, replacement_hash)``. The first is a boolean flag indicating whether the password verified, and the second an optional replacement hash. The tuple will always match one of the following 3 cases: * ``(False, None)`` indicates the secret failed to verify. * ``(True, None)`` indicates the secret verified correctly, and the hash does not need updating. * ``(True, str)`` indicates the secret verified correctly, but the current hash needs to be updated. The :class:`!str` will be the freshly generated hash, to replace the old one. :raises TypeError, ValueError: For the same reasons as :meth:`verify`. .. seealso:: the :ref:`context-migration-example` example in the tutorial. Nr0)FNr(Tru)TN) rr?r1r'rrr2r~r)r4) rdr5r4rrur_rr-Z clean_kwdsr,r,r-verify_and_update- s$@ zCryptContext.verify_and_updateztoo many secretscCs ||jS)z> precalculated hash for dummy_verify() to use )r4 _dummy_secretrlr,r,r- _dummy_hash szCryptContext._dummy_hashcCst|j|dS)z> flush memoized values used by dummy_verify() N)rQr5 clear_cacherlr,r,r-r  sz CryptContext._reset_dummy_verifycCs||j|jdS)a Helper that applications can call when user wasn't found, in order to simulate time it would take to hash a password. Runs verify() against a dummy hash, to simulate verification of a real account password. :param elapsed: .. deprecated:: 1.7.1 this option is ignored, and will be removed in passlib 1.8. .. versionadded:: 1.7 F)r2r4r5)rdelapsedr,r,r-r1 szCryptContext.dummy_verifycCs||dj S)an test if hash represents a usuable password -- i.e. does not represent an unusuable password such as ``"!"``, which is recognized by the :class:`~passlib.hash.unix_disabled` hash. :raises ValueError: if the hash is not recognized (typically solved by adding ``unix_disabled`` to the list of schemes). N)r r)rdr4r,r,r- is_enabled s zCryptContext.is_enabledcCs|jj}||S)a return a string to disable logins for user, usually by returning a non-verifying string such as ``"!"``. :param hash: Callers can optionally provide the account's existing hash. Some disabled handlers (such as :class:`!unix_disabled`) will encode this into the returned value, so that it can be recovered via :meth:`enable`. :raises RuntimeError: if this function is called w/o a disabled hasher (such as :class:`~passlib.hash.unix_disabled`) included in the list of schemes. :returns: hash string which will be recognized as valid by the context, but is guaranteed to not validate against *any* password. )rzrdisablerdr4rr,r,r-r9 szCryptContext.disablecCs$||d}|jr||S|SdS)a inverse of :meth:`disable` -- attempts to recover original hash which was converted by a :meth:`!disable` call into a disabled hash -- thus restoring the user's original password. :raises ValueError: if original hash not present, or if the disabled handler doesn't support encoding the original hash (e.g. ``django_disabled``) :returns: the original hash. N)r renabler:r,r,r-r; s  zCryptContext.enable)r7r8)r7r8)Fr7r8)Fr7r8)FNF)NFF)NNF)F)r7)NN)NNN)NN)NN)NN)NFFF)NN)NN)NN)r)N)@rrrrrzr r rrrEr@rrrfrrirrrpropertyrrrrrr r[rkrr2rrrrr]rrZmvt_estimate_max_samplesZmvt_estimate_min_samplesZmvt_estimate_max_timeZmvt_estimate_resolutionrrr%r'rr)rr+r,r.rr4r/r2r3r4rr5r r1r8r9r;r,r,r,r-r s   & &  "     s E  1 5    # =  E      - 8  M a   r cs6eZdZdZdZd ddZfddZddZZS) r!aCryptContext subclass which doesn't load handlers until needed. This is a subclass of CryptContext which takes in a set of arguments exactly like CryptContext, but won't import any handlers (or even parse its arguments) until the first time one of its methods is accessed. :arg schemes: The first positional argument can be a list of schemes, or omitted, just like CryptContext. :param onload: If a callable is passed in via this keyword, it will be invoked at lazy-load time with the following signature: ``onload(**kwds) -> kwds``; where ``kwds`` is all the additional kwds passed to LazyCryptContext. It should perform any additional deferred initialization, and return the final dict of options to be passed to CryptContext. .. versionadded:: 1.6 :param create_policy: .. deprecated:: 1.6 This option will be removed in Passlib 1.8, applications should use ``onload`` instead. :param kwds: All additional keywords are passed to CryptContext; or to the *onload* function (if provided). This is mainly used internally by modules such as :mod:`passlib.apps`, which define a large number of contexts, but only a few of them will be needed at any one time. Use of this class saves the memory needed to import the specified handlers until the context instance is actually accessed. As well, it allows constructing a context at *module-init* time, but using :func:`!onload()` to provide dynamic configuration at *application-run* time. .. note:: This class is only useful if you're referencing handler objects by name, and don't want them imported until runtime. If you want to have the config validated before your application runs, or are passing in already-imported handler instances, you should use :class:`CryptContext` instead. .. versionadded:: 1.4 NcKs|dur||d<||_dS)Nrk) _lazy_kwds)rdrkr_r,r,r-ri- szLazyCryptContext.__init__cs|j}d|vrJtdt|d}|fi|}tj|dd}|j}n d|vrj|d}|fi|}|`tt |j fi|t |_ dS)N create_policyzThe CryptPolicy class, and LazyCryptContext's ``create_policy`` keyword have been deprecated as of Passlib 1.6, and will be removed in Passlib 1.8; please use the ``onload`` keyword instead.FrWonload) r=rr?rgr"rUr\r]superr!rir __class__)rdr_r>resultrr?rAr,r- _lazy_init2 s   zLazyCryptContext._lazy_initcCs2|dr|dr&|jdur&|t||S)N_r) startswithr=rDobject__getattribute__)rdattrr,r,r-rHE s z!LazyCryptContext.__getattribute__)N) rrrrr=rirDrH __classcell__r,r,rCr-r! s 2  r!)N)BrZ __future__rrZloggingZ getLoggerrlog threadingtimewarningsrr7rZ passlib.excrrrZpasslib.registryrr Z passlib.utilsr rr r r rrrrZpasslib.utils.binaryrZpasslib.utils.compatrrrrrrrrrrrZpasslib.utils.decorrr__all__rGrr.rrrNr(rr3rr6rr>r"rr r!r,r,r,r-sd   ( 4    viL