
    gY                       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mZmZmZ d dlmZmZ d dlmZ d	d
lmZmZmZmZ d	dlmZ d	dlmZm Z m!Z!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- ddl.m/Z/m0Z0  G d d      Z1y)    )annotations)partial)dumpsloads)Timer)time)AnyCallableDictOptionalTupleUnioncast)parse_qsurlparse)uuid4   )COOKIE_OPTIONSDEFAULT_HEADERS
GOTRUE_URLSTORAGE_KEY)APIError)is_http_urlis_valid_jwt
model_dumpmodel_validate)AuthChangeEventCookieOptionsProviderSessionSubscriptionUserUserAttributesUserAttributesDict   )SyncGoTrueAPI)SyncMemoryStorageSyncSupportedStoragec                     e Zd Zei dd e        ej                  e      ddddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d(dZd)dZ	d*dZ
d*dZd*d	Zdddddd
	 	 	 	 	 	 	 	 	 	 	 d+dZddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d,dZdd	 	 	 	 	 	 	 d-dZd.dZd/dZd0dZd1dZd2dZd3dZdd	 	 	 	 	 d4dZd*dZd5dZ	 	 	 	 d6dZ	 	 	 	 	 	 	 	 d7dZd8dZ	 	 	 	 	 	 	 	 d9dZd:dZd*dZd*d Zdd!d;d"Z d<d#Z!d=d$Z"d=d%Z#d*d&Z$d>d'Z%y)?SyncGoTrueClientTNF)
urlheadersauto_refresh_tokenpersist_sessionlocal_storagecookie_optionsapireplace_default_headersverifyproxyc       
           t        |      st        d       |j                  d      rt        d       i | _        d| _        d| _        d| _        || _        || _	        || _
        |ri nt        }|i ||||	|
d}|xs t        di || _        y)aD  Create a new client

        url : str
            The URL of the GoTrue server.
        headers : Dict[str, str]
            Any additional headers to send to the GoTrue server.
        auto_refresh_token : bool
            Set to "true" if you want to automatically refresh the token before
            expiring.
        persist_session : bool
            Set to "true" if you want to automatically save the user session
            into local storage.
        local_storage : SupportedStorage
            The storage engine to use for persisting the session.
        cookie_options : CookieOptions
            The options for the cookie.
        verify: bool
            Verify SSL, True by default, False disables verification.
        proxy: str
            HTTP Proxy string or None, None by default, None disables proxy.
        #url must be a valid HTTP URL stringzhttp://z`Warning:

DO NOT USE HTTP IN PRODUCTION FOR GOTRUE EVER!
GoTrue REQUIRES HTTPS to work securely.N)r+   r,   r0   r3   r4    )r   
ValueError
startswithprintstate_change_emittersrefresh_token_timercurrent_usercurrent_sessionr-   r.   r/   r   r&   r1   )selfr+   r,   r-   r.   r/   r0   r1   r2   r3   r4   empty_or_default_headersargss                H/var/www/openai/venv/lib/python3.12/site-packages/gotrue/_sync/client.py__init__zSyncGoTrueClient.__init__   s    F 3<=>>)$: ?A"48 ,026"4.*)@2o >2>g>,
 /-/$/    c                    | S Nr7   r?   s    rB   	__enter__zSyncGoTrueClient.__enter__X   s    rD   c                $    | j                          y rF   )close)r?   exc_texc_vexc_tbs       rB   __exit__zSyncGoTrueClient.__exit__[   s    

rD   c                8    | j                   j                          y rF   )r1   rJ   rG   s    rB   rJ   zSyncGoTrueClient.close^   s    rD   c                D    | j                          | j                          y)z/Recover the current session from local storage.N)_recover_session_recover_and_refreshrG   s    rB   init_recoverzSyncGoTrueClient.init_recovera   s    !!#rD   )emailphonepasswordredirect_todatac               h   | j                          |r"|r | j                  j                  ||||      }n;|r!|r| j                  j                  |||      }n|st	        d      t	        d      t        |t              r2| j                  |       | j                  t        j                         |S )a7  Creates a new user. If email and phone are provided, email will be
        used and phone will be ignored.

        Parameters
        ---------
        email : Optional[str]
            The user's email address.
        phone : Optional[str]
            The user's phone number.
        password : Optional[str]
            The user's password.
        redirect_to : Optional[str]
            A URL or mobile address to send the user to after they are confirmed.
        data : Optional[Dict[str, Any]]
            Optional user metadata.

        Returns
        -------
        response : Union[Session, User]
            A logged-in session if the server has "autoconfirm" ON
            A user if the server has "autoconfirm" OFF

        Raises
        ------
        APIError
            If an error occurs.
        )rT   rV   rW   rX   )rU   rV   rX   z(Password must be defined, can't be None.z3Email or phone must be defined, both can't be None.sessionevent)_remove_sessionr1   sign_up_with_emailsign_up_with_phoner8   
isinstancer    _save_session_notify_all_subscribersr   	SIGNED_IN)r?   rT   rU   rV   rW   rX   responses          rB   sign_upzSyncGoTrueClient.sign_upf   s    H 	Xxx22!'	 3 H xxx22hT 3 H GHHRSSh( x0((/H/H(IrD   )rT   rU   rV   refresh_tokenproviderrW   scopescreate_userc                  | j                          |r7|r| j                  |||      }	|	S | j                  j                  ||      }	|	S |r6|r| j	                  ||      }	|	S | j                  j                  ||      }	|	S |r | j                  |       | j                  }	|	S |r| j                  |||      }	|	S t        d      )a.  Log in an existing user, or login via a third-party provider.
        If email and phone are provided, email will be used and phone will be ignored.

        Parameters
        ---------
        email : Optional[str]
            The user's email address.
        phone : Optional[str]
            The user's phone number.
        password : Optional[str]
            The user's password.
        refresh_token : Optional[str]
            A valid refresh token that was returned on login.
        provider : Optional[Provider]
            One of the providers supported by GoTrue.
        redirect_to : Optional[str]
            A URL or mobile address to send the user to after they are confirmed.
        scopes : Optional[str]
            A space-separated list of scopes granted to the OAuth application.

        Returns
        -------
        response : Optional[Union[Session, str]]
            If only email are provided between the email and password,
            None is returned and send magic link to email

            If email and password are provided, a logged-in session is returned.

            If only phone are provided between the phone and password,
            None is returned and send message to phone

            If phone and password are provided, a logged-in session is returned.

            If refresh_token is provided, a logged-in session is returned.

            If provider is provided, an redirect URL is returned.

            Otherwise, error is raised.

        Raises
        ------
        APIError
            If an error occurs.
        rT   rV   rW   )rT   rj   rU   rV   )rU   rj   rg   rh   rW   ri   zLEmail, phone, refresh_token, or provider must be defined, all can't be None.)
r^   _handle_email_sign_inr1   send_magic_link_email_handle_phone_sign_insend_mobile_otp_call_refresh_tokenr>   _handle_provider_sign_inr8   )
r?   rT   rU   rV   rg   rh   rW   ri   rj   re   s
             rB   sign_inzSyncGoTrueClient.sign_in   s   p 	55% + 6 @ 5  8899[ : 4 / 55EH5U* '  8833[ 4 & !  $$=$A++H  44!' 5 H 	 % rD   )rW   c                   | j                          | j                  j                  |||      }t        |t              r2| j                  |       | j                  t        j                         |S )a^  Log in a user given a User supplied OTP received via mobile.

        Parameters
        ----------
        phone : str
            The user's phone number.
        token : str
            The user's OTP.
        redirect_to : Optional[str]
            A URL or mobile address to send the user to after they are confirmed.

        Returns
        -------
        response : Union[Session, User]
            A logged-in session if the server has "autoconfirm" ON
            A user if the server has "autoconfirm" OFF

        Raises
        ------
        APIError
            If an error occurs.
        )rU   tokenrW   rZ   r\   )	r^   r1   verify_mobile_otpra   r    rb   rc   r   rd   )r?   rU   rx   rW   re   s        rB   
verify_otpzSyncGoTrueClient.verify_otp   sk    : 	88--# . 

 h(x0((/H/H(IrD   c                    | j                   S )z4Returns the user data, if there is a logged in user.)r=   rG   s    rB   userzSyncGoTrueClient.user(  s       rD   c                    | j                   S )z8Returns the session data, if there is an active session.)r>   rG   s    rB   r[   zSyncGoTrueClient.session,  s    ###rD   c                P    | j                   st        d      | j                         S )zForce refreshes the session.

        Force refreshes the session including the user data incase it was
        updated in a different session.
        Not logged in.)r>   r8   rt   rG   s    rB   refresh_sessionz SyncGoTrueClient.refresh_session0  s(     ##-..''))rD   c               l   | j                   st        d      t        |t              rt	        di |}n|}| j
                  j                  | j                   j                  |      }|| j                   _        | j                  | j                          | j                  t        j                         |S )a  Updates user data, if there is a logged in user.

        Parameters
        ----------
        attributes : UserAttributesDict | UserAttributes
            Attributes to update, could be: email, password, email_change_token, data

        Returns
        -------
        response : User
            The updated user data.

        Raises
        ------
        APIError
            If an error occurs.
        r   )jwt
attributesrZ   r\   r7   )r>   r8   ra   dictr#   r1   update_useraccess_tokenr|   rb   rc   r   USER_UPDATED)r?   r   attributes_to_updatere   s       rB   updatezSyncGoTrueClient.update:  s    $ ##-..j$'#1#?J#? #- 88''$$11+ ( 
 %-!4#7#78$$?+G+G$HrD   c                   t        |      st        d       | j                  j                  |      }| j	                  |       | j                  t        j                         |S )aT  Sets the session data from refresh_token and returns current Session

        Parameters
        ----------
        refresh_token : str
            A JWT token

        Returns
        -------
        response : Session
            A logged-in session

        Raises
        ------
        APIError
            If an error occurs.
        z5refresh_token must be a valid JWT authorization tokenrn   rZ   r\   )r   r8   r1   refresh_access_tokenrb   rc   r   rd   r?   rg   re   s      rB   set_sessionzSyncGoTrueClient.set_session]  sY    & M*NO8800}0M8,$$?+D+D$ErD   c          	     j   t        |      st        d       t        |dddddd      }| j                  rl| j                  j                  |_        | j                  j
                  |_        | j                  j                  |_        | j                  j                  |_        | j                  |       |S )a}  Overrides the JWT on the current client. The JWT will then be sent in
        all subsequent network requests.

        Parameters
        ----------
        access_token : str
            A JWT token

        Returns
        -------
        response : Session
            A logged-in session

        Raises
        ------
        APIError
            If an error occurs.
        z4access_token must be a valid JWT authorization tokenbearerNr   
token_typer|   
expires_in
expires_atrg   provider_tokenrZ   )	r   r8   r    r>   r   r   rg   r   rb   )r?   r   r[   s      rB   set_authzSyncGoTrueClient.set_authx  s    ( L)MN%
 !%!5!5!@!@G!%!5!5!@!@G$($8$8$F$FG!%)%9%9%H%HG"7+rD   )store_sessionc          
        t        |      st        d       t        |      }t        |j                        }|j                  d      }|j                  d      }|j                  d      }|j                  d      }|j                  d      }	|rt        |d   d      |r|d   st        d	d      |r|d   st        d
d      |	r|	d   st        dd      |r|d   st        dd      	 t        t                     t        |d         z   }
| j                  j                  |d         }|j                  d      }t        |d   |	d   |t        |d         |
|d   |r|d   nd      }|rm| j                  |       |j                  d      }| j                  t        j                          |r(|d   dk(  r | j                  t        j"                         |S # t        $ r t        dd      w xY w)a  Gets the session data from a URL string.

        Parameters
        ----------
        url : str
            The URL string.
        store_session : bool
            Optionally store the session in the browser

        Returns
        -------
        response : Session
            A logged-in session

        Raises
        ------
        APIError
            If an error occurs.
        r6   error_descriptionr   r   rg   r   r   i  zNo access_token detected.zNo refresh_token detected.zNo token_type detected.zNo expires_in detected.zInvalid expires_in.r   r   Nr   rZ   typer\   recovery)r   r8   r   r   querygetr   roundr   intr1   get_userr    rb   rc   r   rd   PASSWORD_RECOVERY)r?   r+   r   rX   r   r   r   r   rg   r   r   re   r   r[   recovery_modes                  rB   get_session_from_urlz%SyncGoTrueClient.get_session_from_url  s   2 3<=}$!II&9:yy0YY|,
		/2YY|,
,Q/55<?6<<M!$47==A4c::A4c::	7tvZ]);;J 88$$a$9#34%a!!}:a=)!'*0>>!,D
 w/!IIf-M((/H/H(Iq!1Z!?,,?3T3T,U'  	70#66	7s   *"G G1c                    d}| j                   r| j                   j                  }| j                          | j                  t        j
                         |r| j                  j                  |       yy)zLog the user out.Nr\   r   )r>   r   r^   rc   r   
SIGNED_OUTr1   sign_out)r?   r   s     rB   r   zSyncGoTrueClient.sign_out  sa    &*//<<L$$?+E+E$FHH,/ rD   c               :    | j                   j                  |       y)z Unsubscribe from a subscription.N)r;   pop)r?   ids     rB   _unsubscribezSyncGoTrueClient._unsubscribe  s    ""&&r*rD   c                   t               }t        ||t        | j                  |j                              }|| j
                  |j                  <   |S )a  Receive a notification every time an auth event happens.

        Parameters
        ----------
        callback : Callable[[AuthChangeEvent, Optional[Session]], None]
            The callback to call when an auth event happens.

        Returns
        -------
        subscription : Subscription
            A subscription object which can be used to unsubscribe itself.

        Raises
        ------
        APIError
            If an error occurs.
        )r   )r   callbackunsubscribe)r   r!   r   r   hexr;   )r?   r   	unique_idsubscriptions       rB   on_auth_state_changez%SyncGoTrueClient.on_auth_state_change  sL    , G	# 1 1immD

 5A""9==1rD   c                   | j                   j                  |||      }| j                  |       | j                  t        j
                         |S )z Sign in with email and password.rl   rZ   r\   )r1   sign_in_with_emailrb   rc   r   rd   )r?   rT   rV   rW   re   s        rB   rp   z&SyncGoTrueClient._handle_email_sign_in  sU     88..# / 

 	8,$$?+D+D$ErD   c                   | j                   j                  ||      }| j                  |       | j                  t        j
                         |S )z Sign in with phone and password.rm   rZ   r\   )r1   sign_in_with_phonerb   rc   r   rd   )r?   rU   rV   re   s       rB   rr   z&SyncGoTrueClient._handle_phone_sign_in!  sH    88..UX.N8,$$?+D+D$ErD   c               >    | j                   j                  |||      S )zSign in with provider.ro   )r1   get_url_for_provider)r?   rh   rW   ri   s       rB   ru   z)SyncGoTrueClient._handle_provider_sign_in(  s)     xx,,# - 
 	
rD   c                V   | j                   j                  t              }|syt        |      }|j	                  d      }|j	                  d      }|rXt        |t              rG|rDt        |t              r3t        t        |      }t        |      }t        t                     }|||fS yyyy)zRecover common logicNr[   r   )r/   get_itemr   r   r   ra   r   r   r   r    r   r   )r?   jsonrX   session_rawexpires_at_rawr[   r   time_nows           rB   _recover_commonz SyncGoTrueClient._recover_common6  s    !!**;7T{hhy),/>3/;-$Wk:G^,JTV}HJ00 .  0 rD   c                    | j                         }|sy|\  }}}||k\  r3| j                  |       | j                  t        j                         yy)z-Attempts to get the session from LocalStorageNrZ   r\   )r   rb   rc   r   rd   r?   resultr[   r   r   s        rB   rQ   z!SyncGoTrueClient._recover_sessionI  sW    %%'(.%X!w/((/H/H(I "rD   c                   | j                         }|sy|\  }}}||k  r6| j                  r*|j                  r	 | j                  |j                         y||k  s|r|j                  s| j                          y| j                  |       | j                  t        j                         y# t        $ r | j                          Y yw xY w)z4Recovers the session from LocalStorage and refreshesNrn   rZ   r\   )r   r-   rg   rt   r   r^   r|   rb   rc   r   rd   r   s        rB   rR   z%SyncGoTrueClient._recover_and_refreshS  s    %%'(.%X T%<%<AVAV'((w7L7L(M ("'  "w/((/H/H(I  '$$&'s   B, ,CCrn   c               ^   |.| j                   r| j                   j                  }nt        d      | j                  j	                  t        t        |            }| j                  |       | j                  t        j                         | j                  t        j                         |S )Nz2No current session and refresh_token not supplied.rn   rZ   r\   )r>   rg   r8   r1   r   r   strrb   rc   r   TOKEN_REFRESHEDrd   r   s      rB   rt   z$SyncGoTrueClient._call_refresh_tokend  s     ## $ 4 4 B B !UVV8800tC?W0X8,$$?+J+J$K$$?+D+D$ErD   c               z    | j                   j                         D ]  }|j                  || j                           y)z0Notify all subscribers that auth event happened.N)r;   valuesr   r>   )r?   r]   values      rB   rc   z(SyncGoTrueClient._notify_all_subscribersp  s/    //668ENN5$"6"67 9rD   c               $   || _         |j                  | _        |j                  r@t	        t                     }|j                  |z
  }|dkD  rdnd}| j                  ||z
         | j                  r |j                  r| j                  |       yyy)zSave session to client.<   g      ?)r   rZ   N)	r>   r|   r=   r   r   r   _start_auto_refresh_tokenr.   _persist_session)r?   r[   r   	expire_inrefresh_duration_before_expiress        rB   rb   zSyncGoTrueClient._save_sessionu  s    &#LLTV}H**X5I4=Nb+** #BB +  G$6$6!!'!2 %7rD   c                   t        |      |j                  d}| j                  j                  t        t        |t                     y )N)r[   r   )default)r   r   r/   set_itemr   r   r   )r?   r[   rX   s      rB   r   z!SyncGoTrueClient._persist_session  s4    %g.g>P>PQ##KtS1IJrD   c                    d| _         d| _        | j                  r| j                  j                          | j                  j                  t               y)zRemove the session.N)r>   r=   r<   cancelr/   remove_itemr   rG   s    rB   r^   z SyncGoTrueClient._remove_session  sA    # ##$$++-&&{3rD   c                   | j                   r| j                   j                          |dk  s| j                  sy t        || j                        | _         | j                   j                          y )Nr   )r<   r   r-   r   rt   start)r?   r   s     rB   r   z*SyncGoTrueClient._start_auto_refresh_token  sV    ##$$++-A:T44#(0H0H#I   &&(rD   )r+   r   r,   zDict[str, str]r-   boolr.   r   r/   r(   r0   r   r1   zOptional[SyncGoTrueAPI]r2   r   r3   r   r4   Optional[str]returnNone)r   r*   )r   r   )rT   r   rU   r   rV   r   rW   r   rX   zOptional[Dict[str, Any]]r   Union[Session, User])rT   r   rU   r   rV   r   rg   r   rh   zOptional[Provider]rW   r   ri   r   rj   r   r   zOptional[Union[Session, str]])rU   r   rx   r   rW   r   r   r   )r   zOptional[User])r   zOptional[Session])r   r    )r   z)Union[UserAttributesDict, UserAttributes]r   r"   )rg   r   r   r    )r   r   r   r    )r+   r   r   r   r   r    )r   r   r   r   )r   z4Callable[[AuthChangeEvent, Optional[Session]], None]r   r!   )rT   r   rV   r   rW   r   r   r    )rU   r   rV   r   r   r    )rh   r   rW   r   ri   r   r   r   )r   z"Optional[Tuple[Session, int, int]])rg   r   r   r    )r]   r   r   r   )r[   r    r   r   )r   floatr   r   )&__name__
__module____qualname__r   r'   r   	parse_objr   rC   rH   rN   rJ   rS   rf   rv   rz   r|   r[   r   r   r   r   r   r   r   r   rp   rr   ru   r   rQ   rR   rt   rc   rb   r   r^   r   r7   rD   rB   r*   r*      s    "$#' $.?.A(?(?(?(O'+(-#90 90  	90
 !90 90 ,90 &90 %90 "&90 90 90 
90v$  $#"&%))-; ; 	;
  ; #; '; 
;@  $#"&'+'+%) $![ [ 	[
  [ %[ %[ #[ [ [ 
'[D &*& & 	&
 #& 
&P!$*!F6&X $	A A 	A
 
AF0+ G 
	>  	
 # 
"
 
 #	

 
 

1&JJ" EI 
8
3K4)rD   r*   N)2
__future__r   	functoolsr   r   r   r   	threadingr   r   typingr	   r
   r   r   r   r   r   urllib.parser   r   uuidr   	constantsr   r   r   r   
exceptionsr   helpersr   r   r   r   typesr   r   r   r    r!   r"   r#   r$   r1   r&   storager'   r(   r*   r7   rD   rB   <module>r      sU    "     D D D +  P P ! K K	 	 	  <y	) y	)rD   