o
    g2                     @  s   d Z ddlmZ dgZddlmZmZmZmZ ddl	m
Z
mZmZ ddlmZmZ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 erUd	dlmZ G dd dZdS )z6Implementing support for MySQL Authentication Plugins.    )annotationsMySQLAuthenticator)TYPE_CHECKINGAnyDictOptional   )InterfaceErrorNotSupportedErrorget_exception)AUTH_SWITCH_STATUSDEFAULT_CHARSET_IDDEFAULT_MAX_ALLOWED_PACKET
ERR_STATUSEXCHANGE_FURTHER_STATUS
MFA_STATUS	OK_STATUS)HandShakeType   )logger)MySQLAuthPluginget_auth_plugin)MySQLProtocol)MySQLSocketc                   @  s   e Zd ZdZd:ddZed;ddZed<d
dZd=ddZ			d>d?ddZ	d@dd Z
d@d!d"Zd#d#d#d#ded$d%edddd%ddfdAd8d9ZdS )Br   z$Implements the authentication phase.returnNonec                 C  s(   d| _ i | _i | _d| _d| _d| _dS )zConstructor. FN)	_username
_passwords_plugin_config_ssl_enabled_auth_strategy_auth_plugin_classself r%   \/var/www/html/api-tag/env/lib/python3.10/site-packages/mysql/connector/aio/authentication.py__init__;   s   
zMySQLAuthenticator.__init__boolc                 C     | j S )z&Signals whether or not SSL is enabled.)r    r#   r%   r%   r&   ssl_enabledD   s   zMySQLAuthenticator.ssl_enabledDict[str, Any]c                 C  r)   )a  Custom arguments that are being provided to the authentication plugin.

        The parameters defined here will override the ones defined in the
        auth plugin itself.

        The plugin config is a read-only property - the plugin configuration
        provided when invoking `authenticate()` is recorded and can be queried
        by accessing this property.

        Returns:
            dict: The latest plugin configuration provided when invoking
                  `authenticate()`.
        )r   r#   r%   r%   r&   plugin_configI   s   z MySQLAuthenticator.plugin_configconfigc                 C  s   | j | dS )z,Update the 'plugin_config' instance variableN)r   update)r$   r-   r%   r%   r&   update_plugin_configZ   s   z'MySQLAuthenticator.update_plugin_configNr   new_strategy_namestrstrategy_classOptional[str]usernamepassword_factorintc                 C  sP   |du r| j }|du r| j}td| t||d|| j|d| jd| _dS )a  Switch the authorization plugin.

        Args:
            new_strategy_name: New authorization plugin name to switch to.
            strategy_class: New authorization plugin class to switch to
                            (has higher precedence than the authorization plugin name).
            username: Username to be used - if not defined, the username
                      provided when `authentication()` was invoked is used.
            password_factor: Up to three levels of authentication (MFA) are allowed,
                             hence you can choose the password corresponding to the 1st,
                             2nd, or 3rd factor - 1st is the default.
        NzSwitching to strategy %s)plugin_nameauth_plugin_classr   )r*   )	r   r"   r   debugr   r   getr*   r!   )r$   r0   r2   r4   r5   r%   r%   r&   _switch_auth_strategy^   s   z(MySQLAuthenticator._switch_auth_strategysockr   pktbytesOptional[bytes]c                   s   d}|d t krs|| jvrtdt|\}}| j||d td|| jj	 | jj
||fi | jI dH }|d tkrRt|}| jj||fi | jI dH }|d tkr_td |S |d tkrit||d7 }|d t ks	td	 dS )
a  Handle MFA (Multi-Factor Authentication) response.

        Up to three levels of authentication (MFA) are allowed.

        Args:
            sock: Pointer to the socket connection.
            pkt: MFA response.

        Returns:
            ok_packet: If last server's response is an OK packet.
            None: If last server's response isn't an OK packet and no ERROR was raised.

        Raises:
            InterfaceError: If got an invalid N factor.
            errors.ErrorTypes: If got an ERROR response.
        r      z5Failed Multi Factor Authentication (invalid N factor))r5   zMFA %i factor %sNzMFA completed succesfullyr   z"MFA terminated with a no ok packet)r   r   r	   r   parse_auth_next_factorr;   r   r9   r!   nameauth_switch_responser   r   parse_auth_more_dataauth_more_responser   r   r   warning)r$   r<   r=   n_factorr0   	auth_datar%   r%   r&   _mfa_n_factor   s>   



z MySQLAuthenticator._mfa_n_factorc                   s  |d t krt|dkrtd|d t kr7td t|\}}| | | jj	||fi | j
I dH }|d tkrVtd t|}| jj||fi | j
I dH }|d tkrftd| jj |S |d tkrtd td	| jj | ||I dH S |d tkrt|dS )
a  Handle server's response.

        Args:
            sock: Pointer to the socket connection.
            pkt: Server's response after completing the `HandShakeResponse`.

        Returns:
            ok_packet: If last server's response is an OK packet.
            None: If last server's response isn't an OK packet and no ERROR was raised.

        Raises:
            errors.ErrorTypes: If got an ERROR response.
            NotSupportedError: If got Authentication with old (insecure) passwords.
        r@      zAuthentication with old (insecure) passwords is not supported. For more information, lookup Password Hashing in the latest MySQL manualz+Server's response is an auth switch requestNzExchanging further packetsz%s completed succesfullyz$Starting multi-factor authenticationzMFA 1 factor %s)r   lenr
   r   r9   r   parse_auth_switch_requestr;   r!   rC   r   r   rD   rE   r   rB   r   rI   r   r   )r$   r<   r=   r0   rH   r%   r%   r&   _handle_server_response   s@   




z*MySQLAuthenticator._handle_server_responser   r   F	handshaker   	password1	password2	password3databasecharsetclient_flagsr*   max_allowed_packetauth_pluginr8   
conn_attrsOptional[Dict[str, str]]is_change_user_requestread_timeoutOptional[int]write_timeoutc                   s   || _ |||d| _|
| _|| _tj||||||	|||||| j| jd\}| _|r/dd|fndd|f}|j	|g|R  I dH  t
||I dH }| ||I dH }|du r\tdd|S )a  Perform the authentication phase.

        During re-authentication you must set `is_change_user_request` to True.

        Args:
            sock: Pointer to the socket connection.
            handshake: Initial handshake.
            username: Account's username.
            password1: Account's password factor 1.
            password2: Account's password factor 2.
            password3: Account's password factor 3.
            database: Initial database name for the connection.
            charset: Client charset (see [1]), only the lower 8-bits.
            client_flags: Integer representing client capabilities flags.
            ssl_enabled: Boolean indicating whether SSL is enabled,
            max_allowed_packet: Maximum packet size.
            auth_plugin: Authorization plugin name.
            auth_plugin_class: Authorization plugin class (has higher precedence
                               than the authorization plugin name).
            conn_attrs: Connection attributes.
            is_change_user_request: Whether is a `change user request` operation or not.
            read_timeout: Timeout in seconds upto which the connector should wait for
                          the server to reply back before raising an ReadTimeoutError.
            write_timeout: Timeout in seconds upto which the connector should spend to
                           send data to the server before raising an WriteTimeoutError.

        Returns:
            ok_packet: OK packet.

        Raises:
            InterfaceError: If OK packet is NULL.
            ReadTimeoutError: If the time taken for the server to reply back exceeds
                              'read_timeout' (if set).
            WriteTimeoutError: If the time taken to send data packets to the server
                               exceeds 'write_timeout' (if set).

        References:
            [1]: https://dev.mysql.com/doc/dev/mysql-server/latest/                page_protocol_basic_character_set.html#a_protocol_character_set
        )r   r      )rN   r4   passwordrR   rS   rT   rU   rV   r8   rW   rY   r*   r,   r   NzGot a NULL ok_pkt)r   r   r    r"   r   	make_authr*   r,   r!   writer>   readrM   r	   )r$   r<   rN   r4   rO   rP   rQ   rR   rS   rT   r*   rU   rV   r8   rW   rY   rZ   r\   response_payload	send_argsr=   ok_pktr%   r%   r&   authenticate   s<   =
zMySQLAuthenticator.authenticate)r   r   )r   r(   )r   r+   )r-   r+   r   r   )NNr   )
r0   r1   r2   r3   r4   r3   r5   r6   r   r   )r<   r   r=   r>   r   r?   )$r<   r   rN   r   r4   r1   rO   r1   rP   r1   rQ   r1   rR   r3   rS   r6   rT   r6   r*   r(   rU   r6   rV   r3   r8   r3   rW   rX   rY   r(   rZ   r[   r\   r[   r   r>   )__name__
__module____qualname____doc__r'   propertyr*   r,   r/   r;   rI   rM   r   r   re   r%   r%   r%   r&   r   8   s<    
	

"
6;N)ri   
__future__r   __all__typingr   r   r   r   errorsr	   r
   r   protocolr   r   r   r   r   r   r   typesr   r   pluginsr   r   r   networkr   r   r%   r%   r%   r&   <module>   s   $	