o
    M>S$                  
   @   s  d Z ddlm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 ddlmZ ddlmZ d	Zed
d Zedd Zdd Zdd Zdd Zdd Zdd ZdddddddedddZd*d d!ZG d"d# d#eZd*d$d%Z G d&d' d'eZ!G d(d) d)e"Z#dS )+z3
    flask_jwt
    ~~~~~~~~~

    Flask-JWT module
    )OrderedDict)	timedeltawraps)TimedJSONWebSignatureSerializerSignatureExpiredBadSignature)current_apprequestjsonify_request_ctx_stack)
MethodView)
LocalProxyz0.2.0c                   C   s   t tjdd S )Ncurrent_user)getattrr   top r   r   Y/home/www/bk.finsightngr.online/venv20/lib/python3.10/site-packages/flask_jwt/__init__.py<lambda>   s    r   c                   C   s
   t jd S )Njwt)r	   
extensionsr   r   r   r   r      s   
 c                  C   sH   t jd } t| trt|  } | t jd  }tt jd |t jd dS )NJWT_EXPIRATION_DELTA
JWT_LEEWAYJWT_SECRET_KEYJWT_ALGORITHM)Z
secret_key
expires_inZalgorithm_name)r	   config
isinstancer   inttotal_secondsr   )r   Zexpires_in_totalr   r   r   _get_serializer   s   

r    c                 C   s
   d| j iS )NZuser_id)id)userr   r   r   _default_payload_handler*   s   r#   c                 C   s   t  | dS )zReturn the encoded payload.zutf-8)r    dumpsdecodepayloadr   r   r   _default_encode_handler0   s   r(   c                 C   s4   z	t  | }W |S  ty   tjd r Y |S w )zReturn the decoded token.JWT_VERIFY_EXPIRATION)r    loadsr   r	   r   )tokenresultr   r   r   _default_decode_handler5   s   
r-   c                 C   s   t d| iS )z2Return a Flask response, given an encoded payload.r+   )r   r&   r   r   r   _default_response_handler?   s   r.   zLogin Requiredz/authr   ZHS256Ti,  )seconds)JWT_DEFAULT_REALMJWT_AUTH_URL_RULEJWT_AUTH_ENDPOINTr   Z
JWT_VERIFYr)   r   r   Nc                    s    fdd}|S )zuView decorator that requires a valid JWT token to be present in the request

    :param realm: an optional realm
    c                    s   t   fdd}|S )Nc                     s   t   | i |S N)
verify_jwt)argskwargs)fnrealmr   r   	decoratorU   s   z0jwt_required.<locals>.wrapper.<locals>.decoratorr   )r7   r9   r8   )r7   r   wrapperT   s   zjwt_required.<locals>.wrapperr   )r8   r;   r   r:   r   jwt_requiredO   s   r<   c                   @   s   e Zd ZdddZdS )JWTError  Nc                 C   s   || _ || _|| _|| _d S r3   )errordescriptionstatus_codeheaders)selfr?   r@   rA   rB   r   r   r   __init__^   s   
zJWTError.__init__)r>   N)__name__
__module____qualname__rD   r   r   r   r   r=   ]   s    r=   c                 C   s   | pt jd } tjdd}|du rtddddd|  i| }|d	  d
kr.tddt|dkr9tddt|dkrDtddzt	j
}||d }W n ty[   tdd tyf   tddw t	| tj_}|du rytdddS )a  Does the actual work of verifying the JWT data in the current request.
    This is done automatically for you by `jwt_required()` but you could call it manually.
    Doing so would be useful in the context of optional JWT access in your APIs.

    :param realm: an optional realm
    r0   ZAuthorizationNzAuthorization Requiredz Authorization header was missingi  zWWW-AuthenticatezJWT realm="%s"r   ZbearerzInvalid JWT headerzUnsupported authorization type   zToken missing   zToken contains spaceszInvalid JWTzToken is expiredzToken is undecipherablezUser does not exist)r	   r   r
   rB   getr=   splitlowerlen_jwtdecode_callbackr   r   user_callbackr   r   r   )r8   Zauthpartshandlerr'   r"   r   r   r   r4   e   s2   





r4   c                   @   s   e Zd Zdd ZdS )JWTAuthViewc                 C   s   t jdd}|dd }|dd }||t|dkg}t|s&tdddd	tj||d
}|r>t|}t	|}t
|S tdd)NT)forceusernamepasswordrI   zBad RequestzMissing required credentialsr>   )rA   )rU   rV   zInvalid credentials)r
   Zget_jsonrJ   rM   allr=   rN   authentication_callbackpayload_callbackencode_callbackresponse_callback)rC   datarU   rV   Z	criterionr"   r'   r+   r   r   r   post   s   



