o
    ^[2h:                     @   s   d dl 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 ddlmZ dd	lm	Z	 dd
lm
Z
 ddlmZ e eZdZG dd dee	ZdS )    N)	JoseError)jwt   )	BaseGrant)InvalidClientError)InvalidGrantError)InvalidRequestError)TokenEndpointMixin)UnauthorizedClientError   sign_jwt_bearer_assertionz+urn:ietf:params:oauth:grant-type:jwt-bearerc                   @   s   e Zd ZeZddiddiddidZdZe				dddZdd	 Z	d
d Z
dd Zdd Zdd Zdd Zdd Zdd ZdS )JWTBearerGrant	essentialT)issaudexp<   Nc                 K   s   t | ||||||fi |S )Nr   )keyissueraudiencesubject	issued_at
expires_atclaimskwargs r   r/home/skpark/git/infrasmart_work/infrasmart/venv/lib/python3.10/site-packages/authlib/oauth2/rfc7523/jwt_bearer.pysign!   s
   zJWTBearerGrant.signc              
   C   s\   zt j|| j| jd}|j| jd W |S  ty- } ztd| t	|j
d|d}~ww )a#  Extract JWT payload claims from request "assertion", per
        `Section 3.1`_.

        :param assertion: assertion string value in the request
        :return: JWTClaims
        :raise: InvalidGrantError

        .. _`Section 3.1`: https://tools.ietf.org/html/rfc7523#section-3.1
        )claims_options)leewayzAssertion Error: %rdescriptionN)r   decoderesolve_public_keyCLAIMS_OPTIONSvalidateLEEWAYr   logdebugr   r"   )self	assertionr   er   r   r   process_assertion_claims0   s   

z'JWTBearerGrant.process_assertion_claimsc                 C   s   |  |d }| |||S )Nr   )resolve_issuer_clientresolve_client_key)r*   headerspayloadclientr   r   r   r$   D   s   z!JWTBearerGrant.resolve_public_keyc                 C   s   | j jd}|std| |}| |d }td| || j	s.t
d| j	 d|| j _|   |d}|ra| |}|sItdd	td
|| | ||s[tdd	|| j _dS 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 2.1`_:

        grant_type
             REQUIRED.  Value MUST be set to
             "urn:ietf:params:oauth:grant-type:jwt-bearer".

        assertion
             REQUIRED.  Value MUST contain a single JWT.

        scope
            OPTIONAL.

        The following example demonstrates an access token request with a JWT
        as an authorization grant:

        .. code-block:: http

            POST /token.oauth2 HTTP/1.1
            Host: as.example.com
            Content-Type: application/x-www-form-urlencoded

            grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer
            &assertion=eyJhbGciOiJFUzI1NiIsImtpZCI6IjE2In0.
            eyJpc3Mi[...omitted for brevity...].
            J9l-ZhwP[...omitted for brevity...]

        .. _`Section 2.1`: https://tools.ietf.org/html/rfc7523#section-2.1
        r+   zMissing 'assertion' in requestr   zValidate token request of %sz0The client is not authorized to use 'grant_type='subz Invalid 'sub' value in assertionr!   z'Check client(%s) permission to User(%s)z,Client has no permission to access user dataN)requestformgetr   r-   r.   r(   r)   check_grant_type
GRANT_TYPEr
   r2   validate_requested_scopeauthenticate_userr   has_granted_permissionr   user)r*   r+   r   r2   r   r=   r   r   r   validate_token_requestH   s0   



z%JWTBearerGrant.validate_token_requestc                 C   sB   | j | jjj| jjdd}td|| jj | | d|| j	fS )zZIf valid and authorized, the authorization server issues an access
        token.
        F)scoper=   include_refresh_tokenzIssue token %r to %r   )
generate_tokenr5   r1   r?   r=   r(   r)   r2   
save_tokenTOKEN_RESPONSE_HEADER)r*   tokenr   r   r   create_token_response   s   
z$JWTBearerGrant.create_token_responsec                 C      t  )a1  Fetch client via "iss" in assertion claims. Developers MUST
        implement this method in subclass, e.g.::

            def resolve_issuer_client(self, issuer):
                return Client.query_by_iss(issuer)

        :param issuer: "iss" value in assertion
        :return: Client instance
        NotImplementedError)r*   r   r   r   r   r.         
z$JWTBearerGrant.resolve_issuer_clientc                 C   rG   )au  Resolve client key to decode assertion data. Developers MUST
        implement this method in subclass. For instance, there is a
        "jwks" column on client table, e.g.::

            def resolve_client_key(self, client, headers, payload):
                # from authlib.jose import JsonWebKey

                key_set = JsonWebKey.import_key_set(client.jwks)
                return key_set.find_by_kid(headers["kid"])

        :param client: instance of OAuth client model
        :param headers: headers part of the JWT
        :param payload: payload part of the JWT
        :return: ``authlib.jose.Key`` instance
        rH   )r*   r2   r0   r1   r   r   r   r/      s   z!JWTBearerGrant.resolve_client_keyc                 C   rG   )a%  Authenticate user with the given assertion claims. Developers MUST
        implement it in subclass, e.g.::

            def authenticate_user(self, subject):
                return User.get_by_sub(subject)

        :param subject: "sub" value in claims
        :return: User instance
        rH   )r*   r   r   r   r   r;      rJ   z JWTBearerGrant.authenticate_userc                 C   rG   )a  Check if the client has permission to access the given user's resource.
        Developers MUST implement it in subclass, e.g.::

            def has_granted_permission(self, client, user):
                permission = ClientUserGrant.query(client=client, user=user)
                return permission.granted

        :param client: instance of OAuth client model
        :param user: instance of User model
        :return: bool
        rH   )r*   r2   r=   r   r   r   r<      s   z%JWTBearerGrant.has_granted_permission)NNNN)__name__
__module____qualname__JWT_BEARER_GRANT_TYPEr9   r%   r'   staticmethodr   r-   r$   r>   rF   r.   r/   r;   r<   r   r   r   r   r      s*    <r   )loggingauthlib.joser   r   rfc6749r   r   r   r   r	   r
   r+   r   	getLoggerrK   r(   rN   r   r   r   r   r   <module>   s    
