B
    åCe   ã               @   sZ   d Z ddlmZmZmZmZmZmZ erHddlm	Z	m
Z
mZmZmZmZ G dd„ dƒZdS )a”  
This middleware can be used when a known proxy is fronting the application,
and is trusted to be properly setting the `X-Forwarded-Proto` and
`X-Forwarded-For` headers with the connecting client information.

Modifies the `client` and `scheme` information so that they reference
the connecting client, rather that the connecting proxy.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#Proxies
é    )ÚTYPE_CHECKINGÚListÚOptionalÚTupleÚUnionÚcast)ÚASGI3ApplicationÚASGIReceiveCallableÚASGISendCallableÚ	HTTPScopeÚScopeÚWebSocketScopec               @   sX   e Zd Zddeee ef ddœdd„Zee ee dœdd	„Zd
ddddœdd„Z	dS )ÚProxyHeadersMiddlewareú	127.0.0.1r   N)ÚappÚtrusted_hostsÚreturnc             C   sB   || _ t|tƒr(dd„ | d¡D ƒ| _n
t|ƒ| _d| jk| _d S )Nc             S   s   h | ]}|  ¡ ’qS © )Ústrip)Ú.0Úitemr   r   út/var/www/downstreamdata.science/rtclock/rtclock-venv/lib/python3.7/site-packages/uvicorn/middleware/proxy_headers.pyú	<setcomp>    s    z2ProxyHeadersMiddleware.__init__.<locals>.<setcomp>ú,Ú*)r   Ú
isinstanceÚstrÚsplitr   ÚsetÚalways_trust)Úselfr   r   r   r   r   Ú__init__   s
    

zProxyHeadersMiddleware.__init__)Úx_forwarded_for_hostsr   c             C   s2   | j r|d S xt|ƒD ]}|| jkr|S qW d S )Nr   )r   Úreversedr   )r    r"   Úhostr   r   r   Úget_trusted_client_host%   s    
z.ProxyHeadersMiddleware.get_trusted_client_hostr   r	   r
   )ÚscopeÚreceiveÚsendr   c             Ã   sÊ   |d dkr¶t td |ƒ}| d¡}|r0|d nd }| jsD|| jkr¶t|d ƒ}d|krr|d  d¡}| ¡ |d	< d
|kr¶|d
  d¡}dd„ | d¡D ƒ}	|  	|	¡}
d}|
|f|d< |  
|||¡I d H S )NÚtype)ÚhttpZ	websocket)r   r   Úclientr   Úheaderss   x-forwarded-protoÚlatin1Úschemes   x-forwarded-forc             S   s   g | ]}|  ¡ ‘qS r   )r   )r   r   r   r   r   ú
<listcomp>H   s    z3ProxyHeadersMiddleware.__call__.<locals>.<listcomp>r   )r   r   Úgetr   r   ÚdictÚdecoder   r   r%   r   )r    r&   r'   r(   Úclient_addrZclient_hostr,   Zx_forwarded_protoZx_forwarded_forr"   r$   Úportr   r   r   Ú__call__1   s     

zProxyHeadersMiddleware.__call__)r   )
Ú__name__Ú
__module__Ú__qualname__r   r   r   r!   r   r%   r5   r   r   r   r   r      s   	r   N)Ú__doc__Útypingr   r   r   r   r   r   Zasgiref.typingr   r	   r
   r   r   r   r   r   r   r   r   Ú<module>
   s     
