
    ([f<                         d dl Z d dlmZ d dl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  e j        e          Z G d d	eee          Zd
 ZdS )    N)add_params_to_uri)generate_token   )	BaseGrantAuthorizationEndpointMixinTokenEndpointMixin   )OAuth2ErrorUnauthorizedClientErrorInvalidClientErrorInvalidGrantErrorInvalidRequestErrorAccessDeniedErrorc                   d    e Zd ZdZddgZdZdhZdZd Zde	fd	Z
d
 Zd Zd Zd Zd Zd Zd ZdS )AuthorizationCodeGranta  The authorization code grant type is used to obtain both access
    tokens and refresh tokens and is optimized for confidential clients.
    Since this is a redirection-based flow, the client must be capable of
    interacting with the resource owner's user-agent (typically a web
    browser) and capable of receiving incoming requests (via redirection)
    from the authorization server::

        +----------+
        | Resource |
        |   Owner  |
        |          |
        +----------+
             ^
             |
            (B)
        +----|-----+          Client Identifier      +---------------+
        |         -+----(A)-- & Redirection URI ---->|               |
        |  User-   |                                 | Authorization |
        |  Agent  -+----(B)-- User authenticates --->|     Server    |
        |          |                                 |               |
        |         -+----(C)-- Authorization Code ---<|               |
        +-|----|---+                                 +---------------+
          |    |                                         ^      v
         (A)  (C)                                        |      |
          |    |                                         |      |
          ^    v                                         |      |
        +---------+                                      |      |
        |         |>---(D)-- Authorization Code ---------'      |
        |  Client |          & Redirection URI                  |
        |         |                                             |
        |         |<---(E)----- Access Token -------------------'
        +---------+       (w/ Optional Refresh Token)
    client_secret_basicclient_secret_post0   codeauthorization_codec                      t          |           S )a  The client constructs the request URI by adding the following
        parameters to the query component of the authorization endpoint URI
        using the "application/x-www-form-urlencoded" format.
        Per `Section 4.1.1`_.

        response_type
             REQUIRED.  Value MUST be set to "code".

        client_id
            REQUIRED.  The client identifier as described in Section 2.2.

        redirect_uri
            OPTIONAL.  As described in Section 3.1.2.

        scope
            OPTIONAL.  The scope of the access request as described by
            Section 3.3.

        state
             RECOMMENDED.  An opaque value used by the client to maintain
             state between the request and callback.  The authorization
             server includes this value when redirecting the user-agent back
             to the client.  The parameter SHOULD be used for preventing
             cross-site request forgery as described in Section 10.12.

        The client directs the resource owner to the constructed URI using an
        HTTP redirection response, or by other means available to it via the
        user-agent.

        For example, the client directs the user-agent to make the following
        HTTP request using TLS (with extra line breaks for display purposes
        only):

        .. code-block:: http

            GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
            &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
            Host: server.example.com

        The authorization server validates the request to ensure that all
        required parameters are present and valid.  If the request is valid,
        the authorization server authenticates the resource owner and obtains
        an authorization decision (by asking the resource owner or by
        establishing approval via other means).

        .. _`Section 4.1.1`: https://tools.ietf.org/html/rfc6749#section-4.1.1
        )#validate_code_authorization_requestselfs    d/var/www/piapp/venv/lib/python3.11/site-packages/authlib/oauth2/rfc6749/grants/authorization_code.pyvalidate_authorization_requestz5AuthorizationCodeGrant.validate_authorization_request<   s    ` 34888    redirect_uric                 J   |st          | j        j        |          || j        _        |                                 }|                     || j                   d|fg}| j        j        r!|                    d| j        j        f           t          ||          }d|fg}dd|fS )a'  If the resource owner grants the access request, the authorization
        server issues an authorization code and delivers it to the client by
        adding the following parameters to the query component of the
        redirection URI using the "application/x-www-form-urlencoded" format.
        Per `Section 4.1.2`_.

        code
            REQUIRED.  The authorization code generated by the
            authorization server. The authorization code MUST expire
            shortly after it is issued to mitigate the risk of leaks. A
            maximum authorization code lifetime of 10 minutes is
            RECOMMENDED. The client MUST NOT use the authorization code
            more than once. If an authorization code is used more than
            once, the authorization server MUST deny the request and SHOULD
            revoke (when possible) all tokens previously issued based on
            that authorization code.  The authorization code is bound to
            the client identifier and redirection URI.
        state
            REQUIRED if the "state" parameter was present in the client
            authorization request.  The exact value received from the
            client.

        For example, the authorization server redirects the user-agent by
        sending the following HTTP response.

        .. code-block:: http

            HTTP/1.1 302 Found
            Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA
                   &state=xyz

        .. _`Section 4.1.2`: https://tools.ietf.org/html/rfc6749#section-4.1.2

        :param redirect_uri: Redirect to the given URI for the authorization
        :param grant_user: if resource owner granted the request, pass this
            resource owner, otherwise pass None.
        :returns: (status_code, body, headers)
        stater   r   r!   Locationi.   )r   requestr!   usergenerate_authorization_codesave_authorization_codeappendr   )r   r   
grant_userr   paramsuriheaderss          r   create_authorization_responsez4AuthorizationCodeGrant.create_authorization_responsen   s    N  	Y#$,*<<XXXX&//11$$T4<8884.!< 	9MM7DL$67888f55$%Br   c                 t   |                                  }t                              d|           |                    | j                  st          d| j         d          | j        j                            d          }|t          d          | 
                    ||          }|st          d          t                              d|           | j        j        }|                                }|r||k    rt          d	          || j        _        || j        _        |                     d
           dS )a  The client makes a request to the token endpoint by sending the
        following parameters using the "application/x-www-form-urlencoded"
        format per `Section 4.1.3`_:

        grant_type
             REQUIRED.  Value MUST be set to "authorization_code".

        code
             REQUIRED.  The authorization code received from the
             authorization server.

        redirect_uri
             REQUIRED, if the "redirect_uri" parameter was included in the
             authorization request as described in Section 4.1.1, and their
             values MUST be identical.

        client_id
             REQUIRED, if the client is not authenticating with the
             authorization server as described in Section 3.2.1.

        If the client type is confidential or the client was issued client
        credentials (or assigned other authentication requirements), the
        client MUST authenticate with the authorization server as described
        in Section 3.2.1.

        For example, the client makes the following HTTP request using TLS:

        .. code-block:: http

            POST /token HTTP/1.1
            Host: server.example.com
            Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
            Content-Type: application/x-www-form-urlencoded

            grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
            &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb

        .. _`Section 4.1.3`: https://tools.ietf.org/html/rfc6749#section-4.1.3
        zValidate token request of %rz0The client is not authorized to use "grant_type="r   NzMissing "code" in request.zInvalid "code" in request.z!Validate token redirect_uri of %rz"Invalid "redirect_uri" in request.after_validate_token_request)"authenticate_token_endpoint_clientlogdebugcheck_grant_type
GRANT_TYPEr   r$   formgetr   query_authorization_coder   r   get_redirect_uriclientr   execute_hook)r   r:   r   r   r   original_redirect_uris         r   validate_token_requestz-AuthorizationCodeGrant.validate_token_request   sN   X 88::		0&999&&t77 	W)U4?UUUW W W | $$V,,<%&BCCC
 "::4HH! 	B#$@AAA 			5v>>>|0 2 C C E E  	J\5J%J%J#$HIII %*<'899999r   c                    | j         j        }| j         j        }|                     |          }|st	          d          || j         _        |                                }|                     |||                    d                    }t          
                    d||           |                     |           |                     d|           |                     |           d|| j        fS )a  If the access token request is valid and authorized, the
        authorization server issues an access token and optional refresh
        token as described in Section 5.1.  If the request client
        authentication failed or is invalid, the authorization server returns
        an error response as described in Section 5.2. Per `Section 4.1.4`_.

        An example successful response:

        .. code-block:: http

            HTTP/1.1 200 OK
            Content-Type: application/json
            Cache-Control: no-store
            Pragma: no-cache

            {
                "access_token":"2YotnFZFEjr1zCsicMWpAA",
                "token_type":"example",
                "expires_in":3600,
                "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
                "example_parameter":"example_value"
            }

        :returns: (status_code, body, headers)

        .. _`Section 4.1.4`: https://tools.ietf.org/html/rfc6749#section-4.1.4
        z!There is no "user" for this code.refresh_token)r%   scopeinclude_refresh_tokenzIssue token %r to %rprocess_token)token   )r$   r:   r   authenticate_userr   r%   	get_scoper   r4   r2   r3   
save_tokenr;   delete_authorization_codeTOKEN_RESPONSE_HEADER)r   r:   r   r%   r@   rC   s         r   create_token_responsez,AuthorizationCodeGrant.create_token_response   s    8 $!\<%%&899 	I#$GHHH ",,..##"("9"9/"J"J $ 
 

 			(%888/777&&'9:::E4555r   c                 *    t          | j                  S )a  "The method to generate "code" value for authorization code data.
        Developers may rewrite this method, or customize the code length with::

            class MyAuthorizationCodeGrant(AuthorizationCodeGrant):
                AUTHORIZATION_CODE_LENGTH = 32  # default is 48
        )r   AUTHORIZATION_CODE_LENGTHr   s    r   r&   z2AuthorizationCodeGrant.generate_authorization_code  s     d<===r   c                     t                      )a  Save authorization_code for later use. Developers MUST implement
        it in subclass. Here is an example::

            def save_authorization_code(self, code, request):
                client = request.client
                item = AuthorizationCode(
                    code=code,
                    client_id=client.client_id,
                    redirect_uri=request.redirect_uri,
                    scope=request.scope,
                    user_id=request.user.id,
                )
                item.save()
        NotImplementedError)r   r   r$   s      r   r'   z.AuthorizationCodeGrant.save_authorization_code(  s     "###r   c                     t                      )a  Get authorization_code from previously savings. Developers MUST
        implement it in subclass::

            def query_authorization_code(self, code, client):
                return Authorization.get(code=code, client_id=client.client_id)

        :param code: a string represent the code.
        :param client: client related to this code.
        :return: authorization_code object
        rN   )r   r   r:   s      r   r8   z/AuthorizationCodeGrant.query_authorization_code9  s     "###r   c                     t                      )a,  Delete authorization code from database or cache. Developers MUST
        implement it in subclass, e.g.::

            def delete_authorization_code(self, authorization_code):
                authorization_code.delete()

        :param authorization_code: the instance of authorization_code
        rN   r   r   s     r   rH   z0AuthorizationCodeGrant.delete_authorization_codeF  s     "###r   c                     t                      )aQ  Authenticate the user related to this authorization_code. Developers
        MUST implement this method in subclass, e.g.::

            def authenticate_user(self, authorization_code):
                return User.get(authorization_code.user_id)

        :param authorization_code: AuthorizationCode object
        :return: user
        rN   rR   s     r   rE   z(AuthorizationCodeGrant.authenticate_userQ  s     "###r   N)__name__
__module____qualname____doc__TOKEN_ENDPOINT_AUTH_METHODSrL   RESPONSE_TYPESr5   r   strr-   r=   rJ   r&   r'   r8   rH   rE    r   r   r   r      s           D $9:N"O !#XN%J09 09 09d4 # 4  4  4  4 lH: H: H:T/6 /6 /6b> > >$ $ $"$ $ $	$ 	$ 	$
$ 
$ 
$ 
$ 
$r   r   c                 0   | j         }|j        }t                              d|           |t	          |j                  | j                            |          }|st	          |j                  |                     ||          }|j	        }|
                    |          s t          d| d| j         j        |          	 || j         _        |                                  |                     d           n# t          $ r}||_        |d }~ww xY w|S )Nz$Validate authorization request of %r)r!   z3The client is not authorized to use "response_type=r/   r    $after_validate_authorization_request)r$   	client_idr2   r3   r   r!   serverquery_client#validate_authorization_redirect_uriresponse_typecheck_response_typer   r:   validate_requested_scoper;   r
   r   )grantr$   r^   r:   r   rb   errors          r   r   r   ^  s?   mG!III4i@@@ w}5555\&&y11F 6 w}5555<<WfMML)M%%m44 
%R-RRR-%%
 
 
 	
%&&(((ABBBB   ) s   5C; ;
D	DD)loggingauthlib.common.urlsr   authlib.common.securityr   baser   r   r   errorsr
   r   r   r   r   r   	getLoggerrT   r2   r   r   r[   r   r   <module>rm      s    1 1 1 1 1 1 2 2 2 2 2 2 K K K K K K K K K K                g!!J$ J$ J$ J$ J$Y(BDV J$ J$ J$Z
    r   