U
    eCh5                     @   s   d 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mZ G dd de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G dd dejZG dd dejZdS )aa  
Enhanced Authentication Forms for Stream Processor

This module provides forms for enhanced authentication features including:
- Enhanced login form with 2FA support
- Password change form with strength validation
- 2FA setup and management forms
- User profile security settings

Author: Stream Processor Development Team
Version: 1.0.0
Created: 2025
    )forms)AuthenticationFormPasswordChangeForm)User)ValidationError)gettext_lazy)authenticate)validate_password   )UserProfilevalidate_strong_passwordc                       s   e Zd ZdZejdejddddddd	Zejejd
ddddddZ	ej
dejddiddZd fdd	Zdd Z  ZS )EnhancedLoginFormz/
    Enhanced login form with 2FA support.
       zappearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-smZUsernameusernameT)classplaceholderautocompleterequiredattrs)
max_lengthwidgetzappearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-smPasswordcurrent-password)r   Fr   Gh-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded)r   r   Nc                    s$   t  j|f|| || _d | _d S N)super__init__request
user_cache)selfr   argskwargs	__class__ >/var/www/html/StreamProcessor/src/apps/authentication/forms.pyr   :   s    zEnhancedLoginForm.__init__c                 C   s   | j d}| j d}|d k	r|rztjj|d}tjj|d\}}| r^ttdddt	| j
||d| _| jd krttd	d
d| jjsttddd| rttdddW n& tjk
r   ttd	d
dY nX | j S )Nr   password)r   userz\Account is temporarily locked due to multiple failed login attempts. Please try again later.Zaccount_locked)code)r   r'   zZPlease enter a correct username and password. Note that both fields may be case-sensitive.invalid_loginzThis account is inactive.inactivez<Password change required. Please contact your administrator.Zpassword_change_required)cleaned_datagetr   objectsr   get_or_createis_account_lockedr   _r   r   r   	is_activeZneeds_password_changeDoesNotExist)r    r   r'   r)   profilecreatedr%   r%   r&   clean?   sJ    

zEnhancedLoginForm.clean)N)__name__
__module____qualname____doc__r   	CharField	TextInputr   PasswordInputr'   BooleanFieldCheckboxInputremember_mer   r7   __classcell__r%   r%   r#   r&   r      s6   
	 r   c                       sP   e Zd ZdZejddejddddddd	d
ddZ fddZdd Z	  Z
S )TwoFactorFormz*
    Form for 2FA token verification.
       zappearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm text-center000000zone-time-code[0-9]{6}numeric6T)r   r   r   pattern	inputmode	maxlengthr   r   )r   
min_lengthr   c                    s   t  j|| || _d S r   r   r   r)   r    r)   r!   r"   r#   r%   r&   r      s    zTwoFactorForm.__init__c                 C   s   | j d}|sttd| s0ttdz*tjj| jd}||sXttdW n" tj	k
r|   ttdY nX |S )Ntokenz:Please enter the 6-digit code from your authenticator app.zToken must contain only digits.r(   z+Invalid or expired token. Please try again.#2FA is not set up for this account.
r-   r.   r   r2   isdigitr   r/   r)   Zverify_2fa_tokenr4   r    rO   r5   r%   r%   r&   clean_token   s    
zTwoFactorForm.clean_token)r8   r9   r:   r;   r   r<   r=   rO   r   rT   rB   r%   r%   r#   r&   rC   t   s    rC   c                   @   s   e Zd ZdZejeddejdddddZejed	dejdd
ddeddZ	ejeddejdd
dddZ
dd ZdS )EnhancedPasswordChangeFormzA
    Enhanced password change form with strength validation.
    zCurrent passwordFmt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-smr   r   r   r   )labelstripr   zNew passwordznew-passwordzoPassword must be at least 12 characters long and contain uppercase, lowercase, numbers, and special characters.rX   rY   r   	help_textzConfirm new passwordc                 C   s(   | j d}|r$t|| j t| |S )Nnew_password1)r-   r.   r	   r)   r   r    r'   r%   r%   r&   clean_new_password1   s
    z.EnhancedPasswordChangeForm.clean_new_password1N)r8   r9   r:   r;   r   r<   r2   r>   old_passwordr\   new_password2r^   r%   r%   r%   r&   rU      s:   		rU   c                       sZ   e Zd ZdZejddedejdddddd	d
