
    v=i.                     x   d dl mZmZmZ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Zd dlZd dlZd dlmZ  ej(                  e      Z e       Zd	Zd
ZdedededefdZdedefdZd Z ej@                  ddg      d        Z! ej@                  dddg      d        Z" ej@                  ddg      d        Z# ej@                  ddg      d        Z$ ej@                  ddg      d        Z% ej@                  d d!g      ed"               Z& ej@                  d#d!g      ed$               Z'y)%    )	Blueprintredirectrequestjsonify)MeliAuthService)SessionLocal)
OAuthToken)datetime	timedelta)api_bpNwrapsz#hyper-ai-secret-key-2025-gWh28dGcMp   user_idemailrolereturnc                     | ||t        j                         t        t              z   t        j                         d}t	        j
                  |t        d      S )N)hours)r   r   r   expiatHS256)	algorithm)r
   utcnowr   JWT_EXPIRATION_HOURSjwtencode
JWT_SECRET)r   r   r   payloads       D/var/www/hypershopcomercio.com.br/hyper-ai/app/api/endpoints/auth.pygenerate_tokenr!      sF     93G#HH G ::gzW==    tokenc                 L    	 t        j                  | t        dg      S #  Y y xY w)Nr   )
algorithms)r   decoder   )r#   s    r    verify_tokenr'       s&    zz%	BBs    #c                 .     t                fd       }|S )Nc                     d }dt         j                  v r8t         j                  d   }|j                  d      r|j                  d      d   }|st	        ddd      dfS t        |      }|st	        dd	d      dfS |j                  d
      t         _        |j                  d      t         _        |j                  d      t         _	         | i |S )NAuthorizationBearer     FzToken missingsuccesserror  zInvalid tokenr   r   r   )
r   headers
startswithsplitr   r'   getr   
user_email	user_role)argskwargsr#   auth_headerr   fs        r    	decoratedzrequire_auth.<locals>.decorated(   s    goo-!///:K%%i0#))#.q1uGH#MMu%uGH#MM!++i0$[[1#KK/$!&!!r"   r   )r;   r<   s   ` r    require_authr=   '   s!    
1X" "$ r"   z/auth/mlGET)methodsc                  @    t         j                         } t        |       S )z1Generates URL and redirects to Mercado Livre Auth)auth_serviceget_auth_urlr   )urls    r    rB   rB   >   s     
#
#
%CC=r"   z/auth/ml/callbackPOSTc                     t         j                  d       t        j                  dk(  rt        j                  j                  d      } | syt         j                  d| dd  d       	 t        j                  |       }t         j                  d	|j                  d
              t        j                  |       t         j                  d       yt        j                  }t         j                  d|        |r|j                  d      nd} | s$t         j                  d       t        ddi      dfS t         j                  d| dd  d       	 t         j                  d       t        j                  |       }t         j                  d	|j                  d
              t         j                  d       t        j                  |       t         j                  d       t        ddd      S # t        $ r5}t         j                  d| d       dt        |       ddfcY d}~S d}~ww xY w# t        $ r<}t         j                  d| d       t        dt        |      i      dfcY d}~S d}~ww xY w)zDHandles callback from ML (GET redirect) or frontend (POST with code)z=== ML CALLBACK RECEIVED ===r>   code)u:   <h1>Erro</h1><p>Código não recebido do Mercado Livre</p>  zGET callback - Code received: N   z...z$Token exchange successful. User ID: r   zTokens saved successfully!u  
            <!DOCTYPE html>
            <html>
            <head>
                <title>Autenticação Concluída</title>
                <style>
                    body { font-family: system-ui; background: linear-gradient(135deg, #1a1c2e, #12141e); color: white; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; }
                    .card { background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 16px; padding: 48px; text-align: center; max-width: 400px; }
                    .icon { width: 64px; height: 64px; background: linear-gradient(135deg, #10b981, #059669); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 24px; font-size: 32px; }
                    h1 { margin: 0 0 8px; font-size: 24px; }
                    p { color: #94a3b8; margin: 0 0 24px; }
                    a { background: linear-gradient(135deg, #6366f1, #8b5cf6); color: white; text-decoration: none; padding: 12px 32px; border-radius: 8px; font-weight: 600; display: inline-block; }
                </style>
            </head>
            <body>
                <div class="card">
                    <div class="icon">✓</div>
                    <h1>Autenticação Concluída!</h1>
                    <p>Sua conta do Mercado Livre foi conectada com sucesso.</p>
                    <a href="/integracoes">Voltar ao Sistema</a>
                </div>
            </body>
            </html>
            zCallback error: T)exc_infoz<h1>Erro</h1><p>z</p>  zPOST callback - Request data: zNo code in requestr0   zNo code providedrG   zCode received: zExchanging code for tokens...zSaving tokens to database...zAuthentication successful)messager/   )loggerinfor   methodr8   r5   rA   exchange_code_for_tokensave_tokens	Exceptionr0   strjsonr   )rF   
token_dataedatas       r    handle_callbackrW   D   s    KK./ ~~||'T4T#2YKsCD"	8%==dCJKK>z~~i?X>YZ[$$Z0KK45: <<D
KK078#488FD)*!345s::
KK/$s)C01/34!99$?
::>>);T:UVW23  ,01#>4PQQ1  	8LL+A3/$L?%c!fXT2C77	82  /'s+d;Q()3../s>   (A&G- BH. -	H+6*H& H+&H+.	I371I.(I3.I3z/auth/ml/statusc                     t               } 	 | j                  t              j                  d      j	                         }|st        ddd      | j                          S d}t        j                         }|j                  }|r%|j                  r|j                  d      }||k  rd}t        | |j                  xs |j                  |r|j                         nd|d	      | j                          S # | j                          w xY w)
zReturns ML connection statusmercadolivre)providerFzNot connected)	connectedrK   N)tzinfoT)r[   	seller_id
expires_at
is_expired)r   queryr	   	filter_byfirstr   closer
   r   r^   r\   replacer]   r   	isoformat)dbr#   r_   now_ts
expires_tss        r    get_auth_statusri      s     
B$...GMMO"* , 	
# 
"%%
  '//t/<
F"!
'9EMM4>*..0D$	
  	

s   AC3 BC3 3Dz/auth/loginc            	      H   ddl m}  t               }	 t        j                         }|j                  dd      j                         j                         }|j                  dd      }|r|s t        ddd      d	f|j                          S |j                  |       j                  | j                  |k(        j                         }|r|j                  |      s t        dd
d      df|j                          S |j                  s t        ddd      df|j                          S t!        j"                         |_        |j'                          t)        |j*                  |j                  |j,                        }t        d||j*                  |j                  |j.                  |j,                  ddd      }dt        j0                  v}|j3                  d|d|dd       ||j                          S # t4        $ r}	t7        |	      }
d|
v sd|
v r=t8        j;                  d|
        t        ddd      dfcY d}	~	|j                          S t8        j=                  d|
        t        d|
d      dfcY d}	~	|j                          S d}	~	ww xY w# |j                          w xY w)zUser login endpointr   Userr    passwordFu   Email e senha obrigatóriosr.   rG   u   Credenciais inválidasr1   u   Usuário desativadoTidr   namer   )r#   userr/   rV   	localhost
auth_tokenLaxiQ )keyvaluehttponlysecuresamesitemax_ageOperationalErrorzAccess deniedzDATABASE CONNECTION ERROR: u@   Erro de conexão com o banco de dados. Verifique as credenciais.i  NzLogin error: rJ   )app.models.userrl   r   r   get_jsonr5   striplowerr   rc   r`   filterr   rb   verify_password	is_activer
   r   
last_logincommitr!   rp   r   rq   host
set_cookierQ   rR   rL   criticalr0   )rl   rf   rV   r   rn   rr   r#   responseis_productionrU   	error_msgs              r    loginr      s^    %	B8!"%++-33588J+Hu7TUVX[[d 	
a xx~$$TZZ5%89??A4//9u7OPQSVVZ 	
W ~~u7LMNPSST 	
Q #//+
		tww

DII>''!ZZ II II	
  $7<<7  	 	
  	
  DF	*o.JOO9)EFu7yz{  ~A  A  A
 	
 	}YK0159=>CC

D 	
sV   A'G1 
AG1 8G1 $B<G1 1	J::J4J5J 
'J1J2J JJ J!z/auth/verifyc            	      x   d} dt         j                  v r8t         j                  d   }|j                  d      r|j                  d      d   } | st	        ddd      dfS t        |       }|st	        ddd      dfS t	        d	d	|j                  d
      |j                  d      |j                  d      dd      S )zVerify if token is validNr*   r+   r,   r-   F)r/   validr1   Tr   r   r   )rp   r   r   )r/   r   rr   )r   r2   r3   r4   r   r'   r5   )r#   r:   r   s      r    verify_authr      s     E'//)ooo6!!),%%c*1-E559:C??5!G559:C??++i([[)KK'
  r"   z/auth/profilePUTc                  b   ddl m}  t               }	 t        j                         }|j                  dd      j                         }|s t        ddd      df|j                          S |j                  |       j                  | j                  t        j                  k(        j                         }|s t        dd	d      d
f|j                          S ||_        |j                          t        d|j                  |j                   |j                  |j"                  dd      |j                          S # t$        $ r[}|j'                          t(        j+                  d|        t        dt-        |      d      dfcY d}~|j                          S d}~ww xY w# |j                          w xY w)zUpdate user profile (name)r   rk   rq   rm   Fu   Nome não pode estar vazior.   rG      Usuário não encontrado  Tro   rs   zProfile update error: rJ   N)r~   rl   r   r   r   r5   r   r   rc   r`   r   rp   r   rb   rq   r   r   r   rQ   rollbackrL   r0   rR   )rl   rf   rV   rq   rr   rU   s         r    update_profiler     s[    %	B!xx#))+u7STUWZZ0 	
- xx~$$TWW%?@FFHu7QRSUXX( 	
% 	
		gg					
  	
  A
-aS1253q6:;S@@

A
 	
s?   AD5 (AD5 AD5 5	F>A F>F?F FF F.z/auth/passwordc                     ddl m}  t               }	 t        j                         }|j                  dd      }|j                  dd      }|r|s t        ddd      d	f|j                          S t        |      d
k  r t        ddd      d	f|j                          S |j                  |       j                  | j                  t        j                  k(        j                         }|s t        ddd      df|j                          S |j                  |      s t        ddd      df|j                          S | j                  |      |_        |j#                          t        ddd      |j                          S # t$        $ r[}|j'                          t(        j+                  d|        t        dt-        |      d      dfcY d}~|j                          S d}~ww xY w# |j                          w xY w)zChange user passwordr   rk   current_passwordrm   new_passwordFzPreencha todos os camposr.   rG      z-A nova senha deve ter pelo menos 6 caracteresr   r   zSenha atual incorretar1   TzSenha alterada com sucesso)r/   rK   zPassword change error: rJ   N)r~   rl   r   r   r   r5   r   rc   lenr`   r   rp   r   rb   r   hash_passwordpassword_hashr   rQ   r   rL   r0   rR   )rl   rf   rV   r   r   rr   rU   s          r    change_passwordr   4  s    %	B!88$6;xx3|u7QRSUXX0 	
- |q u7fghjmm* 	
' xx~$$TWW%?@FFHu7QRSUXX" 	
 ##$45u7NOPRUU 	
 "//=
		44PQR 	
  A
.qc2353q6:;S@@

A
 	
sJ   AE< .E< AE<  E< 83E< <	G A GG G# G  G# #G5)(flaskr   r   r   r   app.services.meli_authr   app.core.databaser   app.models.oauth_tokenr	   r
   r   app.apir   r   hashliblogging	functoolsr   	getLogger__name__rL   rA   r   r   intrR   r!   dictr'   r=   routerB   rW   ri   r   r   r   r    r"   r    <module>r      s   7 7 2 * - (  
   			8	$  3
 >C > >3 >3 >  . j5'* +
 !E6?;G/ <G/R %1 2B mfX.= /=@ nug. /6 ow/"  0"J 0#  1#r"   