o
    iv                     @   sV   d dl mZmZ d dlmZ d dlmZ ddlmZ G dd dZ	G dd	 d	eZ
d
S )    )BaseAuthenticationget_authorization_header)
exceptions)AccessToken   )Usuarioc                   @   s4   e Zd ZdZdd Zdd Zedd Zdd	 Zd
S )AuthenticatedUserProxyu   
    Proxy ligero que envuelve tu modelo Usuario y expone is_authenticated=True
    además de delegar todos los atributos/metodos al objeto real.
    c                 C   s
   || _ d S N)_user)selfuser r   5/var/www/html/crm_dreinet/api_login/authentication.py__init__      
zAuthenticatedUserProxy.__init__c                 C   s   t | j|S r	   )getattrr
   )r   namer   r   r   __getattr__   s   z"AuthenticatedUserProxy.__getattr__c                 C   s   dS )NTr   r   r   r   r   is_authenticated   s   z'AuthenticatedUserProxy.is_authenticatedc                 C   s
   t | jS r	   )strr
   r   r   r   r   __str__   r   zAuthenticatedUserProxy.__str__N)	__name__
__module____qualname____doc__r   r   propertyr   r   r   r   r   r   r      s    
r   c                   @   s   e Zd ZdZdd ZdS )CustomJWTAuthenticationz
    Autenticador JWT que busca el usuario en el modelo Usuario (api_login.models.Usuario).
    Devuelve (AuthenticatedUserProxy(user), token) para que DRF reconozca is_authenticated.
    c           	   
   C   s>  t | }|r|d  dkrd S t|dkrtdt|dkr(tdz|d  }W n ty<   tdw zt|}W n t	yY } z
tdt
| d }~ww |d	ph|d
ph|d}|sptdzt|}W n t	y   |}Y nw z	tjj|d}W n tjy   tdw t||fS )Nr   s   bearerr   z.Invalid token header. No credentials provided.   zInvalid token headerzToken decode erroru   Token inválido: user_idr   idzToken no contiene user_id)r    zUser not found)r   splitlowerlenr   AuthenticationFaileddecodeUnicodeErrorr   	Exceptionr   getintr   objectsDoesNotExistr   )	r   requestauthtokenpayloader   pkr   r   r   r   authenticate   s@   




z$CustomJWTAuthentication.authenticateN)r   r   r   r   r2   r   r   r   r   r      s    r   N)rest_framework.authenticationr   r   rest_frameworkr   rest_framework_simplejwt.tokensr   modelsr   r   r   r   r   r   r   <module>   s    