o
    >dhv                     @   s  d Z ddlmZmZmZ ddlmZ ddl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mZmZmZmZmZmZm Z  ddl!m"Z"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.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z>m?Z? ddl@mAZAmBZB ddlCmDZD ddlEmFZF ddlGmHZH ddlIZIddlJZJddlKmLZLmMZMmNZN ddlOmPZPmQZQmRZRmSZSmTZT dd lUmVZVmWZWmXZX dd!lYmZZZm[Z[m\Z\ dd"l]m^Z^ e ZMeJ_e`ZaG d#d$ d$eZbG d%d& d&eeZcG d'd( d(eeZdG d)d* d*eeeZeG d+d, d,eeeZfG d-d. d.eeeZgee	d/d0d1d2d3 ZhG d4d5 d5eFZiG d6d7 d7eFZje>d8ge?eAeBgd9d: ZkG d;d< d<eZlG d=d> d>eeZmdS )?z
Accounts Views Module

This module contains views for user management, roles, and permissions
including user registration, profile management, role assignment,
and user administration.

Author: Senior Django Developer
Date: 2024
    )renderredirectget_object_or_404)get_user_model)login_requiredpermission_required)LoginRequiredMixinPermissionRequiredMixin)messages)	send_mail)settings)gettext_lazy)timezone)ViewTemplateViewFormViewListView
DetailView
CreateView
UpdateView
DeleteView)JsonResponseHttpResponseHttpResponseRedirectHttp404)reverse_lazyreverse)render_to_string)
strip_tags)QCountPrefetch)	Paginator)csrf_exempt)require_http_methods)method_decorator)UserCreationFormstatus)api_viewpermission_classes)IsAuthenticatedIsAdminUser)Response)APIView)	timedeltaN   )RoleUserProfile)UserRegistrationFormProfileFormUserUpdateFormRoleFormUserRoleAssignmentForm)UserSerializerProfileSerializerRoleSerializer)get_client_ipget_user_agent_infolog_security_event)EmailVerificationTokenc                       sP   e Zd ZdZdZeZedZ fddZ	 fddZ
 fdd	Zd
d Z  ZS )UserRegistrationViewz
    User registration view with email verification.
    
    Features:
    - User account creation
    - Email verification token generation
    - Welcome email sending
    - Security logging
    zaccounts/register.htmlzaccounts:registration_completec                    s*   |j jrtdS t j|g|R i |S )a'  
        Redirect authenticated users to dashboard.
        
        Args:
            request: HTTP request object
            *args: Variable length argument list
            **kwargs: Arbitrary keyword arguments
            
        Returns:
            HttpResponse: Response object
        zcore:dashboardN)useris_authenticatedr   superdispatchselfrequestargskwargs	__class__ GC:\Users\vibe-look\OneDrive\Desktop\Adtlas_V\src\apps\accounts\views.pyrD   _   s   zUserRegistrationView.dispatchc                    s.   t  jdi |}td|d< td|d< |S )
        Add additional context data to the template.
        
        Args:
            **kwargs: Arbitrary keyword arguments
            
        Returns:
            dict: Context data for template
        zCreate AccounttitlezJoin us today and get startedpage_descriptionNrL   rC   get_context_data_rF   rI   contextrJ   rL   rM   rR   p   s   
z%UserRegistrationView.get_context_datac                    s   |j dd}d|_d|_|   tjj|t| jd}| || t	d|t| j| jj
dd|jdd	 t| jtd
 t |S )z
        Handle valid form submission.
        
        Args:
            form: Valid registration form
            
        Returns:
            HttpResponse: Response object
        F)commitT)rA   requested_ipZuser_registrationHTTP_USER_AGENT )
user_agentemailrA   
ip_addressdetailszMAccount created successfully! Please check your email to verify your account.N)save	is_activeis_verifiedr?   objectscreater<   rG   send_verification_emailr>   METAgetr[   r
   successrS   rC   
form_valid)rF   formrA   verification_tokenrJ   rL   rM   rh      s,   zUserRegistrationView.form_validc                 C   sb   | j tdd|jid}td||ttdd|jd}t|}t	t
d|tj|jg|d	d
 dS )z
        Send email verification email to user.
        
        Args:
            user: User instance
            verification_token: EmailVerificationToken instance
        zauthentication:verify_emailtoken)rI   z'accounts/emails/email_verification.html	SITE_NAMEzOur Site)rA   verification_url	site_name
expires_atzVerify Your Email AddressF)subjectmessage
from_emailrecipient_listhtml_messagefail_silentlyN)rG   build_absolute_urir   rk   r   getattrr   ro   r   r   rS   DEFAULT_FROM_EMAILr[   )rF   rA   rj   rm   rt   plain_messagerL   rL   rM   rd      s,   	


z,UserRegistrationView.send_verification_email)__name__
__module____qualname____doc__template_namer4   
form_classr   success_urlrD   rR   rh   rd   __classcell__rL   rL   rJ   rM   r@   P   s    
,r@   c                       s6   e Zd ZdZeZdZdZd	ddZ fddZ	  Z
S )
ProfileViewz
    User profile view for displaying user information.
    
    Shows user details, profile information, and account statistics.
    zaccounts/profile.htmlZprofile_userNc                 C   sD   | j d}|r| jjjs| jjdstdtt|dS | jjS )z
        Get the user object to display.
        
        Args:
            queryset: Optional queryset to use
            
        Returns:
            User: User instance
        user_idaccounts.view_userz.You don't have permission to view this profileidN)	rI   rf   rG   rA   is_staffhas_permr   r   r2   )rF   querysetr   rL   rL   rM   
get_object   s   
zProfileView.get_objectc                    sj   t  jdi |}|  }td|d< || jjk|d< |j |d< |j|j	|j
 |j|jd|d< |S )	rN   zUser ProfilerO   Zis_own_profileZ
user_roles)Zmember_since
last_loginZtotal_rolesra   r`   Zprofile_statsNrL   )rC   rR   r   rS   rG   rA   rolesalldate_joinedr   countra   r`   )rF   rI   rU   rA   rJ   rL   rM   rR      s   

zProfileView.get_context_dataN)rz   r{   r|   r}   r2   modelr~   context_object_namer   rR   r   rL   rL   rJ   rM   r      s    
r   c                       sJ   e Zd ZdZeZeZdZdddZ	 fddZ
 fdd	Zd
d Z  ZS )ProfileUpdateViewz
    User profile update view for editing user information.
    
    Allows users to update their profile information and settings.
    zaccounts/profile_edit.htmlNc                 C   s   t t| jjdS )z
        Get the user profile object to edit.
        
        Args:
            queryset: Optional queryset to use
            
        Returns:
            Profile: Profile instance
        )rA   N)r   r3   rG   rA   )rF   r   rL   rL   rM   r     s   
zProfileUpdateView.get_objectc                    s4   t  jdi |}td|d< t| jjd|d< |S )rN   zEdit ProfilerO   instance	user_formNrL   )rC   rR   rS   r6   rG   rA   rT   rJ   rL   rM   rR   &  s   
z"ProfileUpdateView.get_context_datac                    sf   t | jj| jjd}| r|  td| jjt| jdt|j	id t
| jtd t |S )z
        Handle valid form submission.
        
        Args:
            form: Valid profile form
            
        Returns:
            HttpResponse: Response object
        r   Zprofile_updateZupdated_fieldsr\   zProfile updated successfully!N)r6   rG   POSTrA   is_validr_   r>   r<   listchanged_datar
   rg   rS   rC   rh   )rF   ri   r   rJ   rL   rM   rh   5  s$   
	zProfileUpdateView.form_validc                 C   s   t dS )z
        Get the URL to redirect to after successful form submission.
        
        Returns:
            str: Success URL
        zaccounts:profileN)r   rF   rL   rL   rM   get_success_urlY  s   z!ProfileUpdateView.get_success_urlr   )rz   r{   r|   r}   r3   r   r5   r   r~   r   rR   rh   r   r   rL   rL   rJ   rM   r     s    
$r   c                       s<   e Zd ZdZeZdZdZdZdZ	dd Z
 fdd	Z  ZS )
UserListViewzw
    User list view for administrators.
    
    Displays a paginated list of all users with search and filtering.
    zaccounts/user_list.htmlusers   r   c                 C   s   t jdd}| jjdd}|r*|t|dt|dB t|dB t|dB }| jjd	d}|r:|j|d
}| jjdd}|dkrM|jdd}n |dkrX|jdd}n|dkrc|jdd}n
|dkrm|jdd}| jjdd}|dv r~|	|}|S )z~
        Get the queryset of users to display.
        
        Returns:
            QuerySet: Filtered user queryset
        profiler   searchrY   Zemail__icontainsZfirst_name__icontainsZlast_name__icontains)Z profile__phone_number__icontainsrole)Z	roles__idr(   activeTr`   inactiveFverifiedra   Z
unverifiedorder_by-date_joined)
r[   z-email
first_namez-first_name	last_namez
-last_namer   r   r   z-last_loginN)
r2   rb   select_relatedprefetch_relatedrG   GETrf   filterr   r   )rF   r   search_queryZrole_filterZstatus_filterr   rL   rL   rM   get_querysetp  s8   
zUserListView.get_querysetc                    s   t  jdi |}td|d< | jjdd|d< | jjdd|d< | jjdd|d	< | jjd
d|d< tj |d< t	j
 t	jjdd
 t	jjdd
 t	jjdd
 d|d< |S )rN   zUser ManagementrO   r   rY   r   r   Zcurrent_roler(   Zcurrent_statusr   r   Zcurrent_orderZavailable_rolesTr   r   r   )total_usersactive_usersverified_usersstaff_usersZ
user_statsNrL   )rC   rR   rS   rG   r   rf   r1   rb   r   r2   r   r   rT   rJ   rL   rM   rR     s   

zUserListView.get_context_data)rz   r{   r|   r}   r2   r   r~   r   paginate_byr   r   rR   r   rL   rL   rJ   rM   r   c  s    ,r   c                       s8   e Zd ZdZeZdZdZdZdd Z	 fddZ
  ZS )	RoleManagementViewzl
    Role management view for administrators.
    
    Displays and manages user roles and permissions.
    zaccounts/role_management.htmlr   zaccounts.view_rolec                 C   s   t jjtdddS )z
        Get the queryset of roles to display.
        
        Returns:
            QuerySet: Role queryset with user counts
        r   )Z
user_countnameN)r1   rb   annotater    r   r   rL   rL   rM   r     s
   zRoleManagementView.get_querysetc                    sX   t  jd
i |}td|d< | jjd|d< | jjd|d< | jjd|d< |S )rN   zRole ManagementrO   zaccounts.add_roleZcan_add_rolezaccounts.change_roleZcan_change_rolezaccounts.delete_roleZcan_delete_roleNrL   )rC   rR   rS   rG   rA   r   rT   rJ   rL   rM   rR     s   
z#RoleManagementView.get_context_data)rz   r{   r|   r}   r1   r   r~   r   r   r   rR   r   rL   rL   rJ   rM   r     s    r   c                       sL   e Zd ZdZdZeZdZ fddZ fddZ	 fdd	Z
d
d Z  ZS )UserRoleAssignmentViewz|
    User role assignment view for administrators.
    
    Allows administrators to assign or remove roles from users.
    z"accounts/user_role_assignment.htmlaccounts.change_userc                    s,   t t|d d| _t j|g|R i |S )a%  
        Get the user object for role assignment.
        
        Args:
            request: HTTP request object
            *args: Variable length argument list
            **kwargs: Arbitrary keyword arguments
            
        Returns:
            HttpResponse: Response object
        r   r   N)r   r2   user_objrC   rD   rE   rJ   rL   rM   rD     s   zUserRoleAssignmentView.dispatchc                    s   t   }| j|d< |S )zk
        Add user instance to form kwargs.
        
        Returns:
            dict: Form kwargs
        rA   N)rC   get_form_kwargsr   )rF   rI   rJ   rL   rM   r     s   

z&UserRoleAssignmentView.get_form_kwargsc                    s<   t  jdi |}td|d< | j|d< | jj |d< |S )rN   zAssign RolesrO   target_usercurrent_rolesNrL   )rC   rR   rS   r   r   r   rT   rJ   rL   rM   rR     s
   

z'UserRoleAssignmentView.get_context_datac              	   C   s   |j d }t| jj }t|}|| }|| }| jj| |s$|rDtd| jjt| j| jj	| jj
dd |D dd |D dd t| jtd td	S )z
        Handle valid form submission.
        
        Args:
            form: Valid role assignment form
            
        Returns:
            HttpResponse: Response object
        r   Zrole_assignment_changec                 S      g | ]}|j qS rL   r   .0r   rL   rL   rM   
<listcomp>8      z5UserRoleAssignmentView.form_valid.<locals>.<listcomp>c                 S   r   rL   r   r   rL   rL   rM   r   9  r   )target_user_idtarget_user_emailadded_rolesremoved_rolesr\   z User roles updated successfully!accounts:user_listN)cleaned_datasetr   r   r   r>   rG   rA   r<   r   r[   r
   rg   rS   r   )rF   ri   Zselected_rolesr   Z	new_rolesr   r   rL   rL   rM   rh     s,   
z!UserRoleAssignmentView.form_valid)rz   r{   r|   r}   r~   r8   r   r   rD   r   rR   rh   r   rL   rL   rJ   rM   r     s    r   r   T)raise_exceptionc              	   C   s   t t|d}|| jkrt| td tdS |j |_|jdgd t	d| jt
| |j|j|jr3dndd	d
 |jr@tdntd}t| td|j d| d tdS )z
    Toggle user active status (activate/deactivate).
    
    Args:
        request: HTTP request object
        user_id: ID of the user to toggle
        
    Returns:
        HttpResponse: Response object
    r   z'You cannot deactivate your own account.r   r`   )update_fieldsZuser_status_changer   r   )r   r   Z
new_statusr\   	activatedZdeactivatedzUser z
 has been .N)r   r2   rA   r
   errorrS   r   r`   r_   r>   r<   r   r[   rg   )rG   r   rA   status_textrL   rL   rM   toggle_user_statusE  s0   

r   c                   @   s    e Zd ZdZeegZdd ZdS )UserListAPIViewz^
    API view for listing users.
    
    Provides REST API endpoint for user management.
    c           	      C   s   t jdd}|jdd}|r$|t|dt|dB t|dB }tt	|jdd	d
}t	|jdd}t
||}||}t|jdd}t|j|j|j|j| | ddS )z
        Get list of users.
        
        Args:
            request: HTTP request object
            
        Returns:
            Response: API response with user list
        r   r   r   rY   r   r   r   	page_sizer   d   pager0   T)many)Zcurrent_pageZtotal_pagestotal_counthas_nexthas_previous)r   
paginationN)r2   rb   r   r   r   rf   r   r   minintr"   get_pager9   object_listr-   datanumber	num_pagesr   r   r   )	rF   rG   r   r   r   r   	paginatorpage_obj
serializerrL   rL   rM   rf     s0   


zUserListAPIView.getN)rz   r{   r|   r}   r+   r,   r*   rf   rL   rL   rL   rM   r   x  s    r   c                   @   s   e Zd ZdZegZdd ZdS )UserDetailAPIViewzh
    API view for user details.
    
    Provides REST API endpoint for individual user management.
    c                 C   s|   ||j jkr|j jstdditjdS ztjd	dj
|d}t|}t|jW S  tjy=   tdditjd Y S w )	z
        Get user details.
        
        Args:
            request: HTTP request object
            user_id: ID of the user to retrieve
            
        Returns:
            Response: API response with user details
        r   zPermission deniedr'   r   r   r   zUser not foundN)rA   r   r   r-   r(   HTTP_403_FORBIDDENr2   rb   r   r   rf   r9   r   DoesNotExistHTTP_404_NOT_FOUND)rF   rG   r   rA   r   rL   rL   rM   rf     s   
zUserDetailAPIView.getN)rz   r{   r|   r}   r+   r*   rf   rL   rL   rL   rM   r     s    r   r   c              	   C   sl   t j t jjdd t jjdd t jjdd t jjt tdd d tj d}t|S )
z
    API endpoint for user statistics.
    
    Args:
        request: HTTP request object
        
    Returns:
        Response: API response with user statistics
    Tr   r   r      )days)Zdate_joined__gte)r   r   r   r   Zrecent_registrationsZroles_countN)	r2   rb   r   r   r   nowr/   r1   r-   )rG   statsrL   rL   rM   api_user_stats  s   r   c                       $   e Zd ZdZdZ fddZ  ZS )RegistrationCompleteViewz2
    Registration complete confirmation view.
    z#accounts/registration_complete.htmlc                    s"   t  jdi |}td|d< |S )rN   zRegistration CompleterO   NrL   rQ   rT   rJ   rL   rM   rR     s   
z)RegistrationCompleteView.get_context_datarz   r{   r|   r}   r~   rR   r   rL   rL   rJ   rM   r         r   c                       r   )AccountSettingsViewz5
    Account settings view for user preferences.
    zaccounts/settings.htmlc                    s0   t  jdi |}td|d< | jjj|d< |S )rN   zAccount SettingsrO   Zuser_profileNrL   )rC   rR   rS   rG   rA   r   rT   rJ   rL   rM   rR   	  s   
z$AccountSettingsView.get_context_datar   rL   rL   rJ   rM   r     r   r   )nr}   django.shortcutsr   r   r   django.contrib.authr   django.contrib.auth.decoratorsr   r   django.contrib.auth.mixinsr   r	   django.contribr
   django.core.mailr   django.confr   django.utils.translationr   rS   django.utilsr   django.views.genericr   r   r   r   r   r   r   r   django.httpr   r   r   r   django.urlsr   r   django.template.loaderr   django.utils.htmlr   django.db.modelsr   r    r!   django.core.paginatorr"   django.views.decorators.csrfr#   django.views.decorators.httpr$   django.utils.decoratorsr%   django.contrib.auth.formsr&   rest_frameworkr(   rest_framework.decoratorsr)   r*   Zrest_framework.permissionsr+   r,   rest_framework.responser-   rest_framework.viewsr.   datetimer/   jsonloggingmodelsr1   r2   r3   formsr4   r5   r6   r7   r8   serializersr9   r:   r;   Zapps.authentication.utilsr<   r=   r>   Zapps.authentication.modelsr?   	getLoggerrz   loggerr@   r   r   r   r   r   r   r   r   r   r   r   rL   rL   rL   rM   <module>   sj   (	
 =TV)c
14&
