o
    sgc                     @   s   d dl Z d dlmZmZmZmZ d dlmZmZ d dl	m
Z
mZmZ d dlmZ d dlmZ d dlmZ edd	gd
ZG dd deZe Zeddd ZededfddZeddefddZeddd ZeddefddZdS )    N)	APIRouterBodyHTTPExceptionRequest)JSONResponseRedirectResponse)ACCESS_TOKENID_TOKENREFRESH_TOKEN)UserBase)AuthService)DynamoDBz/authAuthentication)prefixtagsc                   @   s   e Zd ZdZdS )UserInfozP
    User information model extending UserBase for authentication responses
    N)__name__
__module____qualname____doc__ r   r   3/var/www/html/XCapMarket/controllers/auth_router.pyr      s    r   z/loginc                     s   t  I dH } t| S )z1
    Redirects to Cognito-hosted login page.
    N)auth_serviceloginr   )	login_urlr   r   r   r      s   r   z	/callback.c              
      s   t |  z.t| dI dH }tdd|d dd}tjdd	k}|jt|d
 d| dd |W S  t	yI } z
t | t
dddd}~ww )z[
    Handles Cognito's callback with the authorization code and redirects to frontend.
    codeN   zAuthentication successfulfrontend_url)messageredirect_urlstatus_codecontentAWS_SAM_LOCALtruerefresh_tokenT  )keyvaluehttponlysecuremax_agei  zFailed to handle callbackr!   detail)printr   handle_callbackgetr   osenviron
set_cookier
   	Exceptionr   )bodyresultresponseis_localer   r   r   callback"   s0   r:   z/userrequestc                    sd   | j j}|r,t }||j|j}|rtdi |S ||j|j}|r,tdi |S tddd)Ni  zUser not foundr,   r   )	statecurrent_userr   get_itemuseremailr   user_idr   )r;   r=   dbuser_detailsr   r   r   get_user_infoA   s   rD   z/logoutc                     s(   t  } tdd| id}|t |S )zHandle user logoutr   
logout_urlr    )r   get_logout_urlr   delete_cookier
   )rE   r7   r   r   r   logoutS   s
   
rH   z/refresh-tokenc              	      sn   | j t}t|I dH }td|t|t|ddd}|tp(|}|jt|dddd	d
d |S )zL
    Refresh the access token using the refresh token stored in cookies
    Nr   
expires_in)access_tokenid_tokenrI   r    TFr&   /lax)r'   r(   r)   r*   r+   pathsamesite)	cookiesr0   r
   r   r%   r   r   r	   r3   )r;   r%   tokensr7   new_refresh_tokenr   r   r   r%   \   s*   	
r%   )r1   fastapir   r   r   r   fastapi.responsesr   r   configs.configr   r	   r
   models.userr   services.auth_servicer   utils.dynamo_dbr   authr   r   r0   r   postr:   rD   rH   r%   r   r   r   r   <module>   s(    

