U
    #iK                     @  s   d dl mZ d dlmZmZmZmZ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mZmZmZmZmZmZmZ G d	d
 d
ZdS )    )annotations)AnyDictListOptionalUnion)parse_obj_as   )APIError)check_responseencode_uri_component)
SyncClient)CookieOptionsLinkTypeProviderSessionUserUserAttributes-determine_session_or_user_model_from_responsec                	   @  s  e Zd Zdddddddddd	d
dddZd dddZd
dddZd
dddZdddddZddddZdddddd	ddd d!d"Z	dd#ddd	d$d%d&d'Z
dd(ddddd)d*d+Zddd$d,d-d.Zdd#ddd	d
d/d0d1Zddd
d2d3d4Zdd#ddd	dd5d6d7Zddddd	ddd8d9d:Zdd#dd	d
d;d<d=Zddd>d?d@Zdd
d>dAdBZdddCdDd	d	ddEdFdGZddd>dHdIZddddJdKdLZdMdNdddd
dOdPdQZdd$dRdSdTZddddUdVdd	d	dddWdXdYZdZd[ Zd\d] ZdS )^SyncGoTrueAPINT)http_clientverifyproxystrzDict[str, str]r   zOptional[SyncClient]boolzOptional[str]None)urlheaderscookie_optionsr   r   r   returnc                C  s0   || _ || _|| _|p(tt||ddd| _dS )zInitialise API class.T)r   r   Zfollow_redirectsZhttp2N)r   r   r   r   r   r   )selfr   r   r   r   r   r    r!   4/tmp/pip-unpacked-wheel-b8wmx3ip/gotrue/_sync/api.py__init__   s    zSyncGoTrueAPI.__init__)r   c                 C  s   | S Nr!   r    r!   r!   r"   	__enter__+   s    zSyncGoTrueAPI.__enter__c                 C  s   |    d S r$   )close)r    Zexc_tZexc_vexc_tbr!   r!   r"   __exit__.   s    zSyncGoTrueAPI.__exit__c                 C  s   | j   d S r$   )r   acloser%   r!   r!   r"   r'   1   s    zSyncGoTrueAPI.closer   r   )
attributesr   c                C  s6   | j }| }| j d}| jj|||d}t|S )a  Creates a new user.

        This function should only be called on a server.
        Never expose your `service_role` key in the browser.

        Parameters
        ----------
        attributes: UserAttributes
            The data you want to create the user with.

        Returns
        -------
        response : User
            The created user

        Raises
        ------
        APIError
            If an error occurs.
        /admin/usersjsonr   )r   dictr   r   postr   parse_response)r    r+   r   datar   responser!   r!   r"   create_user4   s
    zSyncGoTrueAPI.create_userz
List[User]c                 C  sl   | j }| j d}| jj||d}t| | d}|dkrJtddt|ts^tddt	t
t |S )a?  Get a list of users.

        This function should only be called on a server.
        Never expose your `service_role` key in the browser.

        Returns
        -------
        response : List[User]
            A list of users

        Raises
        ------
        APIError
            If an error occurs.
        r,   r   usersNzNo users found in responsei  zExpected a list of users)r   r   r   getr   r.   r
   
isinstancelistr   r   r   )r    r   r   r3   r6   r!   r!   r"   
list_usersO   s    


zSyncGoTrueAPI.list_users)redirect_tor2   zOptional[Dict[str, Any]]zUnion[Session, User])emailpasswordr;   r2   r   c                C  s`   | j }d}|r t|}d| }|||d}| j d| }| jj|||d}	t|	}
|
|	S )a  Creates a new user using their email address.

        Parameters
        ----------
        email : str
            The email address of the user.
        password : str
            The password of the user.
        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.
         ?redirect_to=)r<   r=   r2   /signupr-   r   r   r   r   r0   r   r1   )r    r<   r=   r;   r2   r   query_stringredirect_to_encodedr   r3   session_or_user_modelr!   r!   r"   sign_up_with_emailj   s     
z SyncGoTrueAPI.sign_up_with_email)r;   r   )r<   r=   r;   r   c          
      C  sZ   | j }d}|r$t|}|d| 7 }||d}| j d| }| jj|||d}	t|	S )a  Logs in an existing user using their email address.

        Parameters
        ----------
        email : str
            The email address of the user.
        password : str
            The password of the user.
        redirect_to : Optional[str]
            A URL or mobile address to send the user to after they are confirmed.

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

        Raises
        ------
        APIError
            If an error occurs.
        z?grant_type=passwordz&redirect_to=)r<   r=   z/tokenr-   )r   r   r   r   r0   r   r1   )
r    r<   r=   r;   r   rB   rC   r2   r   r3   r!   r!   r"   sign_in_with_email   s    
z SyncGoTrueAPI.sign_in_with_email)r2   )phoner=   r2   r   c                C  sB   | j }|||d}| j d}| jj|||d}t|}||S )aF  Signs up a new user using their phone number and a password.

        Parameters
        ----------
        phone : str
            The phone number of the user.
        password : str
            The password of the user.
        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.
        )rG   r=   r2   r@   r-   )r   r   r   r0   r   r1   )r    rG   r=   r2   r   r   r3   rD   r!   r!   r"   sign_up_with_phone   s    z SyncGoTrueAPI.sign_up_with_phone)rG   r=   r   c                C  s8   ||d}| j  d}| j}| jj|||d}t|S )a  Logs in an existing user using their phone number and password.

        Parameters
        ----------
        phone : str
            The phone number of the user.
        password : str
            The password of the user.

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

        Raises
        ------
        APIError
            If an error occurs.
        )rG   r=   z/token?grant_type=passwordr-   r   r   r   r0   r   r1   )r    rG   r=   r2   r   r   r3   r!   r!   r"   sign_in_with_phone   s
    
z SyncGoTrueAPI.sign_in_with_phone)r<   r4   r;   r   c          
      C  sT   | j }d}|r t|}d| }||d}| j d| }| jj|||d}	t|	S )ab  Sends a magic login link to an email address.

        Parameters
        ----------
        email : str
            The email address of the user.
        redirect_to : Optional[str]
            A URL or mobile address to send the user to after they are confirmed.

        Raises
        ------
        APIError
            If an error occurs.
        r>   r?   )r<   r4   z
/magiclinkr-   r   r   r   r   r0   r   )
r    r<   r4   r;   r   rB   rC   r2   r   r3   r!   r!   r"   send_magic_link_email   s    

z#SyncGoTrueAPI.send_magic_link_email)rG   r4   r   c                C  s6   | j }||d}| j d}| jj|||d}t|S )a#  Sends a mobile OTP via SMS. Will register the account if it doesn't already exist

        Parameters
        ----------
        phone : str
            The user's phone number WITH international prefix

        Raises
        ------
        APIError
            If an error occurs.
        )rG   r4   z/otpr-   )r   r   r   r0   r   )r    rG   r4   r   r2   r   r3   r!   r!   r"   send_mobile_otp  s
    
zSyncGoTrueAPI.send_mobile_otp)rG   tokenr;   r   c          
      C  sV   | j }||dd}|r&t|}||d< | j d}| jj|||d}t|}	|	|S )a  Send User supplied Mobile OTP to be verified

        Parameters
        ----------
        phone : str
            The user's phone number WITH international prefix
        token : str
            Token that user was sent to their mobile phone
        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.
        Zsms)rG   rN   typer;   z/verifyr-   rA   )
r    rG   rN   r;   r   r2   rC   r   r3   rD   r!   r!   r"   verify_mobile_otp1  s    zSyncGoTrueAPI.verify_mobile_otp)r<   r;   r2   r   c          	      C  sV   | j }d}|r t|}d| }||d}| j d| }| jj|||d}t|S )a  Sends an invite link to an email address.

        Parameters
        ----------
        email : str
            The email address of the user.
        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 : User
            A user

        Raises
        ------
        APIError
            If an error occurs.
        r>   r?   )r<   r2   z/inviter-   )r   r   r   r   r0   r   r1   )	r    r<   r;   r2   r   rB   rC   r   r3   r!   r!   r"   invite_user_by_email\  s    

z"SyncGoTrueAPI.invite_user_by_email)r<   r;   r   c          	      C  sR   | j }d}|r t|}d| }d|i}| j d| }| jj|||d}t|S )a_  Sends a reset request to an email address.

        Parameters
        ----------
        email : str
            The email address of the user.
        redirect_to : Optional[str]
            A URL or mobile address to send the user to after they are confirmed.

        Raises
        ------
        APIError
            If an error occurs.
        r>   r?   r<   z/recoverr-   rK   )	r    r<   r;   r   rB   rC   r2   r   r3   r!   r!   r"   reset_password_for_email  s    
z&SyncGoTrueAPI.reset_password_for_email)jwtr   c                C  s   | j dd| i}|S )a  Create temporary object.

        Create a temporary object with all configured headers and adds the
        Authorization token to be used on request methods.

        Parameters
        ----------
        jwt : str
            A valid, logged-in JWT.

        Returns
        -------
        headers : dict of str
            The headers required for a successful request statement with the
            supabase backend.
        AuthorizationzBearer r5   )r    rS   r   r!   r!   r"   _create_request_headers  s    z%SyncGoTrueAPI._create_request_headersc                C  s,   | j |d}| j d}| jj||d dS )zRemoves a logged-in session.

        Parameters
        ----------
        jwt : str
            A valid, logged-in JWT.
        rS   z/logoutr5   N)rU   r   r   r0   )r    rS   r   r   r!   r!   r"   sign_out  s    zSyncGoTrueAPI.sign_out)r;   scopesr   )providerr;   rX   r   c                C  sZ   dt | g}|r,t |}|d|  |rD|dt |  | j dd| S )aR  Generates the relevant login URL for a third-party provider.

        Parameters
        ----------
        provider : 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
        -------
        url : str
            The URL to redirect the user to.

        Raises
        ------
        APIError
            If an error occurs.
        z	provider=zredirect_to=zscopes=z/authorize?&)r   appendr   join)r    rY   r;   rX   Z
url_paramsrC   r!   r!   r"   get_url_for_provider  s    z"SyncGoTrueAPI.get_url_for_providerc                C  s2   | j |d}| j d}| jj||d}t|S )a  Gets the user details.

        Parameters
        ----------
        jwt : str
            A valid, logged-in JWT.

        Returns
        -------
        response : User
            A user

        Raises
        ------
        APIError
            If an error occurs.
        rV   /userr5   )rU   r   r   r7   r   r1   )r    rS   r   r   r3   r!   r!   r"   get_user  s    zSyncGoTrueAPI.get_user)rS   r+   r   c                C  s<   | j |d}| }| j d}| jj|||d}t|S )an  
        Updates the user data.

        Parameters
        ----------
        jwt : str
            A valid, logged-in JWT.
        attributes : UserAttributes
            The data you want to update.

        Returns
        -------
        response : User
            A user

        Raises
        ------
        APIError
            If an error occurs.
        rV   r^   r-   )rU   r/   r   r   putr   r1   )r    rS   r+   r   r2   r   r3   r!   r!   r"   update_user  s
    zSyncGoTrueAPI.update_userF)should_soft_delete)uidrS   rb   r   c                C  s>   | j |d}| j d| }d|i}| jj|||d}t|S )aU  Delete a user. Requires a `service_role` key.

        This function should only be called on a server.
        Never expose your `service_role` key in the browser.

        Parameters
        ----------
        uid : str
            The user uid you want to remove.
        jwt : str
            A valid, logged-in JWT.
        should_soft_delete : bool
            If true, then the user will be soft-deleted from the auth schema.

        Returns
        -------
        response : User
            A user

        Raises
        ------
        APIError
            If an error occurs.
        rV   z/admin/users/rb   r-   )rU   r   r   deleter   )r    rc   rS   rb   r   r   bodyr3   r!   r!   r"   delete_user  s     zSyncGoTrueAPI.delete_user)refresh_tokenr   c                C  s6   d|i}| j  d}| j}| jj|||d}t|S )a@  Generates a new JWT.

        Parameters
        ----------
        refresh_token : str
            A valid refresh token that was returned on login.

        Returns
        -------
        response : Session
            A session

        Raises
        ------
        APIError
            If an error occurs.
        rg   z/token?grant_type=refresh_tokenr-   rI   )r    rg   r2   r   r   r3   r!   r!   r"   refresh_access_token>  s
    z"SyncGoTrueAPI.refresh_access_token)r=   r;   r2   r   )rO   r<   r=   r;   r2   r   c                C  sb   | j }|||d}|r||d< |r2t|}||d< | j d}| jj|||d}	t|	}
|
|	S )a0  
        Generates links to be sent via email or other.

        Parameters
        ----------
        type : LinkType
            The link type ("signup" or "magiclink" or "recovery" or "invite").
        email : str
            The user's email.
        password : Optional[str]
            User password. For signup only.
        redirect_to : Optional[str]
            The link type ("signup" or "magiclink" or "recovery" or "invite").
        data : Optional[Dict[str, Any]]
            Optional user metadata. For signup only.

        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.
        )rO   r<   r2   r=   r;   z/admin/generate_linkr-   rA   )r    rO   r<   r=   r;   r2   r   rC   r   r3   rD   r!   r!   r"   generate_linkV  s    $zSyncGoTrueAPI.generate_linkc                C  s   t ddS )Stub for parity with JS api.z set_auth_cookie not implemented.NNotImplementedError)r    reqresr!   r!   r"   set_auth_cookie  s    zSyncGoTrueAPI.set_auth_cookiec                C  s   t ddS )rj   z#get_user_by_cookie not implemented.Nrk   )r    rm   r!   r!   r"   get_user_by_cookie  s    z SyncGoTrueAPI.get_user_by_cookie)__name__
__module____qualname__r#   r&   r)   r'   r4   r:   rE   rF   rH   rJ   rL   rM   rP   rQ   rR   rU   rW   r]   r_   ra   rf   rh   ri   ro   rp   r!   r!   r!   r"   r      sV    0,$$/*$!#4r   N)
__future__r   typingr   r   r   r   r   Zpydanticr   
exceptionsr
   Zhelpersr   r   Zhttp_clientsr   typesr   r   r   r   r   r   r   r   r!   r!   r!   r"   <module>   s   $