o
    6hD                     @   sl  d dl Z d dlmZ zd dlmZ W n ey!   d dlmZ Y nw zd dlmZmZm	Z	 e
eZW n eyO   d dlmZm	Z	mZ e
ejZejZY nw d dl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 ejddfddZd'ddZdd Zdd Zdd Zdd Z d(ddZ!d(ddZ"d)ddZ#d)ddZ$d)dd Z%d!d" Z&d#d$ Z'd'd%d&Z(dS )*    N)timegm)Mapping)UTCdatetime	timedelta)r   r   timezone)jws   )
ALGORITHMS)ExpiredSignatureErrorJWSErrorJWTClaimsErrorJWTError)calculate_at_hashtimedelta_total_secondsc                 C   sX   dD ]}t | |trt| |  | |< q|r#t|tj| | d< tj	| |||dS )ab  Encodes a claims set and returns a JWT string.

    JWTs are JWS signed objects with a few reserved claims.

    Args:
        claims (dict): A claims set to sign
        key (str or dict): The key to use for signing the claim set. Can be
            individual JWK or JWK set.
        algorithm (str, optional): The algorithm to use for signing the
            the claims.  Defaults to HS256.
        headers (dict, optional): A set of headers that will be added to
            the default headers.  Any headers that are added as additional
            headers will override the default headers.
        access_token (str, optional): If present, the 'at_hash' claim will
            be calculated and added to the claims present in the 'claims'
            parameter.

    Returns:
        str: The string representation of the header, claims, and signature.

    Raises:
        JWTError: If there is an error encoding the claims.

    Examples:

        >>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'

    )expiatnbfat_hash)headers	algorithm)

isinstancegetr   r   utctimetupler   r
   HASHESr   sign)claimskeyr   r   access_token
time_claim r    \/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/jose/jwt.pyencode   s   r"   c              
   C   s8  i ddddddddddddddd	dd
dddddddddddddddddddi}|r@| | |dd}	ztj| |||	d}
W n tya } zt|d}~ww t| d }z
t|
	d}W n t
y } ztd| d}~ww t|tstdt|||||||d |S )a	  Verifies a JWT string's signature and validates reserved claims.

    Args:
        token (str): A signed JWS to be verified.
        key (str or dict): A key to attempt to verify the payload with. Can be
            individual JWK or JWK set.
        algorithms (str or list): Valid algorithms that should be used to verify the JWS.
        audience (str): The intended audience of the token.  If the "aud" claim is
            included in the claim set, then the audience must be included and must equal
            the provided claim.
        issuer (str or iterable): Acceptable value(s) for the issuer of the token.
            If the "iss" claim is included in the claim set, then the issuer must be
            given and the claim in the token must be among the acceptable values.
        subject (str): The subject of the token.  If the "sub" claim is
            included in the claim set, then the subject must be included and must equal
            the provided claim.
        access_token (str): An access token string. If the "at_hash" claim is included in the
            claim set, then the access_token must be included, and it must match
            the "at_hash" claim.
        options (dict): A dictionary of options for skipping validation steps.

            defaults = {
                'verify_signature': True,
                'verify_aud': True,
                'verify_iat': True,
                'verify_exp': True,
                'verify_nbf': True,
                'verify_iss': True,
                'verify_sub': True,
                'verify_jti': True,
                'verify_at_hash': True,
                'require_aud': False,
                'require_iat': False,
                'require_exp': False,
                'require_nbf': False,
                'require_iss': False,
                'require_sub': False,
                'require_jti': False,
                'require_at_hash': False,
                'leeway': 0,
            }

    Returns:
        dict: The dict representation of the claims set, assuming the signature is valid
            and all requested data validation passes.

    Raises:
        JWTError: If the signature is invalid in any way.
        ExpiredSignatureError: If the signature has expired.
        JWTClaimsError: If any claim is invalid in any way.

    Examples:

        >>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
        >>> jwt.decode(payload, 'secret', algorithms='HS256')

    verify_signatureT
verify_aud
verify_iat
verify_exp
verify_nbf
verify_iss
verify_sub
verify_jtiverify_at_hashrequire_audFrequire_iatrequire_exprequire_nbfrequire_issrequire_subrequire_jtirequire_at_hashleewayr   )verifyNalgutf-8zInvalid payload string: %sz-Invalid payload string: must be a json object)audienceissuersubjectr   r   options)updater   r   r5   r   r   get_unverified_headerjsonloadsdecode
ValueErrorr   r   _validate_claims)tokenr   
algorithmsr;   r8   r9   r:   r   defaultsr#   payloader   r   r    r    r!   r@   D   s   ;	



r@   c                 C   s(   zt | }W |S  ty   tdw )a!  Returns the decoded headers without verification of any kind.

    Args:
        token (str): A signed JWT to decode the headers from.

    Returns:
        dict: The dict representation of the token headers.

    Raises:
        JWTError: If there is an exception decoding the token.
    zError decoding token headers.)r   get_unverified_headers	Exceptionr   )rC   r   r    r    r!   r=      s   r=   c                 C   s   t | S )a{  Returns the decoded headers without verification of any kind.

    This is simply a wrapper of get_unverified_header() for backwards
    compatibility.

    Args:
        token (str): A signed JWT to decode the headers from.

    Returns:
        dict: The dict representation of the token headers.

    Raises:
        JWTError: If there is an exception decoding the token.
    )r=   )rC   r    r    r!   rH      s   rH   c              
   C   sv   zt | }W n ty   tdw z
t|d}W n ty/ } ztd| d}~ww t|t	s9td|S )a  Returns the decoded claims without verification of any kind.

    Args:
        token (str): A signed JWT to decode the headers from.

    Returns:
        dict: The dict representation of the token claims.

    Raises:
        JWTError: If there is an exception decoding the token.
    zError decoding token claims.r7   zInvalid claims string: %sNz,Invalid claims string: must be a json object)
r   get_unverified_claimsrI   r   r>   r?   r@   rA   r   r   )rC   r   rG   r    r    r!   rJ      s   
rJ   c                 C   s6   d| vrdS z	t | d  W dS  ty   tdw )ae  Validates that the 'iat' claim is valid.

    The "iat" (issued at) claim identifies the time at which the JWT was
    issued.  This claim can be used to determine the age of the JWT.  Its
    value MUST be a number containing a NumericDate value.  Use of this
    claim is OPTIONAL.

    Args:
        claims (dict): The claims dictionary to validate.
    r   Nz)Issued At claim (iat) must be an integer.)intrA   r   r   r    r    r!   _validate_iat   s   rM   c                 C   s^   d| vrdS zt | d }W n ty   tdw ttt }||| kr-tddS )a  Validates that the 'nbf' claim is valid.

    The "nbf" (not before) claim identifies the time before which the JWT
    MUST NOT be accepted for processing.  The processing of the "nbf"
    claim requires that the current date/time MUST be after or equal to
    the not-before date/time listed in the "nbf" claim.  Implementers MAY
    provide for some small leeway, usually no more than a few minutes, to
    account for clock skew.  Its value MUST be a number containing a
    NumericDate value.  Use of this claim is OPTIONAL.

    Args:
        claims (dict): The claims dictionary to validate.
        leeway (int): The number of seconds of skew that is allowed.
    r   Nz*Not Before claim (nbf) must be an integer.z The token is not yet valid (nbf))rK   rA   r   r   r   nowr   r   )r   r4   r   rN   r    r    r!   _validate_nbf     rO   c                 C   s^   d| vrdS zt | d }W n ty   tdw ttt }||| k r-tddS )a  Validates that the 'exp' claim is valid.

    The "exp" (expiration time) claim identifies the expiration time on
    or after which the JWT MUST NOT be accepted for processing.  The
    processing of the "exp" claim requires that the current date/time
    MUST be before the expiration date/time listed in the "exp" claim.
    Implementers MAY provide for some small leeway, usually no more than
    a few minutes, to account for clock skew.  Its value MUST be a number
    containing a NumericDate value.  Use of this claim is OPTIONAL.

    Args:
        claims (dict): The claims dictionary to validate.
        leeway (int): The number of seconds of skew that is allowed.
    r   Nz/Expiration Time claim (exp) must be an integer.zSignature has expired.)	rK   rA   r   r   r   rN   r   r   r   )r   r4   r   rN   r    r    r!   _validate_exp+  rP   rQ   c                 C   sd   d| vrdS | d }t |tr|g}t |tstdtdd |D r(td||vr0tddS )a  Validates that the 'aud' claim is valid.

    The "aud" (audience) claim identifies the recipients that the JWT is
    intended for.  Each principal intended to process the JWT MUST
    identify itself with a value in the audience claim.  If the principal
    processing the claim does not identify itself with a value in the
    "aud" claim when this claim is present, then the JWT MUST be
    rejected.  In the general case, the "aud" value is an array of case-
    sensitive strings, each containing a StringOrURI value.  In the
    special case when the JWT has one audience, the "aud" value MAY be a
    single case-sensitive string containing a StringOrURI value.  The
    interpretation of audience values is generally application specific.
    Use of this claim is OPTIONAL.

    Args:
        claims (dict): The claims dictionary to validate.
        audience (str): The audience that is verifying the token.
    audNzInvalid claim format in tokenc                 s   s    | ]	}t |t V  qd S N)r   str).0cr    r    r!   	<genexpr>g  s    z _validate_aud.<locals>.<genexpr>zInvalid audience)r   rT   listr   any)r   r8   audience_claimsr    r    r!   _validate_audI  s   

r[   c                 C   s6   |durt |tr|f}| d|vrtddS dS )a  Validates that the 'iss' claim is valid.

    The "iss" (issuer) claim identifies the principal that issued the
    JWT.  The processing of this claim is generally application specific.
    The "iss" value is a case-sensitive string containing a StringOrURI
    value.  Use of this claim is OPTIONAL.

    Args:
        claims (dict): The claims dictionary to validate.
        issuer (str or iterable): Acceptable value(s) for the issuer that
                                  signed the token.
    NisszInvalid issuer)r   rT   r   r   )r   r9   r    r    r!   _validate_issm  s   
r]   c                 C   sH   d| vrdS t | d tstd|dur | d|kr"tddS dS )ao  Validates that the 'sub' claim is valid.

    The "sub" (subject) claim identifies the principal that is the
    subject of the JWT.  The claims in a JWT are normally statements
    about the subject.  The subject value MUST either be scoped to be
    locally unique in the context of the issuer or be globally unique.
    The processing of this claim is generally application specific.  The
    "sub" value is a case-sensitive string containing a StringOrURI
    value.  Use of this claim is OPTIONAL.

    Arg
        claims (dict): The claims dictionary to validate.
        subject (str): The subject of the token.
    subNzSubject must be a string.zInvalid subject)r   rT   r   r   )r   r:   r    r    r!   _validate_sub  s   r_   c                 C   s&   d| vrdS t | d tstddS )a  Validates that the 'jti' claim is valid.

    The "jti" (JWT ID) claim provides a unique identifier for the JWT.
    The identifier value MUST be assigned in a manner that ensures that
    there is a negligible probability that the same value will be
    accidentally assigned to a different data object; if the application
    uses multiple issuers, collisions MUST be prevented among values
    produced by different issuers as well.  The "jti" claim can be used
    to prevent the JWT from being replayed.  The "jti" value is a case-
    sensitive string.  Use of this claim is OPTIONAL.

    Args:
        claims (dict): The claims dictionary to validate.
    jtiNzJWT ID must be a string.)r   rT   r   rL   r    r    r!   _validate_jti  s
   ra   c              	   C   sh   d| vrdS |sd}t |z
t|tj| }W n ttfy'   d}t |w | d |kr2t ddS )a  
    Validates that the 'at_hash' is valid.

    Its value is the base64url encoding of the left-most half of the hash
    of the octets of the ASCII representation of the access_token value,
    where the hash algorithm used is the hash algorithm used in the alg
    Header Parameter of the ID Token's JOSE Header. For instance, if the
    alg is RS256, hash the access_token value with SHA-256, then take the
    left-most 128 bits and base64url encode them. The at_hash value is a
    case sensitive string.  Use of this claim is OPTIONAL.

    Args:
      claims (dict): The claims dictionary to validate.
      access_token (str): The access token returned by the OpenID Provider.
      algorithm (str): The algorithm used to sign the JWT, as specified by
          the token headers.
    r   Nz:No access_token provided to compare against at_hash claim.z;Unable to calculate at_hash to verify against token claims.z*at_hash claim does not match access_token.)r   r   r
   r   	TypeErrorrA   )r   r   r   msgexpected_hashr    r    r!   _validate_at_hash  s   re   c           
         s*    dd}t|trt|} fdd  D }|D ]}	|	| vr(td|	 d d|	 < qt|tftd fs=td  d	rFt|    d
rQt	| |d   dr\t
| |d   drgt| |d   drrt| |d   dr}t| |d   drt|    drt| || d S d S )Nr4   r   c                    s.   g | ]}| d r | r|td d qS )require_N)
startswithlen)rU   rG   r;   r    r!   
<listcomp>  s   . z$_validate_claims.<locals>.<listcomp>z&missing required key "%s" among claimsTverify_z!audience must be a string or Noner%   r'   )r4   r&   r$   )r8   r(   )r9   r)   )r:   r*   r+   )r   r   r   r   keysr   rT   typerM   rO   rQ   r[   r]   r_   ra   re   )
r   r8   r9   r:   r   r   r;   r4   required_claimsrequire_claimr    ri   r!   rB     s6   








rB   )NNNNNN)r   rS   ))r>   calendarr   collections.abcr   ImportErrorcollectionsr   r   r   rN   utc_nowr   utcjoser   	constantsr
   
exceptionsr   r   r   r   utilsr   r   HS256r"   r@   r=   rH   rJ   rM   rO   rQ   r[   r]   r_   ra   re   rB   r    r    r    r!   <module>   sB    

*r



$
#