U
    h8                     @   s   d Z ddl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ZddlmZmZmZ G dd dejZG dd deZG dd dejZG dd dejZd
S )a  
Adtlas Authentication Forms

Enhanced authentication forms for the Adtlas DAI Management System.
Includes login, registration, password reset, and profile management forms.

Features:
    - Enhanced login form with remember me functionality
    - User registration with profile creation
    - Password reset with secure token system
    - Profile management forms
    - Form validation and security measures

Author: Adtlas Development Team
Version: 2.0.0
Last Updated: 2025-07-09
    )forms)authenticate)UserCreationFormPasswordResetForm)validate_password)ValidationError)gettext_lazy)timezone)	timedeltaN)UserProfilePasswordResetTokenc                       s   e Zd ZdZejdejddddddededd	Zej	ej
dd
dddded
eddZejddejddddededdZd fdd	Z fddZdd Z  ZS )	LoginFormzS
    Enhanced login form with remember me functionality and security features.
       input100Email AddressTclassplaceholderrequired	autofocusattrs#Enter your registered email address
max_lengthwidgetlabel	help_textPasswordcurrent-password)r   r   r    r   zEnter your passwordr   r   r   Fform-check-inputzremember-me)r   idzRemember mezKeep me logged in for 30 days)r   initialr   r   r   Nc                    s   || _ d| _t j|| dS )zN
        Initialize the form with request context for authentication.
        N)request
user_cachesuper__init__)selfr%   argskwargs	__class__ 4/var/www/html/Focus/src/apps/authentication/forms.pyr(   H   s    zLoginForm.__init__c                    sL  t   }|d}|d}|rH|rH|  }ztjj|d}| r^tt	ddd|j
sttt	ddd|jstt	d	d
dt| j||d| _| jdkr| jd7  _|jdkrt tdd |_|jddgd tt	dddn(|jdkrd|_d|_|jddgd W n( tjk
rF   tt	dddY nX |S )zF
        Validate login credentials and check account status.
        emailpasswordr0   zoAccount is temporarily locked due to multiple failed login attempts. Please try again later or contact support.Zaccount_lockedcodez:Your account has been deactivated. Please contact support.Zaccount_inactivez_Please verify your email address before logging in. Check your inbox for the verification link.Zemail_not_verified)usernamer1   N         )minutesfailed_login_attemptsaccount_locked_until)update_fieldsz,Invalid email or password. Please try again.Zinvalid_credentialsr   )r'   cleangetlowerstripr   objectsis_account_lockedr   _	is_activeis_verifiedr   r%   r&   r:   r	   nowr
   r;   saveDoesNotExist)r)   cleaned_datar0   r1   userr,   r.   r/   r=   P   s\    




zLoginForm.cleanc                 C   s   | j S )z0
        Return the authenticated user.
        )r&   r)   r.   r.   r/   get_user   s    zLoginForm.get_user)N)__name__
__module____qualname____doc__r   
EmailField
EmailInputrC   r0   	CharFieldPasswordInputr1   BooleanFieldCheckboxInputremember_mer(   r=   rL   __classcell__r.   r.   r,   r/   r   !   sF   Kr   c                       s  e Zd ZdZejdejdddddededd	Zej	d
ej
dddddededd	Zej	d
ej
dddddededd	Zej	ejdddddededdZej	ejdddddededdZej	ddej
ddddededdZej	ddej
ddddededdZej	ddej
dddded ed!dZejdejd"d#ided$d%ed&id'ZG d(d) d)Z fd*d+Zd,d- Zd.d/ Zd2 fd0d1	Z  ZS )3UserRegistrationFormz@
    Enhanced user registration form with profile creation.
    r   r   r   Tr   r   r   r   zEnter a valid email addressr      z
First NamezEnter your first namez	Last NamezEnter your last namer   zEnter a strong passwordr!   zConfirm PasswordzRe-enter your password   FzPhone Number (Optional))r   r   zPhone Numberz"Enter your phone number (optional))r   r   r   r   r   d   zJob Title (Optional)z	Job TitlezEnter your job title (optional)zCompany (Optional)Companyz"Enter your company name (optional)r   r"   z2I agree to the Terms of Service and Privacy Policyr   z5You must accept the terms and conditions to register.)r   r   r   error_messagesc                   @   s   e Zd ZeZdZdS )zUserRegistrationForm.Meta)r0   
first_name	last_name	password1	password2N)rM   rN   rO   r   modelfieldsr.   r.   r.   r/   Meta  s   rf   c                    s$   t  j|| d| jkr | jd= d S )Nr5   )r'   r(   re   )r)   r*   r+   r,   r.   r/   r(     s    
zUserRegistrationForm.__init__c                 C   s^   | j d}|rZ|  }tjj|d r>tt	dddt
d|sZtt	ddd|S )	z7
        Validate email uniqueness and format.
        r0   r2   z2An account with this email address already exists.Zemail_existsr3   z0^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$z#Please enter a valid email address.Zinvalid_email)rI   r>   r?   r@   r   rA   filterexistsr   rC   rematch)r)   r0   r.   r.   r/   clean_email  s    z UserRegistrationForm.clean_emailc                 C   s>   | j d}|r:tdd|}td|s:ttddd|S )z;
        Validate phone number format if provided.
        phone_numberz[^\d+] z^\+?1?\d{9,15}$z"Please enter a valid phone number.Zinvalid_phoner3   )rI   r>   ri   subrj   r   rC   )r)   phoner.   r.   r/   clean_phone_number*  s    z'UserRegistrationForm.clean_phone_numberc                    sr   t  jdd}| jd   |_|j|_d|_|rn|  tj	j
|| jdd| jdd| jddd |S )	z:
        Save user and create associated profile.
        F)commitr0   rl   rm   	job_titlecompany)rJ   rl   rr   rs   )r'   rG   rI   r?   r@   r0   r5   rE   r   rA   creater>   )r)   rq   rJ   r,   r.   r/   rG   <  s    	zUserRegistrationForm.save)T)rM   rN   rO   rP   r   rQ   rR   rC   r0   rS   	TextInputr`   ra   rT   rb   rc   rl   rr   rs   rU   rV   Zterms_acceptedrf   r(   rk   rp   rG   rX   r.   r.   r,   r/   rY      s   

  rY   c                   @   sL   e Zd ZdZejdejddddddededd	Zd
d Z	dd Z
dS )PasswordResetRequestFormz-
    Form for requesting password reset.
    r   r   r   Tr   r   r   r   c                 C   sR   | j d}|rN|  }ztjj|dd}|| _W n tjk
rL   Y nX |S )z6
        Validate email exists and is active.
        r0   T)r0   rD   )rI   r>   r?   r@   r   rA   rJ   rH   )r)   r0   rJ   r.   r.   r/   rk   f  s    
z$PasswordResetRequestForm.clean_emailc                 C   s2   t | dr.tjj| jt tdd d}|S dS )z=
        Create password reset token and send email.
        rJ   r6   )hours)rJ   
expires_atN)hasattrr   rA   rt   rJ   r	   rF   r
   )r)   reset_tokenr.   r.   r/   rG   w  s    
zPasswordResetRequestForm.saveN)rM   rN   rO   rP   r   rQ   rR   rC   r0   rk   rG   r.   r.   r.   r/   rv   U  s   rv   c                       s   e Zd ZdZejejdddddededdZejejdd	ddded	ed
dZ	d fdd	Z
dd Z fddZdd Z  ZS )PasswordResetConfirmFormz?
    Form for confirming password reset with new password.
    r   zNew PasswordTrZ   r   zEnter your new passwordr!   zConfirm New PasswordzRe-enter your new passwordNc                    s   || _ t j|| d S )N)rJ   r'   r(   )r)   rJ   r*   r+   r,   r.   r/   r(     s    z!PasswordResetConfirmForm.__init__c              
   C   sX   | j d}|rT| jrTzt|| j W n, tk
rR } zt|jW 5 d}~X Y nX |S )z1
        Validate new password strength.
        new_password1N)rI   r>   rJ   r   r   messages)r)   r1   er.   r.   r/   clean_new_password1  s    
z,PasswordResetConfirmForm.clean_new_password1c                    sB   t   }|d}|d}|r>|r>||kr>ttddd|S )z1
        Validate password confirmation.
        r|   new_password2z&The two password fields did not match.password_mismatchr3   )r'   r=   r>   r   rC   )r)   rI   rb   rc   r,   r.   r/   r=     s    


zPasswordResetConfirmForm.cleanc                 C   s8   | j r4| j | jd  t | j _| j   | j S dS )z,
        Set new password for user.
        r|   N)rJ   set_passwordrI   r	   rF   password_changed_atrG   rK   r.   r.   r/   rG     s    
zPasswordResetConfirmForm.save)N)rM   rN   rO   rP   r   rS   rT   rC   r|   r   r(   r   r=   rG   rX   r.   r.   r,   r/   r{     s.   

r{   )rP   djangor   django.contrib.authr   django.contrib.auth.formsr   r   'django.contrib.auth.password_validationr   django.core.exceptionsr   django.utils.translationr   rC   django.utilsr	   datetimer
   ri   apps.accounts.modelsr   r   r   Formr   rY   rv   r{   r.   r.   r.   r/   <module>   s      43