a
    !fZe                     @   s"  d dl Z d dlZd dlZd dlmZ d dlmZmZ d dl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 d	d
ddddddZdZG dd deZG dd deZG dd deZG dd deZG dd deZeG dd deZG dd deZG d d! d!ZdS )"    N)
deprecated)JWExceptionJWKeyNotFound)json_decodejson_encode)JWE)default_allowed_algs)JWKJWKSet)JWSZIssuerSubjectZAudiencezExpiration Timez
Not Beforez	Issued AtzJWT ID)isssubaudexpnbfiatjtiTc                       s"   e Zd ZdZd fdd	Z  ZS )
JWTExpiredznJSON Web Token is expired.

    This exception is raised when a token is expired according to its claims.
    Nc                    s>   d }|rt |}nd}|r*|dt | 7 }tt| | d S )NzToken expired {%s})strsuperr   __init__selfmessage	exceptionmsg	__class__ M/var/www/html/python-backend/venv/lib/python3.9/site-packages/jwcrypto/jwt.pyr   .   s    
zJWTExpired.__init__)NN__name__
__module____qualname____doc__r   __classcell__r    r    r   r!   r   (   s   r   c                       s"   e Zd ZdZd fdd	Z  ZS )JWTNotYetValidz~JSON Web Token is not yet valid.

    This exception is raised when a token is not valid yet according to its
    claims.
    Nc                    s>   d }|rt |}nd}|r*|dt | 7 }tt| | d S )NzToken not yet validr   )r   r   r(   r   r   r   r    r!   r   @   s    
zJWTNotYetValid.__init__)NNr"   r    r    r   r!   r(   9   s   r(   c                       s"   e Zd ZdZd fdd	Z  ZS )JWTMissingClaimsJSON Web Token claim is invalid.

    This exception is raised when a claim does not match the expected value.
    Nc                    s>   d }|rt |}nd}|r*|dt | 7 }tt| | d S NzInvalid Claim Valuer   )r   r   r)   r   r   r   r    r!   r   Q   s    
zJWTMissingClaim.__init__)NNr"   r    r    r   r!   r)   K   s   r)   c                       s"   e Zd ZdZd fdd	Z  ZS )JWTInvalidClaimValuer*   Nc                    s>   d }|rt |}nd}|r*|dt | 7 }tt| | d S r+   )r   r   r,   r   r   r   r    r!   r   b   s    
zJWTInvalidClaimValue.__init__)NNr"   r    r    r   r!   r,   \   s   r,   c                       s"   e Zd ZdZd fdd	Z  ZS )JWTInvalidClaimFormatzqJSON Web Token claim format is invalid.

    This exception is raised when a claim is not in a valid format.
    Nc                    s>   d }|rt |}nd}|r*|dt | 7 }tt| | d S )NzInvalid Claim Formatr   )r   r   r-   r   r   r   r    r!   r   s   s    
zJWTInvalidClaimFormat.__init__)NNr"   r    r    r   r!   r-   m   s   r-   c                       s"   e Zd ZdZd fdd	Z  ZS )JWTMissingKeyIDzJSON Web Token is missing key id.

    This exception is raised when trying to decode a JWT with a key set
    that does not have a kid value in its header.
    Nc                    s>   d }|rt |}nd}|r*|dt | 7 }tt| | d S )NzMissing Key IDr   )r   r   r.   r   r   r   r    r!   r      s    
zJWTMissingKeyID.__init__)NNr"   r    r    r   r!   r.   ~   s   r.   c                       s"   e Zd ZdZd fdd	Z  ZS )JWTMissingKeyzJSON Web Token is using a key not in the key set.

    This exception is raised if the key that was used is not available
    in the passed key set.
    Nc                    s>   d }|rt |}nd}|r*|dt | 7 }tt| | d S )NzMissing Keyr   )r   r   r/   r   r   r   r    r!   r      s    
zJWTMissingKey.__init__)NNr"   r    r    r   r!   r/      s   r/   c                   @   sx  e Zd ZdZdFddZedd Zejdd Zedd	 Zejd
d	 Zedd Z	e	jdd Z	edd Z
e
jdd Z
edd Zejdd ZdGddZedd Zej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)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 ZdHd9d:ZdId<d=Ze d>d? Z!d@dA Z"dBdC Z#dDdE Z$dS )JJWTzFJSON Web token object

    This object represent a generic token.
    Nc	           	      C   s   d| _ d| _d| _|| _d| _d| _d| _d| _d| _|| _	|rF|| _