deddZ fddZ	dd Z
  ZS )Setup2FAFormz"
    Form for setting up 2FA.
    rD   zVerification Codemt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm text-centerrE   rF   rG   rH   T)r   r   rI   rJ   rK   r   r   zCEnter the 6-digit code from your authenticator app to verify setup.r   rL   rX   r   r[   c                    s   t  j|| || _d S r   rM   rN   r#   r%   r&   r      s    zSetup2FAForm.__init__c                 C   s   | j d}|sttd| s0ttdz*tjj| jd}||sXttdW n" tj	k
r|   ttdY nX |S )Nverification_tokenz#Please enter the verification code.z+Verification code must contain only digits.r(   zMInvalid verification code. Please check your authenticator app and try again.z:2FA setup not found. Please start the setup process again.rQ   rS   r%   r%   r&   clean_verification_token   s    
z%Setup2FAForm.clean_verification_token)r8   r9   r:   r;   r   r<   r2   r=   rd   r   re   rB   r%   r%   r#   r&   ra      s"   ra   c                       sp   e Zd ZdZejeddejddddedd	Zej	ed
ej
ddidddZ fddZdd Z  ZS )Disable2FAFormz!
    Form for disabling 2FA.
    zCurrent PasswordFrV   r   rW   r   z+Enter your current password to disable 2FA.rZ   z@I understand that disabling 2FA will make my account less securer   r   T)rX   r   r   c                    s   t  j|| || _d S r   rM   rN   r#   r%   r&   r     s    zDisable2FAForm.__init__c                 C   s(   | j d}| j|s$ttd|S )Nr'   zIncorrect password.)r-   r.   r)   check_passwordr   r2   r]   r%   r%   r&   clean_password  s    zDisable2FAForm.clean_password)r8   r9   r:   r;   r   r<   r2   r>   r'   r?   r@   Zconfirmationr   rh   rB   r%   r%   r#   r&   rf      s(   
 rf   c                   @   s.   e Zd ZdZG dd dZdd Zdd ZdS )	SecuritySettingsFormz3
    Form for managing user security settings.
    c                   @   sf   e Zd ZeZddgZejdddddejddd	ddd
Ze	de	dd
Z
e	de	dd
ZdS )zSecuritySettingsForm.Metamax_concurrent_sessionssession_timeout_minutesrV   110)r   minmaxr   Z30Z1440)rj   rk   zMaximum Concurrent SessionszSession Timeout (minutes)z4Maximum number of simultaneous login sessions (1-10)z@How long sessions stay active without activity (30-1440 minutes)N)r8   r9   r:   r   modelfieldsr   NumberInputwidgetsr2   labels
help_textsr%   r%   r%   r&   Meta%  s&   rv   c                 C   s,   | j d}|dk s|dkr(ttd|S )Nrj   r
   
   z"Must be between 1 and 10 sessions.r-   r.   r   r2   r    valuer%   r%   r&   clean_max_concurrent_sessions=  s    z2SecuritySettingsForm.clean_max_concurrent_sessionsc                 C   s,   | j d}|dk s|dkr(ttd|S )Nrk      i  z$Must be between 30 and 1440 minutes.rx   ry   r%   r%   r&   clean_session_timeout_minutesC  s    z2SecuritySettingsForm.clean_session_timeout_minutesN)r8   r9   r:   r;   rv   r{   r}   r%   r%   r%   r&   ri      s   ri   c                       sX   e Zd ZdZejddedejdddddd	d
eddZ fddZ	dd Z
  ZS )BackupCodesFormz.
    Form for using backup codes for 2FA.
       zBackup Coderb   ZXXXXXXXXztext-transform: uppercase;8T)r   r   stylerK   r   r   zEnter one of your backup codes.rc   c                    s   t  j|| || _d S r   rM   rN   r#   r%   r&   r   ]  s    zBackupCodesForm.__init__c                 C   st   | j dd }|s"ttdz*tjj| jd}||jkrJttdW n" tj	k
rn   ttdY nX |S )Nbackup_code zPlease enter a backup code.r(   zInvalid backup code.rP   )
r-   r.   upperr   r2   r   r/   r)   backup_codesr4   )r    r*   r5   r%   r%   r&   clean_backup_codea  s    
z!BackupCodesForm.clean_backup_code)r8   r9   r:   r;   r   r<   r2   r=   r   r   r   rB   r%   r%   r#   r&   r~   J  s    r~   N)r;   djangor   django.contrib.auth.formsr   r   django.contrib.auth.modelsr   django.core.exceptionsr   django.utils.translationr   r2   django.contrib.authr   'django.contrib.auth.password_validationr	   authenticationr   r   r   FormrC   rU   ra   rf   	ModelFormri   r~   r%   r%   r%   r&   <module>   s   Y+1,$*