zJWTAuthView.postN)rE   rF   rG   r]   r   r   r   r   rS      s    rS   c                   @   sf   e Zd Z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d Zdd ZdS )JWTNc                 C   s<   |d ur|| _ | | nd | _ t| _t| _t| _t| _	d S r3   )
appinit_appr.   r[   r(   rZ   r-   rO   r#   rY   )rC   r_   r   r   r   rD      s   
zJWT.__init__c                 C   s   t  D ]\}}|j|| q|jd|jd  |jdd }|jdd }|r=|r=t|jd }|j|dg|d |t	| j
 t|dsMi |_| |jd< d S )	Nr   Z
SECRET_KEYr1   r2   ZPOST)methodsZ	view_funcr   r   )CONFIG_DEFAULTSitemsr   
setdefaultrJ   rS   Zas_viewZadd_url_ruleZerrorhandlerr=   _on_jwt_errorhasattrr   )rC   r_   kvZurl_ruleZendpointZ	auth_viewr   r   r   r`      s   
zJWT.init_appc                 C   s   t | d| j|S )Nerror_callback)r   _error_callbackrC   er   r   r   re      s   zJWT._on_jwt_errorc                 C   s.   t td|jfd|jfd|jfg|j|jfS )NrA   r?   r@   )r   r   rA   r?   r@   rB   rk   r   r   r   rj      s   zJWT._error_callbackc                 C   
   || _ |S )a
  Specifies the authentication handler function. This function receives two
        positional arguments. The first being the username the second being the password.
        It should return an object representing the authenticated user. Example::

            @jwt.authentication_handler
            def authenticate(username, password):
                if username == 'joe' and password == 'pass':
                    return User(id=1, username='joe')

        :param callback: the authentication handler function
        )rX   rC   callbackr   r   r   authentication_handler      zJWT.authentication_handlerc                 C   rm   )a  Specifies the user handler function. This function receives the token payload as
        its only positional argument. It should return an object representing the current
        user. Example::

            @jwt.user_handler
            def load_user(payload):
                if payload['user_id'] == 1:
                    return User(id=1, username='joe')

        :param callback: the user handler function
        )rP   rn   r   r   r   user_handler   rq   zJWT.user_handlerc                 C   rm   )a]  Specifies the error handler function. This function receives a JWTError instance as
        its only positional argument. It can optionally return a response. Example::

            @jwt.error_handler
            def error_handler(e):
                return "Something bad happened", 400

        :param callback: the error handler function
        )ri   rn   r   r   r   error_handler   s   
zJWT.error_handlerc                 C   rm   )zSpecifies the response handler function. This function receives a
        JWT-encoded payload and returns a Flask response.

        :param callable callback: the response handler function
        )r[   rn   r   r   r   response_handler      zJWT.response_handlerc                 C   rm   )zSpecifies the encoding handler function. This function receives a
        payload and signs it.

        :param callable callback: the encoding handler function
        )rZ   rn   r   r   r   encode_handler   ru   zJWT.encode_handlerc                 C   rm   )zSpecifies the decoding handler function. This function receives a
        signed payload and decodes it.

        :param callable callback: the decoding handler function
        )rO   rn   r   r   r   decode_handler  ru   zJWT.decode_handlerc                 C   rm   )a  Specifies the payload handler function. This function receives a
        user object and returns a dictionary payload.

        Example::

            @jwt.payload_handler
            def make_payload(user):
                return {
                    'user_id': user.id,
                    'exp': datetime.utcnow() + current_app.config['JWT_EXPIRATION_DELTA']
                }

        :param callable callback: the payload handler function
        )rY   rn   r   r   r   payload_handler  s   zJWT.payload_handlerr3   )rE   rF   rG   rD   r`   re   rj   rp   rr   rs   rt   rv   rw   rx   r   r   r   r   r^      s    
			r^   r3   )$__doc__collectionsr   datetimer   	functoolsr   Zitsdangerousr   r   r   Zflaskr	   r
   r   r   Zflask.viewsr   Zwerkzeug.localr   __version__r   rN   r    r#   r(   r-   r.   rb   r<   	Exceptionr=   r4   rS   objectr^   r   r   r   r   <module>   s<   


&