|durT|| _|durt|durn| | || _|dur|| _|dur| || dS )a  Creates a JWT object.

        :param header: A dict or a JSON string with the JWT Header data.
        :param claims: A dict or a string with the JWT Claims data.
        :param jwt: a 'raw' JWT token
        :param key: A (:class:`jwcrypto.jwk.JWK`) key to deserialize
         the token. A (:class:`jwcrypto.jwk.JWKSet`) can also be used.
        :param algs: An optional list of allowed algorithms
        :param default_claims: An optional dict with default values for
         registered claims. A None value for NumericDate type claims
         will cause generation according to system time. Only the values
         from RFC 7519 - 4.1 are evaluated.
        :param check_claims: An optional dict of claims that must be
         present in the token, if the value is not None the claim must
         match exactly.
        :param expected_type: An optional string that defines what kind
         of token to expect when validating a deserialized token.
         Supported values: "JWS" or "JWE"
         If left to None the code will try to detect what the expected
         type is based on other parameters like 'algs' and will default
         to JWS if no hints are found. It has no effect on token creation.

        Note: either the header,claims or jwt,key parameters should be
        provided as a deserialization operation (which occurs if the jwt
        is provided) will wipe any header or claim provided by setting
        those obtained from the deserialization of the jwt token.

        Note: if check_claims is not provided the 'exp' and 'nbf' claims
        are checked if they are set on the token but not enforced if not
        set. Any other RFC 7519 registered claims are checked only for
        format conformance.
        N<   iX  F)_header_claims_token_algs_reg_claims_check_claims_leeway	_validitydeserializelog_expected_typeheader_check_check_claimsclaimsdeserialize)	r   r<   r>   jwtkeyZalgsZdefault_claimscheck_claimsexpected_typer    r    r!   r      s,    $
zJWT.__init__c                 C   s   | j d u rtd| j S )Nz'header' not set)r2   KeyErrorr   r    r    r!   r<      s    
z
JWT.headerc                 C   s@   t |trt|}n|}t|}|ddu r6td|| _d S )NZb64Fz8b64 header is invalid.JWTs cannot use unencoded payloads)
isinstancedictr   r   get
ValueErrorr2   )r   hehr    r    r!   r<      s    

c                 C   s   | j d u rtd| j S )Nz'claims' not set)r3   rD   rE   r    r    r!   r>      s    
z
JWT.claimsc                 C   sF   t |ts$| js|| _d S t|}n
t|}| | t|| _d S N)	rF   rG   r6   r3   r   copydeepcopy_add_default_claimsr   )r   datar    r    r!   r>     s    



c                 C   s   | j S rL   )r4   rE   r    r    r!   token  s    z	JWT.tokenc                 C   s2   t |tst |tst |tr&|| _ntdd S )Nz.Invalid token type, must be one of JWS,JWE,JWT)rF   r   r   r0   r4   	TypeError)r   tr    r    r!   rQ     s    c                 C   s   | j S rL   )r8   rE   r    r    r!   leeway  s    z
JWT.leewayc                 C   s   t || _d S rL   )intr8   )r   Zlwyr    r    r!   rT   !  s    c                 C   s   | j S rL   )r9   rE   r    r    r!   validity%  s    zJWT.validityc                 C   s   t || _d S rL   )rU   r9   r   vr    r    r!   rV   )  s    c                 C   s  | j d u rD| jrDt| jtdg r.d| _ nt| jtrDd| _ | j d u rh| jrhdt| jv rhd| _ | j d u r|d urt|t	r|
d}|dkrd| _ n|dkrd| _ ndt|trd }|D ],}|
d}|d u r|}q||krd } qq|dkrd| _ n|dkrd| _ | j d u rn|d urnt|t	r|
d}|rnt|tsZ|g}t|dd	grvd| _ nt|d
dgrnd| _ nt|trnd }d }|D ]}|
d}|rNt|ts|g}|d u r2t|dd	gr tdd	g}d}n0t|d
dgr&td
dg}d}n
d } qbnt||s^d } qbn|rd } qbq|rn|| _ | j d u rd| _ | j S )NZRSA1_5r   r   encusesigZkey_opssignverifyZencryptdecrypt)r;   r5   setissubsetjwe_algsjws_algsr2   r   rF   r	   rH   r
   list)r   rA   rZ   Zall_usekopsZall_opsttyper    r    r!   _expected_type_heuristics-  s    








zJWT._expected_type_heuristicsc                 C   s   | j d ur| j S |  S rL   )r;   rg   rE   r    r    r!   rC   u  s    
zJWT.expected_typec                 C   s   |dv r|| _ ntdd S )N)r   r   z%Invalid value, must be 'JWS' or 'JWE')r;   rI   rW   r    r    r!   rC     s    c                 C   s.   ||v rd S | j |d }|d ur*|||< d S rL   )r6   rH   )r   namer>   valr    r    r!   _add_optional_claim  s
    zJWT._add_optional_claimc                 C   s@   ||v rd S || j v r<| j | d u r.|||< n| j | ||< d S rL   )r6   )r   rh   r>   Zdefvalr    r    r!   _add_time_claim  s    

