o
    uh�jÉ  ã                   @   sÊ   d dl mZ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dd�Zeeƒfded	B d
efdd„Zeeƒfded	B d
ed	B fdd„Zeeƒfded
efdd„Zeeƒfded
efdd„Zd	S )é    )ÚDependsÚHTTPExceptionÚstatus)Ú
HTTPBearerÚHTTPAuthorizationCredentials)Úget_database)Úget_agent_by_id)Údecode_access_tokenF)Ú
auto_errorÚcredentialsNÚreturnc                 Ã   sª   �| r| j sttjdddid�‚t| j ƒ}|r| d¡s&ttjdddid�‚| d¡}tƒ }t||ƒI dH }|r?| d¡d	krIttjd
ddid�‚t|ƒ}| 	dd¡ |S )z§
    FastAPI dependency that validates Bearer JWT access token and resolves authenticated agent.
    Raises HTTP 401 Unauthorized if missing, invalid, or expired.
    z,Authentication credentials were not providedzWWW-AuthenticateÚBearer)Ústatus_codeÚdetailÚheadersÚsubzInvalid or expired access tokenNr   ÚACTIVEz&Agent account is inactive or not foundÚpasswordHash)
r   r   r   ÚHTTP_401_UNAUTHORIZEDr	   Úgetr   r   ÚdictÚpop©r   ÚpayloadÚagent_idÚdbÚagentÚ
safe_agent© r   ú6/web/html/dev/chatbot/backend/app/dependencies/auth.pyÚget_current_agent	   s4   €
ý
ý
ýr    c                 Ã   sz   �| r| j sdS t| j ƒ}|r| d¡sdS | d¡}tƒ }t||ƒI dH }|r/| d¡dkr1dS t|ƒ}| dd¡ |S )z„
    Optional authentication dependency.
    Returns safe agent dict if valid Bearer token is provided; returns None otherwise.
    Nr   r   r   r   )r   r	   r   r   r   r   r   r   r   r   r   Úget_current_agent_optional-   s   €


r!   Úcurrent_agentc                 Ã   s"   �|   d¡dvrttjdd�‚| S )zS
    Authorization dependency ensuring the caller is an active AGENT or ADMIN.
    Úrole)ÚAGENTÚADMINz,Agent authorization required for this action©r   r   ©r   r   r   ÚHTTP_403_FORBIDDEN©r"   r   r   r   Úrequire_agentD   s   €þr*   c                 Ã   s"   �|   d¡dkrttjdd�‚| S )z}
    Authorization dependency ensuring the caller has ADMIN role.
    Raises HTTP 403 Forbidden if user is not an ADMIN.
    r#   r%   z#Admin role required for this actionr&   r'   r)   r   r   r   Úrequire_adminO   s   €þr+   )Úfastapir   r   r   Úfastapi.securityr   r   Úapp.databaser   Ú!app.repositories.agent_repositoryr   Úapp.utils.securityr	   Úsecurityr   r    r!   r*   r+   r   r   r   r   Ú<module>   s    
"$