o
    ؞iV                     @   s  d dl mZmZ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mZ d dlmZ ddlmZmZmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* edgeej+gedddddd Z,edgeej+gedddddd Z-edgeej+gdd Z.edgeej/gdd Z0eddgeej/gdd  Z1edgeej/gd!d" Z2edgeej/gd#d$ Z3edgeej/gd%d& Z4edgeej/gd'd( Z5edgeej+gedd)ddd*d+ Z6edgeej+gd,d- Z7edgeej+gedd.ddd/d0 Z8edgeej+gd1d2 Z9edgeej+gedd.ddd3d4 Z:edgeej+gd5d6 Z;edgeej+geddddd7d8 Z<d9S ):    )statusgenericspermissions)api_viewpermission_classes)Response)RefreshToken)authenticate)validate_password)ValidationErrorsettings)	send_mail)render_to_string)	ratelimit)config   )UserPasswordResetTokenVerificationCode)UserSerializerUserRegistrationSerializerUserProfileSerializerChangePasswordSerializerPasswordResetSerializerPasswordResetConfirmSerializerEmailVerificationSerializer"EmailVerificationConfirmSerializerPhoneVerificationSerializer"PhoneVerificationConfirmSerializerGoogleLoginSerializerPOSTipz5/m)keyratemethodc                 C   s   | j  }d|vs|ds|dd}|r|dd |d< t|d}| rD| }t|}t	t
|j t|t|jdtjdS t	|jtjdS )	zUser Registrationusernameemail @r   datauserrefreshaccessr   )r+   copygetsplitr   is_validsaver   for_userr   r   straccess_tokenr   HTTP_201_CREATEDerrorsHTTP_400_BAD_REQUEST)requestr+   r'   
serializerr-   r.    r>   3/var/www/newdalilibackend/backend/accounts/views.pyregister   s"   


r@   z10/mc                 C   s"  | j d}| j d}|r|stdditjdS d}d|v r:ztjj|d}t|j|d	}W n tj	y9   Y nw t||d	}|du rcd|vrcztjj|d}t|j|d	}W n
 tj	yb   Y nw |du rptdd
itj
dS |js|tdditj
dS t|}tt|j t|t|jdS )z&User Login - accepts username or emailr&   passworderroruc   اسم المستخدم أو البريد الإلكتروني وكلمة المرور مطلوبةr0   Nr)   r'   )r&   rA   uk   اسم المستخدم أو البريد الإلكتروني أو كلمة المرور غير صحيحةu"   حساب المستخدم معطلr,   )r+   r2   r   r   r;   r   objectsr	   r&   DoesNotExistHTTP_401_UNAUTHORIZED	is_activer   r6   r   r7   r8   )r<   username_or_emailrA   r-   user_objr.   r>   r>   r?   login5   sN   
rJ   c              
   C   sv   | j d}|stdditjdS zt|}tdt|jiW S  ty: } ztdditj	dW  Y d}~S d}~ww )zRefresh JWT Tokenr.   rB   zRefresh token is requiredr0   r/   z Invalid or expired refresh tokenN)
r+   r2   r   r   r;   r   r7   r8   	ExceptionrF   )r<   refresh_tokenr.   er>   r>   r?   token_refreshl   s$   
rN   c              
   C   sp   z| j d}|rt|}|  tdditjdW S  ty7 } ztdt|itj	dW  Y d}~S d}~ww )zUser Logoutr.   messagezSuccessfully logged outr0   rB   N)
r+   r2   r   	blacklistr   r   HTTP_200_OKrK   r7   r;   )r<   rL   tokenrM   r>   r>   r?   logout   s   "rS   GETPATCHc                 C   sh   | j dkrt| j}t|jS | j dkr2t| j| jdd}| r*|  t|jS t|jtj	dS dS )zGet or Update User ProfilerT   rU   T)r+   partialr0   N)
r%   r   r-   r   r+   r4   r5   r:   r   r;   )r<   r=   r>   r>   r?   profile   s   




rW   c                 C   sp   t | jd}| r0| j}||jd stdditjdS |	|jd  |
  tddiS t|jtjdS )	zChange User Passwordr*   old_passwordrB   zWrong passwordr0   new_passwordrO   zPassword changed successfully)r   r+   r4   r-   check_passwordvalidated_datar   r   r;   set_passwordr5   r:   )r<   r=   r-   r>   r>   r?   change_password   s   r]   c              
   C   s  d| j vrtdditjdS ddlm} ddlm} z2| j}| j d }d|j	 d	|j
 }|||d
d}||_|jdgd td|jrG|jjnddW S  tyi } ztdt|itjdW  Y d}~S d}~w ty } ztdditjdW  Y d}~S d}~ww )zUpload User AvataravatarrB   zNo avatar file providedr0   r   )
save_imager   zavatars//T)optimizeupdate_fieldszAvatar uploaded successfullyN)rO   
avatar_urlzFailed to upload avatar)FILESr   r   r;   common.utilsr_   django.confr   r-   idnamer^   r5   url
ValueErrorr7   rK   HTTP_500_INTERNAL_SERVER_ERROR)r<   r_   r   r-   
image_file
image_path
saved_pathrM   r>   r>   r?   upload_avatar   s>   



rp   c                 C   s   | j d}|stdditjdS | j}||s"tdditjdS d|_|jdgd zt	
|}|  W n	 ty@   Y nw td	d
itjdS )z!Delete User Account (Soft Delete)rA   rB   u"   كلمة المرور مطلوبةr0   u'   كلمة المرور غير صحيحةFrG   rb   rO   u#   تم حذف الحساب بنجاح)r+   r2   r   r   r;   r-   rZ   rG   r5   r   r6   rP   rK   rQ   )r<   rA   r-   rL   r>   r>   r?   delete_account   s2   

rq   c                    s   | j }g d  fdd| j D }|stdditjdS | D ]\}}t||r1t||| q"|j|	 d t
|}t|jtjdS )z5Update User Settings (notifications, language, theme))notifications_enabledlanguagethemec                    s   i | ]\}}| v r||qS r>   r>   ).0kvallowed_fieldsr>   r?   
<dictcomp>  s    z#update_settings.<locals>.<dictcomp>rB   u)   لا توجد بيانات للتحديثr0   rb   )r-   r+   itemsr   r   r;   hasattrsetattrr5   keysr   rQ   )r<   r-   r+   fieldvaluer=   r>   rx   r?   update_settings   s   
r   z3/hc              
   C   s   t | jd}| st|jtjdS |jd }z
tj	j
|dd}W n tjy4   tdditjd Y S w t|}tjp>d d	|j }ztd
d| tj|jgdd W n tyo } ztd|  W Y d}~nd}~ww tdditjdS )zRequest Password Resetr*   r0   r'   T)r'   rG   rO   z9If the email exists, a password reset link has been sent.zhttp://localhost:3000z/reset-password?token=z#Password Reset Request - Daleeli IQz1Click the following link to reset your password: FsubjectrO   
from_emailrecipient_listfail_silentlyz$Error sending password reset email: N)r   r+   r4   r   r:   r   r;   r[   r   rD   r2   rE   rQ   r   generate_tokenr   FRONTEND_URLrR   r   DEFAULT_FROM_EMAILr'   rK   print)r<   r=   r'   r-   reset_token	reset_urlrM   r>   r>   r?   password_reset  s<   



r   c                 C   s   t | jd}| st|jtjdS |jd }|jd }z
tj	j
|dd}W n tjy9   tdditjd Y S w | sGtdd	itjdS |j}|| |  d
|_|  tddiS )zConfirm Password Resetr*   r0   rR   rY   F)rR   usedrB   zInvalid or expired reset tokenzReset token has expiredTrO   z$Password has been reset successfully)r   r+   r4   r   r:   r   r;   r[   r   rD   r2   rE   r-   r\   r5   r   )r<   r=   	token_strrY   r   r-   r>   r>   r?   password_reset_confirmC  s0   



r   z5/hc              
   C   s  t | jd}| st|jtjdS |jd }z	tj	j
|d}W n tjy3   tdditjd Y S w |jr@tdditjdS t|d}ztd	d
|j tj|jgdd W n" tyz } ztd|  tdditjdW  Y d}~S d}~ww tdditjdS )zRequest Email Verificationr*   r0   r'   rC   rB   #User with this email does not existrO   zEmail is already verifiedzEmail Verification - Daleeli IQzYour verification code is: Fr   z"Error sending verification email: z!Failed to send verification emailNz-Verification code has been sent to your email)r   r+   r4   r   r:   r   r;   r[   r   rD   r2   rE   HTTP_404_NOT_FOUNDemail_verifiedrQ   r   generate_coder   coder   r   r'   rK   r   rl   )r<   r=   r'   r-   verification_coderM   r>   r>   r?   email_verificationh  sL   



r   c                 C      t | jd}| st|jtjdS |jd }|jd }z	tj	j
|d}W n tjy8   tdditjd Y S w ztj	j|d|dd	d
}W n tjy[   tdditjd Y S w | sitdditjdS d|_|  d|_|  tddiS )zConfirm Email Verificationr*   r0   r'   r   rC   rB   r   Fr-   typer   r   
created_atInvalid verification codeVerification code has expiredTrO   zEmail verified successfully)r   r+   r4   r   r:   r   r;   r[   r   rD   r2   rE   r   r   filterlatestr   r5   r   )r<   r=   r'   r   r-   r   r>   r>   r?   email_verification_confirm  L   



r   c                 C   s   t | jd}| st|jtjdS |jd }z	tj	j
|d}W n tjy3   tdditjd Y S w |jr@tdditjdS t|d}tjrTtd	|jd
tjdS tdditjdS )zRequest Phone Verificationr*   r0   phoner   rB   #User with this phone does not existrO   zPhone is already verifiedz#Verification code sent (DEBUG MODE))rO   r   z-Verification code has been sent to your phone)r   r+   r4   r   r:   r   r;   r[   r   rD   r2   rE   r   phone_verifiedrQ   r   r   r   DEBUGr   )r<   r=   r   r-   r   r>   r>   r?   phone_verification  s:   

	r   c                 C   r   )zConfirm Phone Verificationr*   r0   r   r   r   rB   r   Fr   r   r   r   TrO   zPhone verified successfully)r   r+   r4   r   r:   r   r;   r[   r   rD   r2   rE   r   r   r   r   r   r5   r   )r<   r=   r   r   r-   r   r>   r>   r?   phone_verification_confirm  r   r   c                 C   s  t | jd}| st|jtjdS |jd }z"ddlm	} ddl
m} tddd	}|s7td
ditjdW S z||| |}W n! tyc } ztd
dt| itjdW  Y d}~W S d}~ww |d}|dd}	|d}
|d}|r}|std
ditjdW S d}d}z
tjj|dd}W n tjy!   ztjj|d}d|_||_d|_|jsd|_|  W nd tjy   |dd }|}d}tjj|d r| | }|d7 }tjj|d s|	r|	 ng }|r|d nd}t|dkr
d|dd nd}tjj ||||d|ddd}d}Y nw Y nw t!"|}tt#|jt|t|j$dtj%dW S  t&yM   td
ditjd Y S  t'ym } ztd
dt| itjdW  Y d}~S d}~ww ) zGoogle OAuth Loginr*   r0   id_tokenr   )r   )requestsGOOGLE_CLIENT_IDr(   )defaultrB   zRGoogle OAuth not configured. Please set GOOGLE_CLIENT_ID in environment variables.zInvalid token: Nr'   ri   picturesubz'Invalid token: missing email or user IDFgoogle)	social_idsocial_providerrC   Tr)   r   )r&    )r&   r'   
first_name	last_namer   r   r   is_verifiedr,   ztGoogle auth libraries not installed. Install with: pip install google-auth google-auth-oauthlib google-auth-httplib2zAn error occurred: )(r    r+   r4   r   r:   r   r;   r[   google.oauth2r   google.auth.transportr   r   rl   verify_oauth2_tokenRequestrk   r7   r2   r   rD   rE   r   r   r   r   r5   r3   r   existslenjoincreate_userr   r6   r   r8   rQ   ImportErrorrK   )r<   r=   id_token_strr   google_requestsr   idinforM   r'   ri   r   	google_idr-   createdr&   base_usernamecounter
name_partsr   r   r.   r>   r>   r?   google_login(  s   



$

'
r   N)=rest_frameworkr   r   r   rest_framework.decoratorsr   r   rest_framework.responser   rest_framework_simplejwt.tokensr   django.contrib.authr	   'django.contrib.auth.password_validationr
   django.core.exceptionsr   rg   r   django.core.mailr   django.template.loaderr   django_ratelimit.decoratorsr   decoupler   modelsr   r   r   serializersr   r   r   r   r   r   r   r   r   r   r    AllowAnyr@   rJ   rN   IsAuthenticatedrS   rW   r]   rp   rq   r   r   r   r   r   r   r   r   r>   r>   r>   r?   <module>   s    4

4





$
#

'
#
.
/
*
/