zJWT._add_time_claimc                 C   s*   d|v sd| j vrd S tt |d< d S )Nr   )r6   r   uuiduuid4r   r>   r    r    r!   _add_jti_claim  s    zJWT._add_jti_claimc                 C   s|   | j d u rd S tt }| d| | d| | d| | d||| j  | d|| | d|| | | d S )Nr   r   r   r   r   r   )r6   rU   timerj   rk   rV   ro   )r   r>   nowr    r    r!   rO     s    
zJWT._add_default_claimsc                 C   s8   ||vs|| d u rd S t || ts4td|f d S )N"Claim %s is not a StringOrURI type)rF   r   r-   r   rh   r>   r    r    r!   _check_string_claim  s    zJWT._check_string_claimc                 C   sh   ||vs|| d u rd S t || trHtdd |D rdtd|f nt || tsdtd|f d S )Nc                 s   s   | ]}t |t V  qd S rL   )rF   r   ).0claimr    r    r!   	<genexpr>      z3JWT._check_array_or_string_claim.<locals>.<genexpr>z'Claim %s contains non StringOrURI typesrr   )rF   rc   anyr-   r   rs   r    r    r!   _check_array_or_string_claim  s    z JWT._check_array_or_string_claimc              
   C   sb   ||vs|| d u rd S zt ||  W n4 ty\ } ztd|f |W Y d }~n
d }~0 0 d S )NzClaim %s is not an integer)rU   rI   r-   )r   rh   r>   er    r    r!   _check_integer_claim  s    zJWT._check_integer_claimc                 C   s"   ||| k rt d|||f d S )Nz#Expired at %d, time: %d(leeway: %d))r   r   rv   limitrT   r    r    r!   
_check_exp  s    zJWT._check_expc                 C   s"   ||| krt d|||f d S )Nz#Valid from %d, time: %d(leeway: %d))r(   r}   r    r    r!   
_check_nbf  s    zJWT._check_nbfc                 C   s   |  d| |  d| | d| | d| | d| | d| |  d| |  d| | jd u rd|v r| |d t | j d|v r| |d t | j d S 	Nr   r   r   r   r   r   r   typ)rt   rz   r|   r7   r   rp   r8   r   rn   r    r    r!   _check_default_claims  s    
zJWT._check_default_claimsc                 C   sd   |  d| |  d| | d| | d| | d| | d| |  d| |  d| d S r   )rt   rz   r|   )r   rB   r    r    r!   r=     s    zJWT._check_check_claimsc           	   
   C   sj  | j du rd S zt| j}t|ts*t W n: tyf } z"| j d urPtd|W Y d }~d S d }~0 0 | | | j d u rd S | j  D ]\}}||vrt	d|f |dv r|d ur||| krt
d|||| f q|dkrp|d urdt|| tr|| }n
|| g}t|tr(|}n|g}d}|D ]}||v r6d} qRq6|sdt
d||| |q|d	kr|d ur| || |d
 n| || t | j q|dkr|d ur| || |d
 n| || t | j q|dkr:|d urd| || || krdt
d||| |f q|d ur||| krt
d|||| f qd S )NFz4Claims check requested but claims is not a json dictzClaim %s is missing)r   r   r   z*Invalid '%s' value. Expected '%s' got '%s'r   Tz)Invalid '{}' value. Expected '{}' in '{}'r   r   r   r   z3Invalid '%s' value. '%s' does not normalize to '%s')r7   r   r>   rF   rG   rI   r-   r   itemsr)   r,   rc   formatr   rp   r8   r   norm_typ)	r   r>   r{   rh   valueZtclaimsZcclaimsfoundrX   r    r    r!   _check_provided_claims  s    





















zJWT._check_provided_claimsc                 C   s    |  }d|v r|S d| S d S )N/zapplication/)lower)r   ri   lcr    r    r!   r   6  s    zJWT.norm_typc                 C   s8   t | j}| jr| j|_|j|| jd || _d| _dS )a  Signs the payload.

        Creates a JWS token with the header as the JWS protected header and
        the claims as the payload. See (:class:`jwcrypto.jws.JWS`) for
        details on the exceptions that may be raised.

        :param key: A (:class:`jwcrypto.jwk.JWK`) key.
        )Z	protectedr   N)r   r>   r5   allowed_algsZadd_signaturer<   rQ   r;   r   rA   rS   r    r    r!   make_signed_token=  s    

zJWT.make_signed_tokenc                 C   s6   t | j| j}| jr| j|_|| || _d| _dS )a"  Encrypts the payload.

        Creates a JWE token with the header as the JWE protected header and
        the claims as the plaintext. See (:class:`jwcrypto.jwe.JWE`) for
        details on the exceptions that may be raised.

        :param key: A (:class:`jwcrypto.jwk.JWK`) key.
        r   N)r   r>   r<   r5   r   Zadd_recipientrQ   r;   r   r    r    r!   make_encrypted_tokenN  s    

zJWT.make_encrypted_tokenc              
   C   sb  g | _ | jdu rtd| |}d}t| jtrV|dkrLtrLtd|| jj	}n8t| jt
r|dkr|tr|td|| jj}ntdz|| | j d W n ty& } zft| jtr| jj| _ nt| jt
r| jj| _ | j d	t| t|trt | W Y d}~n
d}~0 0 | jj| _| jj}t|trP|d
}|| _|   dS )a  Validate a JWT token that was deserialized w/o providing a key

        :param key: A (:class:`jwcrypto.jwk.JWK`) verification or
         decryption key, or a (:class:`jwcrypto.jwk.JWKSet`) that
         contains a key indexed by the 'kid' header.
        NzToken emptyr   zExpected {}, got JWSr   zExpected {}, got JWEToken format unrecognizedZSuccesszValidation failed: [{}]zutf-8)r:   rQ   rI   rg   rF   r   JWT_expect_typerR   r   r]   r   r^   append	ExceptionZ	verifylogZ
decryptlogreprr   r/   Zjose_headerr<   payloadbytesdecoder>   r   )r   rA   etZvalidate_fnr{   r   r    r    r!   validate_  sD    






zJWT.validatec                 C   sl   | d}|dkrt | _n|dkr.t | _ntd| jrF| j| j_d| _| j|d |rh| 	| dS )aa  Deserialize a JWT token.

        NOTE: Destroys any current status and tries to import the raw
        token provided.

        :param jwt: a 'raw' JWT token.
        :param key: A (:class:`jwcrypto.jwk.JWK`) verification or
         decryption key, or a (:class:`jwcrypto.jwk.JWKSet`) that
         contains a key indexed by the 'kid' header.
        .      r   N)
countr   rQ   r   rI   r5   r   r:   r?   r   )r   r@   rA   rP   r    r    r!   r?     s    



zJWT.deserializeTc                 C   s   |st d| j|S )a  Serializes the object into a JWS token.

        :param compact(boolean): must be True.

        Note: the compact parameter is provided for general compatibility
        with the serialize() functions of :class:`jwcrypto.jws.JWS` and
        :class:`jwcrypto.jwe.JWE` so that these objects can all be used
        interchangeably. However the only valid JWT representation is the
        compact representation.

        :return: A json formatted string or a compact representation string
        :rtype: `str`
        z)Only the compact serialization is allowed)rI   rQ   	serialize)r   compactr    r    r!   r     s    zJWT.serializec                 C   s   |  }| | |S )a3  Creates a JWT object from a serialized JWT token.

        :param token: A string with the json or compat representation
         of the token.

        :raises InvalidJWEData or InvalidJWSObject: if the raw object is an
         invalid JWT token.

        :return: A JWT token
        :rtype: JWT
        )r?   )clsrQ   objr    r    r!   from_jose_token  s    
zJWT.from_jose_tokenc                 C   s2   t |tsdS | j|jko0| j|jko0| j|jkS )NF)rF   r0   r3   r2   rQ   )r   otherr    r    r!   __eq__  s    


z
JWT.__eq__c                 C   s*   z
|   W S  ty$   |   Y S 0 d S rL   )r   r   __repr__rE   r    r    r!   __str__  s    
zJWT.__str__c                 C   s\   t | j}d| j dd| j d d| d d| j d d| j d d| j d S )	NzJWT(header=z, zclaims=zjwt=zkey=None, algs=zdefault_claims=zcheck_claims=))r   rQ   r2   r3   r5   r6   r7   )r   r@   r    r    r!   r     s    

zJWT.__repr__)NNNNNNNN)N)N)T)%r#   r$   r%   r&   r   propertyr<   setterr>   rQ   rT   rV   rg   rC   rj   rk   ro   rO   rt   rz   r|   r   r   r   r=   r   r   r   r   r   r?   r   classmethodr   r   r   r   r    r    r    r!   r0      sj      
@










H


		
N.


r0   )rM   rp   rl   r   Zjwcrypto.commonr   r   r   r   Zjwcrypto.jwer   r   ra   Zjwcrypto.jwkr	   r
   Zjwcrypto.jwsr   rb   ZJWTClaimsRegistryr   r   r(   r)   r,   r-   r.   r/   r0   r    r    r    r!   <module>   s8   	