o
    [hC
                     @   sl   d Z ddlmZ ddlZddlZddlmZ ddlmZmZ ddl	m
Z
 dd	lmZ d
ZG dd deZdS )a  
A provided CSRF implementation which puts CSRF data in a session.

This can be used fairly comfortably with many `request.session` type
objects, including the Werkzeug/Flask session store, Django sessions, and
potentially other similar objects which use a dict-like API for storing
session keys.

The basic concept is a randomly generated value is stored in the user's
session, and an hmac-sha1 of it (along with an optional expiration time,
for extra security) is used as the value of the csrf_token. If this token
validates with the hmac of the random value + expiration time, and the
expiration time is not passed, the CSRF validation will pass.
    )unicode_literalsN)sha1)datetime	timedelta   )ValidationError   )
SecureForm)SessionSecureFormc                   @   s.   e Zd ZdZeddZdZdd Zdd ZdS )	r
   z%Y%m%d%H%M%S   )minutesNc                 C   s   | j d u r	td|d u rtdt|d|}d|vr&ttd |d< |d | j_	| j
rCt | j
 | j}d|d |f }nd}|d }tj| j |dtd	}d
|| f S )Nz=must set SECRET_KEY in a subclass of this form for it to workz2Must provide a session-like object as csrf contextsessionZcsrf@   z%s%s utf8	digestmodz%s##%s)
SECRET_KEY	Exception	TypeErrorgetattrr   osurandom	hexdigestZ
csrf_tokencsrf_key
TIME_LIMITr   nowstrftimeTIME_FORMAThmacnewencode)selfZcsrf_contextr   expiresZ
csrf_build	hmac_csrf r%   /home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/wtforms/ext/csrf/session.pygenerate_csrf_token"   s   
z%SessionSecureForm.generate_csrf_tokenc                 C   s   |j rd|j vrt|d|j d\}}|j| d}tj| j|t	d}|
 |kr5t|d| jrKt | j}||krMt|dd S d S )Nz##zCSRF token missingr   r   zCSRF failedzCSRF token expired)datar   gettextsplitr   r!   r   r    r   r   r   r   r   r   r   r   )r"   fieldr#   r$   Z	check_valZhmac_compareZnow_formattedr%   r%   r&   validate_csrf_token8   s   z%SessionSecureForm.validate_csrf_token)	__name__
__module____qualname__r   r   r   r   r'   r,   r%   r%   r%   r&   r
      s    
r
   )__doc__
__future__r   r   r   hashlibr   r   r   Z
validatorsr   formr	   __all__r
   r%   r%   r%   r&   <module>   s    