o
    Ah%                     @   sR  d dl Z d dlZd dlZd dlmZmZ 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)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__ 6/var/www/html/moveengine/app/v1/services/saas/login.pyr       s
   

zCustomJSONEncoder.default)__name__
__module____qualname__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>)   s    z"serialize_data.<locals>.<dictcomp>c                 S   s   g | ]}t |qS r"   r(   )r*   itemr"   r"   r#   
<listcomp>+   s    z"serialize_data.<locals>.<listcomp>)r   dictitemslistr   r   r   r   )r   r"   r"   r#   r)   '   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)r=   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	   r2   find)r3   dbr5   accounts_collectionaccount_infosubscription_collectionsubscriptionproject_collectionactive_projects_countrole_idrolefeatures_collectionfeatures_listr"   r"   r#   enrich_user_data3   sL   



r^   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mobiler9   )dataexpires_deltazLogin Successful)messageusertoken)r^   r   rL   r)   )r3   rS   r_   rg   r"   r"   r#   process_user_logini   s   rh   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.
    ra   i  zUser not foundstatus_codedetailhashed_passwordi  zInvalid credentialsN)
COLLECTION_NAMErN   ra   r   pwd_contextverifypasswordrL   rh   access_token_expires)
user_loginrS   
user_in_dbr"   r"   r#   
login_userz   s   rt   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.ri   z#OTP not sent for this phone number.expireszOTP expired.zInvalid OTP.rb   Tr9      )rb   created_date
last_login	is_activeis_verifiedmobile_verifiedr=   rZ   r>   $setr|   )rL   r   r   utcnowrH   rm   rN   
insert_oneinserted_id
update_onerh   rq   )
ru   rS   rv   rw   otp_submittedstoredusers_collectionrs   r3   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.ri   ra   namepicturer9   refresh_tokenTF)
ra   r   picurlgoogle_connectr{   r|   date_of_birthr}   r~   r   emailsr=   r[   	   rZ   r>   N)r|   r   r   )r   rg   r   r   HTTP_401_UNAUTHORIZEDrm   rN   rL   r   r   r   r   add_taskr   rh   rq   r   update)google_tokenbackground_tasksrS   	user_infor   rs   r3   emails_collection
invitationr   update_datar"   r"   r#   google_connect_user   s>   


r   ))jsonrI   randomr   r   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   rn   rq   rm   rM   rO   rP   JSONEncoderr   r)   r0   r^   rh   rt   r   r   r"   r"   r"   r#   <module>   s:    
6: