B
    `D                 @   s   d dl Z d dlZd dlZd dlZd dlmZmZ d dlmZ d dl	m
Z
 d dlmZmZ d dlmZ d dlmZmZ dd	 Zd
d ZG dd dZedd eZdddZd ddZeZedd eZedd dS )!    N)JSONSerializerSignedSerializer)
deprecated)implementer)check_csrf_origincheck_csrf_token)ISession)bytes_text_c                s    fdd} j |_ |S )zTDecorator which causes a cookie to be renewed when an accessor
    method is called.c                sD   t t  | _}| jd k	r4|| j | jkr4|    | f||S )N)inttimeaccessed_reissue_timerenewedchanged)sessionargkwnow)wrapped W/home/kop/projects/devel/pgwui/test_venv/lib/python3.7/site-packages/pyramid/session.pyr      s
    
z!manage_accessed.<locals>.accessed)__doc__)r   r   r   )r   r   manage_accessed   s    r   c                s    fdd} j |_ |S )zMDecorator which causes a cookie to be set when a setter method
    is called.c                s&   t t | _|    | f||S )N)r   r   r   r   )r   r   r   )r   r   r   r   !   s    zmanage_changed.<locals>.changed)r   )r   r   r   )r   r   manage_changed   s    r   c               @   s.   e Zd ZdZejfddZdd Zdd ZdS )	PickleSerializera  
    .. deprecated:: 2.0

    .. warning::

        In :app:`Pyramid` 2.0 the default ``serializer`` option changed to
        use :class:`pyramid.session.JSONSerializer`, and ``PickleSerializer``
        has been been removed from active Pyramid code.

        Pyramid will require JSON-serializable objects in :app:`Pyramid` 2.0.

        Please see :ref:`upgrading_session_20`.

    A serializer that uses the pickle protocol to dump Python data to bytes.

    This was the default serializer used by Pyramid, but has been deprecated.

    ``protocol`` may be specified to control the version of pickle used.
    Defaults to :attr:`pickle.HIGHEST_PROTOCOL`.
    c             C   s
   || _ d S )N)protocol)selfr   r   r   r   __init__@   s    zPickleSerializer.__init__c             C   s(   y
t |S  tk
r"   tY nX dS )z(Accept bytes and return a Python object.N)pickleloads	Exception
ValueError)r   Zbstructr   r   r   r    C   s    
zPickleSerializer.loadsc             C   s   t || jS )z(Accept a Python object and return bytes.)r   dumpsr   )r   Z	appstructr   r   r   r#   L   s    zPickleSerializer.dumpsN)	__name__
__module____qualname__r   r   HIGHEST_PROTOCOLr   r    r#   r   r   r   r   r   *   s   	r   zpyramid.session.PickleSerializer is deprecated as of Pyramid 2.0 for security concerns. Use pyramid.session.JSONSerializer or reference the narrative documentation for information on building a migration tool.r   /FLax  Tc                s4   t tG  	
fdddt}|S )a)  
    Configure a :term:`session factory` which will provide cookie-based
    sessions.  The return value of this function is a :term:`session factory`,
    which may be provided as the ``session_factory`` argument of a
    :class:`pyramid.config.Configurator` constructor, or used as the
    ``session_factory`` argument of the
    :meth:`pyramid.config.Configurator.set_session_factory` method.

    The session factory returned by this function will create sessions
    which are limited to storing fewer than 4000 bytes of data (as the
    payload must fit into a single cookie).

    .. warning:

       This class provides no protection from tampering and is only intended
       to be used by framework authors to create their own cookie-based
       session factories.

    Parameters:

    ``serializer``
      An object with two methods: ``loads`` and ``dumps``.  The ``loads``
      method should accept bytes and return a Python object.  The ``dumps``
      method should accept a Python object and return bytes.  A ``ValueError``
      should be raised for malformed inputs.

    ``cookie_name``
      The name of the cookie used for sessioning. Default: ``'session'``.

    ``max_age``
      The maximum age of the cookie used for sessioning (in seconds).
      Default: ``None`` (browser scope).

    ``path``
      The path used for the session cookie. Default: ``'/'``.

    ``domain``
      The domain used for the session cookie.  Default: ``None`` (no domain).

    ``secure``
      The 'secure' flag of the session cookie. Default: ``False``.

    ``httponly``
      Hide the cookie from Javascript by setting the 'HttpOnly' flag of the
      session cookie. Default: ``False``.

    ``samesite``
      The 'samesite' option of the session cookie. Set the value to ``None``
      to turn off the samesite option.  Default: ``'Lax'``.

    ``timeout``
      A number of seconds of inactivity before a session times out. If
      ``None`` then the cookie never expires. This lifetime only applies
      to the *value* within the cookie. Meaning that if the cookie expires
      due to a lower ``max_age``, then this setting has no effect.
      Default: ``1200``.

    ``reissue_time``
      The number of seconds that must pass before the cookie is automatically
      reissued as the result of a request which accesses the session. The
      duration is measured as the number of seconds since the last session
      cookie was issued and 'now'.  If this value is ``0``, a new cookie
      will be reissued on every request accessing the session. If ``None``
      then the cookie's lifetime will never be extended.

      A good rule of thumb: if you want auto-expired cookies based on
      inactivity: set the ``timeout`` value to 1200 (20 mins) and set the
      ``reissue_time`` value to perhaps a tenth of the ``timeout`` value
      (120 or 2 mins).  It's nonsensical to set the ``timeout`` value lower
      than the ``reissue_time`` value, as the ticket will never be reissued.
      However, such a configuration is not explicitly prevented.

      Default: ``0``.

    ``set_on_exception``
      If ``True``, set a session cookie even if an exception occurs
      while rendering a view. Default: ``True``.

    .. versionadded: 1.5a3

    .. versionchanged: 1.10

       Added the ``samesite`` option and made the default ``'Lax'``.
    c                   sl  e Zd ZdZ ZdkrneZZZZ	Z
Z	Z
dkrH
ne
Zdkr\neZdZfddZdd Zdd	 ZeejZeejZeejZeejZeejZeejZeejZeejZeejZeejZeej Z eej!Z!eej"Z"eej#Z#eej$Z$edddZ%edddZ&edddZ'edd Z(edd Z)fddZ*dS )z/BaseCookieSessionFactory.<locals>.CookieSessionz  Dictionary-like session object NFc          	      s   || _ t }| }}d}d }i }|j| j}|d k	rdy t|}W n tk
rb   d }Y nX |d k	ry&|\}	}
}t|	}t|
}|}d}W n t	tfk
r   i }Y nX | j
d k	r|| | j
kri }|| _|| _|| _|| _t| | d S )NTF)requestr   cookiesget_cookie_namer    r	   r"   float	TypeError_timeoutcreatedr   r   newdictr   )r   r+   r   r2   r   r3   valuestate	cookievalrvalcvalZsval)
serializerr   r   r      s:    



z8BaseCookieSessionFactory.<locals>.CookieSession.__init__c                s(    j s$d _  fdd} j| d S )NTc                s     | d  _d S )N)_set_cookier+   )r+   response)r   r   r   set_cookie_callback  s    
zTBaseCookieSessionFactory.<locals>.CookieSession.changed.<locals>.set_cookie_callback)_dirtyr+   Zadd_response_callback)r   r=   r   )r   r   r      s    z7BaseCookieSessionFactory.<locals>.CookieSession.changedc             S   s   |    d S )N)clear)r   r   r   r   
invalidate  s    z:BaseCookieSessionFactory.<locals>.CookieSession.invalidate Tc             S   s*   |  d| g }|s||kr&|| d S )N_f_)
setdefaultappend)r   msgqueueZallow_duplicatestorager   r   r   flash  s    z5BaseCookieSessionFactory.<locals>.CookieSession.flashc             S   s   |  d| g }|S )NrB   )pop)r   rF   rG   r   r   r   	pop_flash$  s    z9BaseCookieSessionFactory.<locals>.CookieSession.pop_flashc             S   s   |  d| g }|S )NrB   )r-   )r   rF   rG   r   r   r   
peek_flash)  s    z:BaseCookieSessionFactory.<locals>.CookieSession.peek_flashc             S   s    t ttd}|| d< |S )N   _csrft_)r
   binasciihexlifyosurandom)r   tokenr   r   r   new_csrf_token/  s    z>BaseCookieSessionFactory.<locals>.CookieSession.new_csrf_tokenc             S   s    |  dd }|d kr|  }|S )NrM   )r-   rS   )r   rR   r   r   r   get_csrf_token5  s    z>BaseCookieSessionFactory.<locals>.CookieSession.get_csrf_tokenc          
      s   | j s t| jdd }|d k	r dS t | j| jt| f}t|dkrXt	dt| |j
| j|| j| j| j| j| j| jd dS )N	exceptionFi  z,Cookie value is too long to store (%s bytes))r5   max_agepathdomainsecurehttponlysamesiteT)_cookie_on_exceptiongetattrr+   r
   r#   r   r2   r4   lenr"   
set_cookier.   _cookie_max_age_cookie_path_cookie_domain_cookie_secure_cookie_httponly_cookie_samesite)r   r<   rU   r7   )r:   r   r   r;   =  s(    
z;BaseCookieSessionFactory.<locals>.CookieSession._set_cookie)rA   T)rA   )rA   )+r$   r%   r&   r   r.   r   r`   ra   rb   rc   rd   re   r\   r1   r   r>   r   r   r@   r   r4   r-   __getitem__itemsvalueskeys__contains____len____iter__r   r?   updaterC   rI   popitem__setitem____delitem__rH   rJ   rK   rS   rT   r;   r   )cookie_namerX   rZ   rV   rW   reissue_timer[   rY   r:   set_on_exceptiontimeoutr   r   CookieSession   sN   *















ru   )r   r   r4   )r:   rq   rV   rW   rX   rY   rZ   r[   rt   rr   rs   ru   r   )rq   rX   rZ   rV   rW   rr   r[   rY   r:   rs   rt   r   BaseCookieSessionFactory\   s    b( rv   sha512pyramid.session.c             C   s<   |dkrt  }t| |||d}t|||||||||	|
|dS )a  
    Configure a :term:`session factory` which will provide signed
    cookie-based sessions.  The return value of this
    function is a :term:`session factory`, which may be provided as
    the ``session_factory`` argument of a
    :class:`pyramid.config.Configurator` constructor, or used
    as the ``session_factory`` argument of the
    :meth:`pyramid.config.Configurator.set_session_factory`
    method.

    The session factory returned by this function will create sessions
    which are limited to storing fewer than 4000 bytes of data (as the
    payload must fit into a single cookie).

    Parameters:

    ``secret``
      A string which is used to sign the cookie. The secret should be at
      least as long as the block size of the selected hash algorithm. For
      ``sha512`` this would mean a 512 bit (64 character) secret.  It should
      be unique within the set of secret values provided to Pyramid for
      its various subsystems (see :ref:`admonishment_against_secret_sharing`).

    ``hashalg``
      The HMAC digest algorithm to use for signing. The algorithm must be
      supported by the :mod:`hashlib` library. Default: ``'sha512'``.

    ``salt``
      A namespace to avoid collisions between different uses of a shared
      secret. Reusing a secret for different parts of an application is
      strongly discouraged (see :ref:`admonishment_against_secret_sharing`).
      Default: ``'pyramid.session.'``.

    ``cookie_name``
      The name of the cookie used for sessioning. Default: ``'session'``.

    ``max_age``
      The maximum age of the cookie used for sessioning (in seconds).
      Default: ``None`` (browser scope).

    ``path``
      The path used for the session cookie. Default: ``'/'``.

    ``domain``
      The domain used for the session cookie.  Default: ``None`` (no domain).

    ``secure``
      The 'secure' flag of the session cookie. Default: ``False``.

    ``httponly``
      Hide the cookie from Javascript by setting the 'HttpOnly' flag of the
      session cookie. Default: ``False``.

    ``samesite``
      The 'samesite' option of the session cookie. Set the value to ``None``
      to turn off the samesite option.  Default: ``'Lax'``.

    ``timeout``
      A number of seconds of inactivity before a session times out. If
      ``None`` then the cookie never expires. This lifetime only applies
      to the *value* within the cookie. Meaning that if the cookie expires
      due to a lower ``max_age``, then this setting has no effect.
      Default: ``1200``.

    ``reissue_time``
      The number of seconds that must pass before the cookie is automatically
      reissued as the result of accessing the session. The
      duration is measured as the number of seconds since the last session
      cookie was issued and 'now'.  If this value is ``0``, a new cookie
      will be reissued on every request accessing the session. If ``None``
      then the cookie's lifetime will never be extended.

      A good rule of thumb: if you want auto-expired cookies based on
      inactivity: set the ``timeout`` value to 1200 (20 mins) and set the
      ``reissue_time`` value to perhaps a tenth of the ``timeout`` value
      (120 or 2 mins).  It's nonsensical to set the ``timeout`` value lower
      than the ``reissue_time`` value, as the ticket will never be reissued.
      However, such a configuration is not explicitly prevented.

      Default: ``0``.

    ``set_on_exception``
      If ``True``, set a session cookie even if an exception occurs
      while rendering a view. Default: ``True``.

    ``serializer``
      An object with two methods: ``loads`` and ``dumps``.  The ``loads``
      method should accept bytes and return a Python object.  The ``dumps``
      method should accept a Python object and return bytes.  A ``ValueError``
      should be raised for malformed inputs.  If a serializer is not passed,
      the :class:`pyramid.session.JSONSerializer` serializer will be used.

    .. warning::

        In :app:`Pyramid` 2.0 the default ``serializer`` option changed to
        use :class:`pyramid.session.JSONSerializer`. See
        :ref:`upgrading_session_20` for more information about why this
        change was made.

    .. versionadded: 1.5a3

    .. versionchanged: 1.10

        Added the ``samesite`` option and made the default ``Lax``.

    .. versionchanged: 2.0

        Changed the default ``serializer`` to be an instance of
        :class:`pyramid.session.JSONSerializer`.

    N)r:   )
rq   rV   rW   rX   rY   rZ   r[   rt   rr   rs   )r   r   rv   )secretrq   rV   rW   rX   rY   rZ   r[   rs   rt   rr   ZhashalgZsaltr:   Zsigned_serializerr   r   r   SignedCookieSessionFactory[  s     rz   r   znpyramid.session.check_csrf_origin is deprecated as of Pyramid 1.9. Use pyramid.csrf.check_csrf_origin instead.r   zlpyramid.session.check_csrf_token is deprecated as of Pyramid 1.9. Use pyramid.csrf.check_csrf_token instead.)
r   Nr(   NFFr)   r*   r   T)r   Nr(   NFFr)   Tr*   r   rw   rx   N)rN   rP   r   r   Zwebob.cookiesr   r   Zzope.deprecationr   Zzope.interfacer   Zpyramid.csrfr   r   Zpyramid.interfacesr   Zpyramid.utilr	   r
   r   r   r   rv   rz   r   r   r   r   <module>   sb   '         
 w            
 