o
    ̿Si&                     @   s  d dl Z d dlZd dlZd dlmZmZ zd dlZeeds)G dd dZe e_	W n	 e
y3   Y nw d dlmZ d dlmZmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlZe  edgddZ eddZ!dZ"dZ#dZ$dZ%G dd de j&Z'dd Z(de)de)fdd Z*de)d!ede)fd"d#Z+de)fd$d%Z,d&e)d'e)de)fd(d)Z-de)fd*d+Z.dS ),    N)datetime	timedelta	__about__c                   @   s   e Zd ZeeddZdS )_About__version__0N)__name__
__module____qualname__getattr_bcryptr    r   r   8/var/www/html/Trade-python/app/v1/services/saas/login.pyr      s    r   )CryptContext)HTTPExceptionstatus)create_access_token)str_to_objectid)get_role_service)FeatureBase)verify_google_token)send_welcome_email)ObjectId)load_dotenvbcryptauto)schemes
deprecatedi7  )minutesusersaccountssubscriptionsprojectsc                       s   e Zd Z fddZ  ZS )CustomJSONEncoderc                    s0   t |tr	| S t |trt|S t |S )N)
isinstancer   	isoformatr   strsuperdefault)selfobj	__class__r   r   r(   .   s
   

zCustomJSONEncoder.default)r   r	   r
   r(   __classcell__r   r   r+   r   r#   -   s    r#   c                 C   s^   t | trdd |  D S t | trdd | D S t | tjr$|  S t | tr-t| S | S )Nc                 S   s   i | ]	\}}|t |qS r   serialize_data).0kvr   r   r   
<dictcomp>7   s    z"serialize_data.<locals>.<dictcomp>c                 S   s   g | ]}t |qS r   r.   )r0   itemr   r   r   
<listcomp>9   s    z"serialize_data.<locals>.<listcomp>)r$   dictitemslistr   r%   r   r&   )r*   r   r   r   r/   5   s   


r/   	user_datareturnc                    sj  t tdd}| dd | dd | dd | d| | d	d | d
r|t }|dt| d
 i}|r|dd| d< |dd| d< |dd| d< |dr}|t }|dt|di}|r||dd| d	< |d|| d< n|t	 }|
| d
 dd}|| d	< | d}	|	rt|	|}
|
r|
di | d< |d }t| }|| d< | S )z
    Enriches user data with common details:
      - Account information (subscription, active agents, etc.)
      - Role rights from roles service.
    ALLOWED_FREE_AGENTS5account_typer   subscription_id subscription_statussubscription_agentsactive_agents
account_id_idactive_subscription_idactive_agents_countsubscription_agents_countACTIVE)rC   r   rolespermissionsrole_rightsfeaturesrole_features)intosgetenv
setdefaultgetACCOUNT_COLLECTION_NAMEfind_oner   SUBSCRIPTION_COLLECTION_NAMEPROJECT_COLLECTION_NAMEcount_documentsr   r8   find)r9   dbr;   accounts_collectionaccount_infosubscription_collectionsubscriptionproject_collectionactive_projects_countrole_idrolefeatures_collectionfeatures_listr   r   r   enrich_user_dataA   sL   



rd   token_expires_deltac              	      sF   t | |I dH } td| d| ddi|d}t| } d| |dS )	z
    Common login processing:
      - Enrich user data with account/role details.
      - Generate a JWT token.
      - Serialize user data for the response.
    Nsubemailmobiler?   )dataexpires_deltazLogin Successful)messageusertoken)rd   r   rR   r/   )r9   rY   re   rm   r   r   r   process_user_loginw   s   rn   c                    sX   |t  d| ji}|stdddt| j|ds#tdddt||t	I dH S )	z+
    Handles the email/password login.
    rg   i  zUser not foundstatus_codedetailhashed_passwordi  zInvalid credentialsN)
COLLECTION_NAMErT   rg   r   pwd_contextverifypasswordrR   rn   access_token_expires)
user_loginrY   
user_in_dbr   r   r   
login_user   s   rz   payload	otp_storec           
   	      s  |  d}|  d}|r|du rtddd||vr!tddd|| }t |d kr6||= tdd	d|d t|krDtdd
d||= |t }|d|i}|sn|t t dddddd}||j}	|	|d< n|	d|d iddt ii |}t
||tI dH S )a  
    Verifies the OTP for a phone login.
    This function handles:
      - Validating the OTP (using an in-memory store for demo purposes)
      - Looking up (or creating) the user by phone
      - Processing the login (enriching user data and generating JWT token)
    phoneotpNi  z"Phone number and OTP are required.ro   z#OTP not sent for this phone number.expireszOTP expired.zInvalid OTP.rh   Tr?      )rh   created_date
last_login	is_activeis_verifiedmobile_verifiedrC   r`   rD   $setr   )rR   r   r   utcnowrN   rs   rT   
insert_oneinserted_id
update_onern   rw   )
r{   rY   r|   r}   otp_submittedstoredusers_collectionry   r9   r   r   r   r   verify_phone_otp_service   sD   




r   c                    s6  t | j}|sttjdd|t }|d|d i}|sx|d |d |dd|d t	 t	 t	 ddd	d

}|d }|d|d i}|rZ|dd|d< |dd|d< |
|j}	|	|d< |t|d |d  t||tI dH S t	 |d d}
|d|d id|
i ||
 t||tI dH S )z'
    Handles Google Connect login.
    zInvalid Google token.ro   rg   namepicturer?   refresh_tokenTF)
rg   r   picurlgoogle_connectr   r   date_of_birthr   r   r   emailsrC   ra   	   r`   rD   N)r   r   r   )r   rm   r   r   HTTP_401_UNAUTHORIZEDrs   rT   rR   r   r   r   r   add_taskr   rn   rw   r   update)google_tokenbackground_tasksrY   	user_infor   ry   r9   emails_collection
invitationr   update_datar   r   r   google_connect_user   s>   


r   )/jsonrO   randomr   r   r   r   hasattrr   r   	Exceptionpasslib.contextr   fastapir   r   app.v1.dependencies.authr   app.v1.libraries.objectr   app.v1.services.saas.rolesr   app.v1.models.crudmodelr   app.v1.libraries.googleconnectr    app.v1.libraries.email_templatesr   bsonr   dotenvr   rt   rw   rs   rS   rU   rV   JSONEncoderr#   r/   r6   rd   rn   rz   r   r   r   r   r   r   <module>   sL    

6: