o
    $ahO                     @   s   d 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 ddlmZ dd	lmZ d
dlmZmZmZmZ eeG dd dejZeeG dd dejZeeG dd dejZeeG dd dejZdS )z
Authentication Admin Module

This module contains Django admin configurations for authentication models
including login attempts, password reset tokens, email verification tokens,
and user sessions.

Author: Senior Django Developer
Date: 2024
    )admin)gettext_lazy)format_html)reverse)	mark_safe)CountQ)timezone)	timedelta   )LoginAttemptPasswordResetTokenEmailVerificationTokenUserSessionc                       s  e Zd ZdZg dZdddddejfgZg dZd	gZ	dZ
g d
ZedddifedddifeddddfeddddffZdZdd Zd-ddZdd Zede_de_d d! Zed"e_ fd#d$Zd%d&gZd'd( Zed)e_d*d+ Zed,e_  ZS ).LoginAttemptAdminz
    Admin configuration for LoginAttempt model.
    
    Provides comprehensive management interface for monitoring
    and analyzing login attempts for security purposes.
    )	attempted_email	user_linkis_successful
ip_addresscountrycityfailure_reason
created_atuser_agent_shortr   r   r   r   user)r   r   user__emailuser__first_nameuser__last_namer   r   -created_at)r   r   r   
user_agentr   r   r   r   r   
updated_at
created_by
updated_byzLogin Informationfields)r   r   r   r   zTechnical Details)r   r   Location Informationr   r   collapser#   classesMetadatar   r    r!   r"   2   c                 C      dS )z*Disable add permission for login attempts.FN selfrequestr.   r.   OC:\Users\vibe-look\OneDrive\Desktop\Adtlas_V\src\apps\authentification\admin.pyhas_add_permission      z$LoginAttemptAdmin.has_add_permissionNc                 C   r-   )z-Disable change permission for login attempts.FNr.   )r0   r1   objr.   r.   r2   has_change_permission   r4   z'LoginAttemptAdmin.has_change_permissionc                 C   s0   |j rtd|j jgd}td||j jS tdS )z
        Display a link to the user if exists.
        
        Args:
            obj: LoginAttempt instance
            
        Returns:
            str: HTML link to user or 'Unknown User'
        admin:accounts_user_changeargs<a href="{}">{}</a>zUnknown UserN)r   r   pkr   email_r0   r5   urlr.   r.   r2   r      s   
zLoginAttemptAdmin.user_linkUserr   c                 C   s0   |j rt|j dkr|j dd d S |j S dS )z
        Display a shortened version of user agent.
        
        Args:
            obj: LoginAttempt instance
            
        Returns:
            str: Shortened user agent string
        r,   N...-)r   lenr0   r5   r.   r.   r2   r      s   
&z"LoginAttemptAdmin.user_agent_shortz
User Agentc                       t  |dS z
        Optimize queryset with select_related for better performance.
        
        Args:
            request: HTTP request object
            
        Returns:
            QuerySet: Optimized queryset
        r   Nsuperget_querysetselect_relatedr/   	__class__r.   r2   rI         
zLoginAttemptAdmin.get_querysetmark_as_suspiciousexport_failed_attemptsc              
   C   s<   |j ddd }| |tdt| dd|  dS )z
        Custom action to mark IP addresses as suspicious.
        
        Args:
            request: HTTP request object
            queryset: Selected login attempts
        r   T)flatzMarked z IP addresses as suspicious: z, N)values_listdistinctmessage_userr=   rC   join)r0   r1   querysetZip_addressesr.   r.   r2   rN      s
   
z$LoginAttemptAdmin.mark_as_suspiciouszMark IP addresses as suspiciousc                 C   s0   |j dd}| }| |td| d dS )z
        Custom action to export failed login attempts.
        
        Args:
            request: HTTP request object
            queryset: Selected login attempts
        F)r   z	Exported z failed login attemptsN)filtercountrS   r=   )r0   r1   rU   Zfailed_attemptsrW   r.   r.   r2   rO      s   z(LoginAttemptAdmin.export_failed_attemptszExport failed login attempts)N)__name__
__module____qualname____doc__list_displayr   RelatedOnlyFieldListFilterlist_filtersearch_fieldsorderingdate_hierarchyreadonly_fieldsr=   	fieldsetslist_per_pager3   r6   r   short_descriptionadmin_order_fieldr   rI   actionsrN   rO   __classcell__r.   r.   rK   r2   r      sT    	"



r   c                       s  e Zd ZdZg dZddddejfgZg dZdgZ	dZ
g d	Zed
ddifedddifedddifeddddffZdZdd Zede_de_dd Zede_dd Zde_ed e_ fd!d"Zd#d$gZd%d& Zed'e_d(d) Zed*e_  ZS )+PasswordResetTokenAdminz
    Admin configuration for PasswordResetToken model.
    
    Provides management interface for password reset tokens
    with security monitoring capabilities.
    )r   token_shortis_used
is_expiredrequested_ipused_ipr   
expires_atrk   r   ro   r   )r   r   r   tokenrm   rn   r   )
rp   ro   rk   used_atrm   rn   r   r    r!   r"   zToken Informationr#   )r   rp   rk   rq   
Expirationro   IP Tracking)rm   rn   r*   r+   r&   r(   r,   c                 C   "   t d|jjgd}td||jjS )z
        Display a link to the user.
        
        Args:
            obj: PasswordResetToken instance
            
        Returns:
            str: HTML link to user
        r7   r8   r:   Nr   r   r;   r   r<   r>   r.   r.   r2   r   ;     
z!PasswordResetTokenAdmin.user_linkr@   r   c                 C   "   |j dd  d|j dd  S )z
        Display a shortened version of the token.
        
        Args:
            obj: PasswordResetToken instance
            
        Returns:
            str: Shortened token string
        N   rA   rp   rD   r.   r.   r2   rj   J     "
z#PasswordResetTokenAdmin.token_shortTokenc                 C      t  |jkS )z
        Check if the token is expired.
        
        Args:
            obj: PasswordResetToken instance
            
        Returns:
            bool: True if token is expired
        Nr	   nowro   rD   r.   r.   r2   rl   W     
z"PasswordResetTokenAdmin.is_expiredT
Is Expiredc                    rE   rF   rG   r/   rK   r.   r2   rI   e  rM   z$PasswordResetTokenAdmin.get_querysetcleanup_expired_tokensinvalidate_tokensc                 C   $   t  }| |td| d dS )z
        Custom action to clean up expired tokens.
        
        Args:
            request: HTTP request object
            queryset: Selected tokens
        Cleaned up z expired tokensN)r   cleanup_expiredrS   r=   r0   r1   rU   Zexpired_countr.   r.   r2   r   t  
   z.PasswordResetTokenAdmin.cleanup_expired_tokenszClean up expired tokensc                 C   s6   |j ddjdt d}| |td| d dS )z
        Custom action to invalidate selected tokens.
        
        Args:
            request: HTTP request object
            queryset: Selected tokens
        F)rk   T)rk   rq   Invalidated z tokensN)rV   updater	   r   rS   r=   r0   r1   rU   rW   r.   r.   r2   r     s   z)PasswordResetTokenAdmin.invalidate_tokenszInvalidate selected tokens)rX   rY   rZ   r[   r\   r   r]   r^   r_   r`   ra   rb   r=   rc   rd   r   re   rf   rj   rl   booleanrI   rg   r   r   rh   r.   r.   rK   r2   ri      sR    
 



ri   c                       s   e Zd ZdZg dZddddejfgZg dZdgZ	dZ
g d	Zed
ddifedddifedddifeddddffZdZdd Zede_de_dd Zede_dd Zde_ed e_ fd!d"Z  ZS )#EmailVerificationTokenAdminz
    Admin configuration for EmailVerificationToken model.
    
    Provides management interface for email verification tokens.
    )r   r<   rj   rk   rl   verified_ipr   ro   rk   r   ro   r   )r   r   r   r<   rp   r   r   )	rp   ro   rk   rq   r   r   r    r!   r"   zVerification Informationr#   )r   r<   rp   rk   rq   rr   rs   rt   )r   r*   r+   r&   r(   r,   c                 C   ru   )z
        Display a link to the user.
        
        Args:
            obj: EmailVerificationToken instance
            
        Returns:
            str: HTML link to user
        r7   r8   r:   Nrv   r>   r.   r.   r2   r     rw   z%EmailVerificationTokenAdmin.user_linkr@   r   c                 C   rx   )z
        Display a shortened version of the token.
        
        Args:
            obj: EmailVerificationToken instance
            
        Returns:
            str: Shortened token string
        Nry   rA   rz   r{   rD   r.   r.   r2   rj     r|   z'EmailVerificationTokenAdmin.token_shortr}   c                 C   r~   )z
        Check if the token is expired.
        
        Args:
            obj: EmailVerificationToken instance
            
        Returns:
            bool: True if token is expired
        Nr   rD   r.   r.   r2   rl     r   z&EmailVerificationTokenAdmin.is_expiredTr   c                    rE   rF   rG   r/   rK   r.   r2   rI     rM   z(EmailVerificationTokenAdmin.get_queryset)rX   rY   rZ   r[   r\   r   r]   r^   r_   r`   ra   rb   r=   rc   rd   r   re   rf   rj   rl   r   rI   rh   r.   r.   rK   r2   r     sH    
	 


r   c                	       s  e Zd ZdZg dZddddddd	d
ejfgZg dZdgZ	dZ
g dZedddifedddifeddddfeddddffZdZdd Zede_de_dd Zed e_d!d" Zd#e_ed$e_ fd%d&Zd'd(gZd)d* Zed+e_d,d- Zed.e_  ZS )/UserSessionAdminz
    Admin configuration for UserSession model.
    
    Provides management interface for user sessions with
    device and location tracking.
    )r   session_key_shortr   device_typebrowseroperating_system	is_activerl   last_activityr   r   r   r   r   r   r   r   ro   r   )
r   r   r   session_keyr   r   r   r   r   r   z-last_activity)r   r   r   r   r   r   r   ro   r   r   r   r    r!   r"   zSession Informationr#   )r   r   r   r   ro   zDevice Information)r   r   r   r   r   r$   r%   r&   r(   r*   r+   r,   c                 C   ru   )z
        Display a link to the user.
        
        Args:
            obj: UserSession instance
            
        Returns:
            str: HTML link to user
        r7   r8   r:   Nrv   r>   r.   r.   r2   r     rw   zUserSessionAdmin.user_linkr@   r   c                 C   rx   )z
        Display a shortened version of the session key.
        
        Args:
            obj: UserSession instance
            
        Returns:
            str: Shortened session key
        Nry   rA   rz   )r   rD   r.   r.   r2   r     r|   z"UserSessionAdmin.session_key_shortzSession Keyc                 C   s   |  S )z
        Check if the session is expired.
        
        Args:
            obj: UserSession instance
            
        Returns:
            bool: True if session is expired
        N)rl   rD   r.   r.   r2   rl     s   
zUserSessionAdmin.is_expiredTr   c                    rE   rF   rG   r/   rK   r.   r2   rI     rM   zUserSessionAdmin.get_querysetinvalidate_sessionscleanup_expired_sessionsc                 C   s0   |j ddjdd}| |td| d dS )z
        Custom action to invalidate selected sessions.
        
        Args:
            request: HTTP request object
            queryset: Selected sessions
        T)r   Fr   z	 sessionsN)rV   r   rS   r=   r   r.   r.   r2   r     s
   z$UserSessionAdmin.invalidate_sessionszInvalidate selected sessionsc                 C   r   )z
        Custom action to clean up expired sessions.
        
        Args:
            request: HTTP request object
            queryset: Selected sessions
        r   z expired sessionsN)r   r   rS   r=   r   r.   r.   r2   r     r   z)UserSessionAdmin.cleanup_expired_sessionszClean up expired sessions)rX   rY   rZ   r[   r\   r   r]   r^   r_   r`   ra   rb   r=   rc   rd   r   re   rf   r   rl   r   rI   rg   r   r   rh   r.   r.   rK   r2   r   )  s\    		&



r   N)r[   Zdjango.contribr   django.utils.translationr   r=   django.utils.htmlr   django.urlsr   django.utils.safestringr   django.db.modelsr   r   django.utilsr	   datetimer
   modelsr   r   r   r   register
ModelAdminr   ri   r   r   r.   r.   r.   r2   <module>   s*    ? 9 