o
    *i)                     @   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              	      s   t | |I dH } td| d| ddi|d}| d}t|tr(t|}n|s,d}d}|rN|d d	|id
dd}t	|}|rNt|d d }|| 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_deltaworkforce_idiot_devicesassociated_entity_idlast_updated   r   r>   	device_idzLogin Successful)messageusertoken)r^   r   rL   r   r   r   rR   sortlimitr2   r)   )r3   rS   r_   rn   re   rk   iot_device_cursoriot_device_listr"   r"   r#   process_user_logini   s0   



rs   c                    s   |t  d| ji}|stdddt| j|ds#tddd| jr7|t  	d|d id	d
| jii 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 credentialsr>   $set	fcm_tokenN)COLLECTION_NAMErN   ra   r   pwd_contextverifypasswordrL   ry   
update_oners   access_token_expires)
user_loginrS   
user_in_dbr"   r"   r#   
login_user   s   
r   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.rt   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>   rx   r   )rL   r   r   utcnowrH   rz   rN   
insert_oneinserted_idr~   rs   r   )
r   rS   r   r   otp_submittedstoredusers_collectionr   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.rt   ra   namepicturer9   refresh_tokenTF)
ra   r   picurlgoogle_connectr   r   date_of_birthr   r   r   emailsr=   r[   	   rZ   r>   N)r   r   rx   )r   rn   r   r   HTTP_401_UNAUTHORIZEDrz   rN   rL   r   r   r   r   add_taskr   rs   r   r~   update)google_tokenbackground_tasksrS   	user_infor   r   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   r{   r   rz   rM   rO   rP   JSONEncoderr   r)   r0   r^   rs   r   r   r   r"   r"   r"   r#   <module>   s:    
6-: