o
    ⾗h                     @   s   d Z ddlZddlZddlZddl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 ddlmZ eeZG d	d
 d
eZdedeeeef  fddZdedeeeef  fddZdefddZdedeeeef  fddZdS )z^
Google OAuth utilities for authentication.
Handles Google OAuth flow and token verification.
    N)OptionalDictAny)	urlencode)requests)id_token)GoogleAuthError)settingsc                   @   s   e Zd ZdZdS )GoogleOAuthErrorz)Custom exception for Google OAuth errors.N)__name__
__module____qualname____doc__ r   r   -/var/www/html/aiguide_backend/google_oauth.pyr
      s    r
   tokenreturnc              
   C   s  zLt | t tj}|d tjkrtd W dS |d t k r*td W dS |d |d |	dd	|	d
d	|	dd	|	dd	|	dddW S  t
yg } ztd|  W Y d}~dS d}~w ty } ztd|  W Y d}~dS d}~ww )z
    Verify Google ID token and return user information.
    
    Args:
        token: Google ID token
        
    Returns:
        User information from Google or None if verification fails
    audzToken audience mismatchNexpzToken has expiredsubemailname 
given_namefamily_namepictureemail_verifiedF)r   r   r   r   r   r   r   z!Google token verification error: z3Unexpected error during Google token verification: )r   verify_oauth2_tokengoogle_requestsRequestr	   GOOGLE_CLIENT_IDloggerwarningtimegetr   error	Exception)r   idinfoer   r   r   verify_google_token   s:   








r)   access_tokenc              
   C   s   z$dd|  i}t jd|d}|jdkr| W S td|j  W dS  ty? } ztd|  W Y d}~dS d}~ww )	z
    Get user information from Google using access token.
    
    Args:
        access_token: Google access token
        
    Returns:
        User information from Google or None if request fails
    AuthorizationzBearer z-https://www.googleapis.com/oauth2/v2/userinfo)headers   z Failed to get Google user info: Nz Error getting Google user info: )r   r$   status_codejsonr!   r%   r&   )r*   r,   responser(   r   r   r   get_google_user_infoI   s   


r1   c                  C   s0   d} t jt jddddd}t|}|  d| S )zm
    Create Google OAuth URL for authorization.
    
    Returns:
        Google OAuth authorization URL
    z,https://accounts.google.com/o/oauth2/v2/authcodezopenid email profileofflineconsent)	client_idredirect_uriresponse_typescopeaccess_typeprompt?)r	   r    GOOGLE_REDIRECT_URIr   )base_urlparamsquery_stringr   r   r   create_google_oauth_urle   s   
r@   r2   c              
      s~   z#ddt dttt tf  f fdd}|tj}|r|W S |dW S  ty> } ztd|  W Y d}~dS d}~ww )	z
    Exchange authorization code for access and refresh tokens.
    
    Args:
        code: Authorization code from Google
        
    Returns:
        Token response from Google or None if exchange fails
    z#https://oauth2.googleapis.com/tokenr6   r   c                    sT   t jt j d| d}tj|d}|jdkr| S td|j| |j	d d  d S )Nauthorization_code)r5   client_secretr2   
grant_typer6   )datar-   z>Google code exchange failed: status=%s redirect_uri=%s body=%si  )
r	   r    GOOGLE_CLIENT_SECRETr   postr.   r/   r!   r"   text)r6   payloadrespr2   	token_urlr   r   _try_exchange   s    
z/exchange_code_for_tokens.<locals>._try_exchangepostmessagez"Error exchanging code for tokens: N)	strr   r   r   r	   r<   r&   r!   r%   )r2   rL   resultr(   r   rJ   r   exchange_code_for_tokens{   s   
$

rP   )r   loggingr#   r   typingr   r   r   urllib.parser   google.auth.transportr   google.oauth2r   google.auth.exceptionsr   configr	   	getLoggerr   r!   r&   r
   rN   r)   r1   r@   rP   r   r   r   r   <module>   s     
0"