o
    h 
                     @   s   d 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	m
Z
 ddlmZ ddlmZ ddlmZ eeZG d	d
 d
eZG dd deZG dd deZdS )z=
Custom middleware for rate limiting, logging, and security.
    N)defaultdict)DictSet)RequestHTTPException)JSONResponse)BaseHTTPMiddleware)Responsec                       s6   e Zd ZdZd	def fddZdefddZ  ZS )
RateLimitMiddlewarezRate limiting middleware.d   requests_per_minutec                    s    t  | || _tt| _d S )N)super__init__r   r   listrequests)selfappr   	__class__ +/var/www/html/aiguide_backend/middleware.pyr      s   zRateLimitMiddleware.__init__requestc                    sr   |j j}t   fdd| j| D | j|< t| j| | jkr*tdddidS | j|   ||I d H S )Nc                    s   g | ]
} | d k r|qS )<   r   ).0req_timecurrent_timer   r   
<listcomp>   s
    z0RateLimitMiddleware.dispatch.<locals>.<listcomp>i  detailz,Rate limit exceeded. Please try again later.)status_codecontent)clienthosttimer   lenr   r   append)r   r   	call_next	client_ipr   r   r   dispatch   s   
zRateLimitMiddleware.dispatch)r   )	__name__
__module____qualname____doc__intr   r   r(   __classcell__r   r   r   r   r
      s    r
   c                   @      e Zd ZdZdefddZdS )LoggingMiddlewarezRequest logging middleware.r   c                    sj   t   }td|j d|jj d|jj  ||I d H }t   | }td|j d|dd |S )Nz	Request:  z from z
Response: z in z.3fs)	r#   loggerinfomethodurlpathr!   r"   r   )r   r   r&   
start_timeresponseprocess_timer   r   r   r(   2   s   &zLoggingMiddleware.dispatchNr)   r*   r+   r,   r   r(   r   r   r   r   r0   /       r0   c                   @   r/   )SecurityMiddlewarezSecurity headers middleware.r   c                    sF   ||I d H }d|j d< d|j d< d|j d< d|j d< d	|j d
< |S )NnosniffzX-Content-Type-OptionsDENYzX-Frame-Optionsz1; mode=blockzX-XSS-Protectionzstrict-origin-when-cross-originzReferrer-Policyz(geolocation=(), microphone=(), camera=()zPermissions-Policy)headers)r   r   r&   r9   r   r   r   r(   D   s   




zSecurityMiddleware.dispatchNr;   r   r   r   r   r=   A   r<   r=   )r,   r#   loggingcollectionsr   typingr   r   fastapir   r   fastapi.responsesr   starlette.middleware.baser   starlette.responsesr	   	getLoggerr)   r3   r
   r0   r=   r   r   r   r   <module>   s    
