
    P1i,                         d Z ddlmZ 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Z e       Z G d
 de      Zy	)z
Management command to test the systematic activity tracking system.

This command verifies that the signal-based activity tracking works for
both web (session) and API (JWT) authentication methods.
    )BaseCommand)get_user_modelloginlogout)ClientRequestFactory)cache)RefreshToken)	APIClient)fire_jwt_authenticated_signalNc                   @    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zy
)Commandz3Test the systematic activity tracking functionalityc                 ,    |j                  ddd       y )Nz--comprehensive
store_truez5Run comprehensive tests including signal verification)actionhelp)add_argument)selfparsers     \/home/cursorai/projects/iching/main/management/commands/test_systematic_activity_tracking.pyadd_argumentszCommand.add_arguments   s    H 	 	
    c                 f   | j                   j                  | j                  j                  d             t        j
                  j                  dddd      \  }}|rJ|j                  d       |j                          | j                   j                  d|j                          n(| j                   j                  d	|j                          | j                  |       | j                   j                  d
       | j                   j                  | j                  j                  d             | j                   j                  d       | j                  |       | j                   j                  d
       | j                   j                  | j                  j                  d             | j                   j                  d       | j                  |       | j                   j                  d
       | j                   j                  | j                  j                  d             | j                   j                  d       | j                  |       |d   r{| j                   j                  d
       | j                   j                  | j                  j                  d             | j                   j                  d       | j                  |       | j                   j                  d
       | j                   j                  | j                  j                  d             | j                   j                  d       |j!                          | j                   j                  d|j"                          |j"                  rP| j                   j                  | j                  j                  d             | j                   j                  d       n4| j                   j                  | j                  j%                  d             |r,|j'                          | j                   j                  d       y y )Nz'Testing systematic activity tracking...
1234567890zsystemtest@example.comT)email	is_active)phonedefaultstestpass123zCreated test user: zUsing existing test user: z=
============================================================z&Test 1: Signal-Based Activity Trackingz<============================================================z"Test 2: JWT Authentication Backendz"Test 3: Web Session Authenticationcomprehensivez!Test 4: Comprehensive API Testingz)Systematic Activity Tracking Test SummaryzFinal user activity state: u#   ✅ SYSTEMATIC TRACKING IS WORKING!z8All authentication methods automatically track activity.u4   ❌ No activity tracked - check signal configurationzCleaned up test user)stdoutwritestyleSUCCESSUserobjectsget_or_createset_passwordsaver   _clear_user_activityWARNING_test_django_signals _test_jwt_authentication_backend _test_web_session_authentication_test_comprehensive_apirefresh_from_dblast_active_dateERRORdelete)r   argsoptions	test_usercreateds        r   handlezCommand.handle   s   $**,,-VWX "\\771! 8 
	7 ""=1NNKK 3IOO3DEFKK :9??:KLM 	!!), 	-($**,,-UVW&!!!), 	-($**,,-QRS&!--i8 	-($**,,-QRS&!--i8?#KKm,KKdjj001TUVKKf%((3 	-($**,,-XYZ&!!!#7	8R8R7STU%%KKdjj001VWXKKXYKKdjj../efg KK45 r   c                    t         j                  j                  |j                        j	                  d       t        j                          |j                          | j                  j                  d|j                          y)z0Clear user activity and cache for clean testing.)pkN)r1   zCleared activity for user )
r%   r&   filterr:   updater	   clearr0   r!   r"   )r   users     r   r*   zCommand._clear_user_activityc   s\    tww'...E6twwi@Ar   c                 j   ddl m}m} ddlm}  |       }|j                  d      }||_        | j                  |       | j                  j                  d       |j                  t        ||       |j                          |j                  r5| j                  j                  | j                  j                  d             n4| j                  j                  | j                  j!                  d             | j                  j                  d	       | j                  |       t#        ||       |j                          |j                  r5| j                  j                  | j                  j                  d
             y| j                  j                  | j                  j!                  d             y)z.Test Django's built-in authentication signals.r   )user_logged_inuser_logged_outr   /z Testing user_logged_in signal...)senderrequestr>   u(   ✅ user_logged_in signal tracking worksu)   ❌ user_logged_in signal tracking failedz*Testing custom jwt_authenticated signal...u+   ✅ jwt_authenticated signal tracking worksu,   ❌ jwt_authenticated signal tracking failedN)django.contrib.auth.signalsr@   rA   django.testr   getr>   r*   r!   r"   sendr%   r0   r1   r#   r$   r2   r   )r   r>   r@   rA   r   factoryrE   s          r   r,   zCommand._test_django_signalsj   s>   O. "++c" 	!!$' 	<=4tD  KKdjj001[\]KKdjj../Z[\ 	FG!!$'%dG4  KKdjj001^_`KKdjj../]^_r   c                    	 ddl m} ddlm}  |       } |       }t	        j
                  |      }t        |j                        }|j                  d      }d| |j                  d<   | j                  |       | j                  j                  d       |j                  |      }	|	r|	\  }
}| j                  j                  d|
j                          |j                          |j                   r5| j                  j                  | j"                  j%                  d	             y| j                  j                  | j"                  j'                  d
             y| j                  j                  | j"                  j'                  d             y# t(        $ rA}| j                  j                  | j"                  j'                  d|              Y d}~yd}~ww xY w)z+Test the custom JWT authentication backend.r   )!ActivityTrackingJWTAuthenticationrB   z
/api/test/Bearer HTTP_AUTHORIZATIONz%Testing JWT authentication backend...z(JWT authentication successful for user: u'   ✅ JWT backend activity tracking worksu(   ❌ JWT backend activity tracking failedu   ❌ JWT authentication failedu   ❌ JWT backend test error: N)main.authenticationrL   rG   r   r
   for_userstraccess_tokenrH   METAr*   r!   r"   authenticater:   r0   r1   r#   r$   r2   	Exception)r   r>   rL   r   rJ   auth_backendrefreshrR   rE   resultauthenticated_usertokenes                r   r-   z(Command._test_jwt_authentication_backend   s   $	TM2$&G<>L #++D1Gw334L kk,/G3:<.1IGLL-. %%d+ KKEF!..w7F,2)"E!!$LM_MbMbLc"de $$&((KK%%djj&8&89b&cdKK%%djj&6&67a&bc!!$**"2"23R"ST 	TKKdjj..1MaS/QRSS	Ts$   D#F &4F 4F 	G7GGc                 V   | j                  |       t               }| j                  j                  d       	 |j	                  dd      }|r| j                  j                  d       |j                          |j                  r5| j                  j                  | j                  j                  d             n4| j                  j                  | j                  j                  d             |j                  d      }|j                  d	v rQ| j                  j                  d
       y| j                  j                  | j                  j                  d             yy# t        $ rA}| j                  j                  | j                  j                  d|              Y d}~yd}~ww xY w)z&Test web session-based authentication.zTesting web session login...r   r   r   passwordzWeb login successfulu'   ✅ Web session activity tracking worksu*   ⚠️ Web login signal may not have firedrC   )   i.  zWeb view access successfulu   ❌ Web login failedu   ❌ Web session test error: N)r*   r   r!   r"   r   r0   r1   r#   r$   r+   rH   status_coder2   rU   )r   r>   clientlogin_successresponser[   s         r   r.   z(Command._test_web_session_authentication   sN   !!$' 89	T"LL|mLTM!!"89 $$&((KK%%djj&8&89b&cdKK%%djj&8&89e&fg "::c?'':5KK%%&BC !!$**"2"23I"JK	 6  	TKKdjj..1MaS/QRSS	Ts   C/E (4E 	F('7F##F(c                 f   t               }| j                  j                  d       	 ddd}| j                  |       |j	                  d|d      }| j                  j                  d|j
                          |j
                  d	k(  r(	 t        j                  |j                  j                               }d
|v r|d
   }| j                  j                  d       |j                  d|        |j                  d      }| j                  j                  d|j
                          |j                          |j                  r5| j                  j                  | j                  j                  d             n5| j                  j                  | j                  j!                  d             yyyy# t        j"                  $ r | j                  j                  d       Y yw xY w# t$        $ rA}| j                  j                  | j                  j!                  d|              Y d}~yd}~ww xY w)z%Test comprehensive API functionality.zTesting API login endpoint...r   r   r]   z/api/user/login/json)formatzAPI login response: r_   accessz$API login successful, token receivedrM   )rN   z/api/user/profile/zAuthenticated API request: u.   ✅ API authentication activity tracking worksu/   ❌ API authentication activity tracking failedz!API login response not valid JSONu   ❌ API test error: N)r   r!   r"   r*   postr`   re   loadscontentdecodecredentialsrH   r0   r1   r#   r$   r2   JSONDecodeErrorrU   )	r   r>   
api_client
login_datarc   response_datarZ   api_responser[   s	            r   r/   zCommand._test_comprehensive_api   s   [
 	9:#	L%)J
 %%d+!'9:fUHKK 4X5I5I4JKL##s*K$(JJx/?/?/F/F/H$IM=0 -h 7))*PQ #..GE7BS.T'1~~6J'K)),GH`H`Ga*bc ,,.00 KK--djj.@.@Aq.rs KK--djj.>.>?p.qr t 1 +( ++ KKK%%&IJK  	LKKdjj..1EaS/IJKK	Ls7   A"G& 
D$F2 2.G# G& "G##G& &	H0/7H++H0c                 2   ddl m} ddlm} | j                  j                  d       t        ||      r5| j                  j                  | j                  j                  d             n4| j                  j                  | j                  j                  d             ddl
m} |j                  t              }|r)| j                  j                  d	t        |       d
       y| j                  j                  | j                  j                  d             y)z)Check if signals are properly registered.r   )Signal)jwt_authenticatedzChecking signal registration...u#   ✅ Custom JWT signal is registeredu   ❌ Custom JWT signal not found)r@   )rD   u
   ✅ Found z$ receivers for user_logged_in signalu0   ❌ No receivers found for user_logged_in signalN)django.dispatchrs   main.signalsrt   r!   r"   
isinstancer#   r$   r2   rF   r@   _live_receiversr%   len)r   rs   rt   r@   	receiverss        r   _check_signal_registrationz"Command._check_signal_registration  s    *2;< '0KKdjj001VWXKKdjj../PQR 	?"22$2?	KK
3y>*::^_`KKdjj../abcr   N)__name__
__module____qualname__r   r   r8   r*   r,   r-   r.   r/   r{    r   r   r   r      s;    @D
C6JB `D&TP TD*LXdr   r   )__doc__django.core.management.baser   django.contrib.authr   r   r   rG   r   r   django.core.cacher	   rest_framework_simplejwt.tokensr
   rest_framework.testr   rv   r   re   r%   r   r   r   r   <module>r      s?    4 = = . # 8 ) 6 Bdk Bdr   