
_8                 @   s  d  Z  d d l Z d d l Z d d l m Z d d l m Z d d l m Z d d l m Z d d l	 m
 Z
 d d	 l m Z d d
 l m Z d d l m Z Gd d   d e
 j  Z Gd d   d e e  Z Gd d   d e  Z Gd d   d e  Z e   Z Gd d   d e  Z d S)z
    flask.sessions
    ~~~~~~~~~~~~~~

    Implements cookie based sessions based on itsdangerous.

    :copyright: 2010 Pallets
    :license: BSD-3-Clause
    N)datetime)BadSignature)URLSafeTimedSerializer)CallbackDict   )collections_abc)is_ip)total_seconds)TaggedJSONSerializerc               @   sO   e  Z d  Z d Z e d d    Z e j d d    Z d Z d Z d Z	 d S)SessionMixinz3Expands a basic dictionary with session attributes.c             C   s   |  j  d d  S)z3This reflects the ``'_permanent'`` key in the dict.
_permanentF)get)self r   //tmp/pip-build-5gj8f0j9/flask/flask/sessions.py	permanent   s    zSessionMixin.permanentc             C   s   t  |  |  d <d  S)Nr   )bool)r   valuer   r   r   r   !   s    FTN)
__name__
__module____qualname____doc__propertyr   setternewmodifiedaccessedr   r   r   r   r      s   r   c                   ss   e  Z d  Z d Z d Z d Z d   f d d  Z   f d d   Z d   f d d	  Z d   f d
 d  Z	   S)SecureCookieSessiona	  Base class for sessions based on signed cookies.

    This session backend will set the :attr:`modified` and
    :attr:`accessed` attributes. It cannot reliably track whether a
    session is new (vs. empty), so :attr:`new` remains hard coded to
    ``False``.
    FNc                s)   d d   } t  t |   j | |  d  S)Nc             S   s   d |  _  d |  _ d  S)NT)r   r   )r   r   r   r   	on_updateL   s    	z/SecureCookieSession.__init__.<locals>.on_update)superr   __init__)r   initialr   )	__class__r   r   r    K   s    zSecureCookieSession.__init__c                s   d |  _  t t |   j |  S)NT)r   r   r   __getitem__)r   key)r"   r   r   r#   R   s    	zSecureCookieSession.__getitem__c                s"   d |  _  t t |   j | |  S)NT)r   r   r   r   )r   r$   default)r"   r   r   r   V   s    	zSecureCookieSession.getc                s"   d |  _  t t |   j | |  S)NT)r   r   r   
setdefault)r   r$   r%   )r"   r   r   r&   Z   s    	zSecureCookieSession.setdefault)
r   r   r   r   r   r   r    r#   r   r&   r   r   )r"   r   r   5   s   r   c               @   sC   e  Z d  Z d Z d d   Z e Z Z Z Z Z	 Z
 Z [ d S)NullSessionzClass used to generate nicer error messages if sessions are not
    available.  Will still allow read-only access to the empty session
    but fail on setting.
    c             O   s   t  d   d  S)NzThe session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.)RuntimeError)r   argskwargsr   r   r   _faile   s    zNullSession._failN)r   r   r   r   r+   __setitem____delitem__clearpoppopitemupdater&   r   r   r   r   r'   _   s   r'   c               @   s   e  Z d  Z d Z e Z d Z d d   Z d d   Z d d   Z	 d	 d
   Z
 d d   Z d d   Z d d   Z d d   Z d d   Z d d   Z d d   Z d S)SessionInterfacea  The basic interface you have to implement in order to replace the
    default session interface which uses werkzeug's securecookie
    implementation.  The only methods you have to implement are
    :meth:`open_session` and :meth:`save_session`, the others have
    useful defaults which you don't need to change.

    The session object returned by the :meth:`open_session` method has to
    provide a dictionary like interface plus the properties and methods
    from the :class:`SessionMixin`.  We recommend just subclassing a dict
    and adding that mixin::

        class Session(dict, SessionMixin):
            pass

    If :meth:`open_session` returns ``None`` Flask will call into
    :meth:`make_null_session` to create a session that acts as replacement
    if the session support cannot work because some requirement is not
    fulfilled.  The default :class:`NullSession` class that is created
    will complain that the secret key was not set.

    To replace the session interface on an application all you have to do
    is to assign :attr:`flask.Flask.session_interface`::

        app = Flask(__name__)
        app.session_interface = MySessionInterface()

    .. versionadded:: 0.8
    Fc             C   s
   |  j    S)a  Creates a null session which acts as a replacement object if the
        real session support could not be loaded due to a configuration
        error.  This mainly aids the user experience because the job of the
        null session is to still support lookup without complaining but
        modifications are answered with a helpful error message of what
        failed.

        This creates an instance of :attr:`null_session_class` by default.
        )null_session_class)r   appr   r   r   make_null_session   s    
z"SessionInterface.make_null_sessionc             C   s   t  | |  j  S)zChecks if a given object is a null session.  Null sessions are
        not asked to be saved.

        This checks if the object is an instance of :attr:`null_session_class`
        by default.
        )
isinstancer3   )r   objr   r   r   is_null_session   s    z SessionInterface.is_null_sessionc             C   s   | j  d } | d k	 r' | r# | Sd S| j  d } | sK d | j  d <d S| j d d  d j d  } d | k r t j d	 j d
 |   d | j  d <d St |  } | r t j d  |  j |  d k r | r d | } | | j  d <| S)aM  Returns the domain that should be set for the session cookie.

        Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise
        falls back to detecting the domain based on ``SERVER_NAME``.

        Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is
        updated to avoid re-running the logic.
        ZSESSION_COOKIE_DOMAINNZSERVER_NAMEF:r   r   .z"{rv}" is not a valid cookie domain, it must contain a ".". Add an entry to your hosts file, for example "{rv}.localdomain", and use that instead.rvzThe session cookie domain is an IP address. This may not work as intended in some browsers. Add an entry to your hosts file, for example "localhost.localdomain", and use that instead./)configrsplitlstripwarningswarnformatr   get_cookie_path)r   r4   r;   ipr   r   r   get_cookie_domain   s,    
	

