a
    !f$                     @   s   d Z ddlZddl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mZmZmZ ejded	d
 G dd deZdddZedZdd Zdde ddfddZdd ZdS )z9
Functions for generating and verifying JSON Web Tokens.
    N)datetime	timedelta)timegm)urandom)JWSJWSHeaderRegistry)base64url_encodebase64url_decodejson_encodejson_decodez#The python_jwt module is deprecated   )
stacklevelc                   @   s   e Zd ZdZdS )	_JWTErrorzu Exception raised if claim doesn't pass. Private to this module because
        jwcrypto throws many exceptions too. N)__name__
__module____qualname____doc__ r   r   T/var/www/html/python-backend/venv/lib/python3.9/site-packages/python_jwt/__init__.pyr      s   r   PS512   c                 C   s0  d|r
|ndd}|durTt | t | @ }	|	rJtdd|	|| t| } t }
|rxt	t
|| d< t|p|
 | d< t|
 | d	< |rt|
|  | d
< n|rt| | d
< |d dkrd}n6tt| }|d g|_|j||d t| d }dt	t|t	t| |f S )aK  
    Generate a JSON Web Token.

    :param claims: The claims you want included in the signature.
    :type claims: dict

    :param priv_key: The private key to be used to sign the token. Note: if you pass ``None`` then the token will be returned with an empty cryptographic signature and :obj:`algorithm` will be forced to the value ``none``.
    :type priv_key: `jwcrypto.jwk.JWK <https://jwcrypto.readthedocs.io/en/latest/jwk.html>`_

    :param algorithm: The algorithm to use for generating the signature. ``RS256``, ``RS384``, ``RS512``, ``PS256``, ``PS384``, ``PS512``, ``ES256``, ``ES384``, ``ES512``, ``HS256``, ``HS384``, ``HS512`` and ``none`` are supported.
    :type algorithm: str

    :param lifetime: How long the token is valid for.
    :type lifetime: datetime.timedelta

    :param expires: When the token expires (if :obj:`lifetime` isn't specified)
    :type expires: datetime.datetime

    :param not_before: When the token is valid from. Defaults to current time (if ``None`` is passed).
    :type not_before: datetime.datetime

    :param jti_size: Size in bytes of the unique token ID to put into the token (can be used to detect replay attacks). Defaults to 16 (128 bits). Specify 0 or ``None`` to omit the JTI from the token.
    :type jti_size: int

    :param other_headers: Any headers other than "typ" and "alg" may be specified, they will be included in the header.
    :type other_headers: dict

    :rtype: unicode
    :returns: The JSON Web Token. Note this includes a header, the claims and a cryptographic signature. The following extra claims are added, per the `JWT spec <http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html>`_:

    - **exp** (*IntDate*) -- The UTC expiry date and time of the token, in number of seconds from 1970-01-01T0:0:0Z UTC.
    - **iat** (*IntDate*) -- The UTC date and time at which the token was generated.
    - **nbf** (*IntDate*) -- The UTC valid-from date and time of the token.
    - **jti** (*str*) -- A unique identifier for the token.

    :raises:
        ValueError: If other_headers contains either the "typ" or "alg" header
    JWTnone)typalgNz*other_headers re-specified the headers: {}z, Zjtinbfiatexpr    )Z	protected	signaturez%s.%s.%s)setkeys
ValueErrorformatjoinupdatedictr   utcnowr   r   r   utctimetupler   r
   allowed_algsZadd_signaturer   	serialize)claimsZpriv_key	algorithmZlifetimeexpiresZ
not_beforeZjti_sizeZother_headersheaderZredefined_keysnowr   tokenr   r   r   generate_jwt   s:    +



r1   z3^[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]*$c                 C   s   t | stdd S )Nzinvalid JWT format)_jwt_rematchr   )jwtr   r   r   _check_jwt_formatj   s    
r5   Fc                 C   s  t |  |du rg }t|ts&td| d\}}}tt|}	|	d}
|
du r\td|
|vrptd|
 |s|	D ].}|tvrtd| t| j	sxtd| qx|rt
 }||_|| | t|j}nd	|vrtd
ntt|}t }t| }|	d}|du r&|s8tdn|dkr8td|d}|du r\|sztdn|t||  krztd|d}|du r|stdn||krtd|d}|du r|stdn||krtd|	|fS )a  
    Verify a JSON Web Token.

    :param jwt: The JSON Web Token to verify.
    :type jwt: str or unicode

    :param pub_key: The public key to be used to verify the token. Note: if you pass ``None`` and **allowed_algs** contains ``none`` then the token's signature will not be verified.
    :type pub_key: `jwcrypto.jwk.JWK <https://jwcrypto.readthedocs.io/en/latest/jwk.html>`_

    :param allowed_algs: Algorithms expected to be used to sign the token. The ``in`` operator is used to test membership.
    :type allowed_algs: list or NoneType (meaning an empty list)

    :param iat_skew: The amount of leeway to allow between the issuer's clock and the verifier's clock when verifying that the token was generated in the past. Defaults to no leeway.
    :type iat_skew: datetime.timedelta

    :param checks_optional: If ``False``, then the token must contain the **typ** header property and the **iat**, **nbf** and **exp** claim properties.
    :type checks_optional: bool

    :param ignore_not_implemented: If ``False``, then the token must *not* contain the **jku**, **jwk**, **x5u**, **x5c** or **x5t** header properties.
    :type ignore_not_implemented: bool

    :rtype: tuple
    :returns: ``(header, claims)`` if the token was verified successfully. The token must pass the following tests:

    - Its header must contain a property **alg** with a value in **allowed_algs**.
    - Its signature must verify using **pub_key** (unless its algorithm is ``none`` and ``none`` is in **allowed_algs**).
    - If the corresponding property is present or **checks_optional** is ``False``:

      - Its header must contain a property **typ** with the value ``JWT``.
      - Its claims must contain a property **iat** which represents a date in the past (taking into account :obj:`iat_skew`).
      - Its claims must contain a property **nbf** which represents a date in the past.
      - Its claims must contain a property **exp** which represents a date in the future.

    :raises: If the token failed to verify.
    Nzallowed_algs must be a list.r   zalg header not presentzalgorithm not allowed: zunknown header: zheader not implemented: r   zno key but none alg not allowedr   ztyp header not presentr   ztyp header is not JWTr   ziat claim not presentzissued in the futurer   znbf claim not presentznot yet validr   zexp claim not presentZexpired)r5   
isinstancelistr   splitr   r	   getr   	supportedr   r)   Zdeserializepayloadr   r'   r   r(   )r4   Zpub_keyr)   Ziat_skewZchecks_optionalZignore_not_implementedr.   r+   _parsed_headerr   kr0   parsed_claimsr'   r/   r   r   r   r   r   r   r   
verify_jwtn   sj    +


















rA   c                 C   s8   t |  | d\}}}tt|}tt|}||fS )a  
    Process a JSON Web Token without verifying it.

    Call this before :func:`verify_jwt` if you need access to the header or claims in the token before verifying it. For example, the claims might identify the issuer such that you can retrieve the appropriate public key.

    :param jwt: The JSON Web Token to verify.
    :type jwt: str or unicode

    :rtype: tuple
    :returns: ``(header, claims)``
    r6   )r5   r9   r   r	   )r4   r.   r+   r=   r>   r@   r   r   r   process_jwt   s
    rB   )Nr   NNNr   N)r   warningsrer   r   calendarr   osr   Zjwcrypto.jwsr   r   Zjwcrypto.commonr   r	   r
   r   warnDeprecationWarning	Exceptionr   r1   compiler2   r5   rA   rB   r   r   r   r   <module>   s.       
T

r