z"SessionInterface.get_cookie_domainc             C   s   | j  d p | j  d S)a  Returns the path for which the cookie should be valid.  The
        default implementation uses the value from the ``SESSION_COOKIE_PATH``
        config var if it's set, and falls back to ``APPLICATION_ROOT`` or
        uses ``/`` if it's ``None``.
        ZSESSION_COOKIE_PATHZAPPLICATION_ROOT)r=   )r   r4   r   r   r   rC      s    z SessionInterface.get_cookie_pathc             C   s   | j  d S)zReturns True if the session cookie should be httponly.  This
        currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``
        config var.
        ZSESSION_COOKIE_HTTPONLY)r=   )r   r4   r   r   r   get_cookie_httponly   s    z$SessionInterface.get_cookie_httponlyc             C   s   | j  d S)zReturns True if the cookie should be secure.  This currently
        just returns the value of the ``SESSION_COOKIE_SECURE`` setting.
        ZSESSION_COOKIE_SECURE)r=   )r   r4   r   r   r   get_cookie_secure   s    z"SessionInterface.get_cookie_securec             C   s   | j  d S)zReturn ``'Strict'`` or ``'Lax'`` if the cookie should use the
        ``SameSite`` attribute. This currently just returns the value of
        the :data:`SESSION_COOKIE_SAMESITE` setting.
        ZSESSION_COOKIE_SAMESITE)r=   )r   r4   r   r   r   get_cookie_samesite   s    z$SessionInterface.get_cookie_samesitec             C   s   | j  r t j   | j Sd S)a  A helper method that returns an expiration date for the session
        or ``None`` if the session is linked to the browser session.  The
        default implementation returns now + the permanent session
        lifetime configured on the application.
        N)r   r   utcnowpermanent_session_lifetime)r   r4   sessionr   r   r   get_expiration_time  s    	z$SessionInterface.get_expiration_timec             C   s   | j  p | j o | j d S)a  Used by session backends to determine if a ``Set-Cookie`` header
        should be set for this session cookie for this response. If the session
        has been modified, the cookie is set. If the session is permanent and
        the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is
        always set.

        This check is usually skipped if the session was deleted.

        .. versionadded:: 0.11
        ZSESSION_REFRESH_EACH_REQUEST)r   r   r=   )r   r4   rK   r   r   r   should_set_cookie  s    	z"SessionInterface.should_set_cookiec             C   s   t     d S)a%  This method has to be implemented and must either return ``None``
        in case the loading failed because of a configuration error or an
        instance of a session object which implements a dictionary like
        interface + the methods and attributes on :class:`SessionMixin`.
        N)NotImplementedError)r   r4   requestr   r   r   open_session  s    zSessionInterface.open_sessionc             C   s   t     d S)zThis is called for actual sessions returned by :meth:`open_session`
        at the end of the request.  This is still called during a request
        context so if you absolutely need access to the request you can do
        that.
        N)rN   )r   r4   rK   responser   r   r   save_session'  s    zSessionInterface.save_sessionN)r   r   r   r   r'   r3   Zpickle_basedr5   r8   rE   rC   rF   rG   rH   rL   rM   rP   rR   r   r   r   r   r2   p   s   	:	r2   c               @   sa   e  Z d  Z d Z d Z e e j  Z d Z	 e
 Z e Z d d   Z d d   Z d d	   Z d
 S)SecureCookieSessionInterfacezuThe default session interface that stores sessions in signed cookies
    through the :mod:`itsdangerous` module.
    zcookie-sessionhmacc             C   sM   | j  s d  St d |  j d |  j  } t | j  d |  j d |  j d | S)Nkey_derivationdigest_methodsalt
serializersigner_kwargs)Z
secret_keydictrU   rV   r   rW   rX   )r   r4   rY   r   r   r   get_signing_serializerF  s    				z3SecureCookieSessionInterface.get_signing_serializerc             C   s   |  j  |  } | d  k r d  S| j j | j  } | sD |  j   St | j  } y& | j | d | } |  j |  SWn t k
 r |  j   SYn Xd  S)Nmax_age)	r[   cookiesr   session_cookie_namesession_classr	   rJ   loadsr   )r   r4   rO   svalr\   datar   r   r   rP   S  s    
z)SecureCookieSessionInterface.open_sessionc             C   s  |  j  |  } |  j |  } | sM | j rI | j | j d | d | d  S| j rf | j j d  |  j | |  s| d  S|  j	 |  } |  j
 |  } |  j |  } |  j | |  }	 |  j |  j t |   }
 | j | j |
 d |	 d | d | d | d | d | d  S)NdomainpathCookieexpireshttponlysecuresamesite)rE   rC   r   Zdelete_cookier^   r   varyaddrM   rF   rG   rH   rL   r[   dumpsrZ   
set_cookie)r   r4   rK   rQ   rd   re   rh   ri   rj   rg   rb   r   r   r   rR   a  s2    		z)SecureCookieSessionInterface.save_sessionN)r   r   r   r   rW   staticmethodhashlibsha1rV   rU   session_json_serializerrX   r   r_   r[   rP   rR   r   r   r   r   rS   3  s   rS   )r   rp   r@   r   Zitsdangerousr   r   Zwerkzeug.datastructuresr   _compatr   helpersr   r	   Zjson.tagr
   MutableMappingr   r   r'   objectr2   rr   rS   r   r   r   r   <module>
   s    *	