o
    bK                     @   s   d dl mZ d dlmZmZ d dlmZ d dlmZm	Z	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mZ ddlmZ G dd deZ
dddZdddZdS )    )import_string)Responsejson)	deprecate)OAuth2RequestHttpRequestAuthorizationServer)BearerToken)AuthorizationServerMetadatagenerate_token)
to_unicode   )client_authenticatedtoken_revoked   )create_oauth_requestc                       sz   e Zd ZdZeZd fd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dZ  ZS )r   a  Flask implementation of :class:`authlib.oauth2.rfc6749.AuthorizationServer`.
    Initialize it with ``query_client``, ``save_token`` methods and Flask
    app instance::

        def query_client(client_id):
            return Client.query.filter_by(client_id=client_id).first()

        def save_token(token, request):
            if request.user:
                user_id = request.user.get_user_id()
            else:
                user_id = None
            client = request.client
            tok = Token(
                client_id=client.client_id,
                user_id=user.get_user_id(),
                **token
            )
            db.session.add(tok)
            db.session.commit()

        server = AuthorizationServer(app, query_client, save_token)
        # or initialize lazily
        server = AuthorizationServer()
        server.init_app(app, query_client, save_token)
    Nc                    s4   t t| j||d i | _|d ur| | d S d S )N)query_client
save_token)superr   __init__configinit_app)selfappr   r   	__class__ u/var/www/secure340b-portal/env/lib/python3.10/site-packages/authlib/integrations/flask_oauth2/authorization_server.pyr   .   s   
zAuthorizationServer.__init__c                 C   s   |dur|| _ |dur|| _| |j| _|jd}|r@t|}| t	|}|
  || _W d   n1 s;w   Y  | jd|jd |jdr^tdd | |j dS dS )z)Initialize later with Flask app instance.NZOAUTH2_METADATA_FILE
error_urisZOAUTH2_ERROR_URISZOAUTH2_JWT_ENABLEDz0Define "get_jwt_config" in OpenID Connect grantsz1.0)r   r   create_bearer_token_generatorr   r   getopenmetadata_classr   loadvalidatemetadata
setdefaultr   init_jwt_config)r   r   r   r   Zmetadata_filefr&   r   r   r   r   7   s"   

zAuthorizationServer.init_appc                 C   s   | d}|std| d}|r9t|d}|dr#t|}nt| }W d   n1 s3w   Y  n| d}|sDtd| d	}|sOtd
| dd}| j	d| | j	d| | j	d| | j	d| dS )z%Initialize JWT related configuration.ZOAUTH2_JWT_ISSz'Missing "OAUTH2_JWT_ISS" configuration.ZOAUTH2_JWT_KEY_PATHrz.jsonNZOAUTH2_JWT_KEYz'Missing "OAUTH2_JWT_KEY" configuration.ZOAUTH2_JWT_ALGz'Missing "OAUTH2_JWT_ALG" configuration.ZOAUTH2_JWT_EXPi  jwt_issjwt_keyjwt_algjwt_exp)
r!   RuntimeErrorr"   endswithr   r$   r   readr   r'   )r   r   r+   Zjwt_key_pathr)   r,   r-   r.   r   r   r   r(   L   s.   




z#AuthorizationServer.init_jwt_configc                 C   s   | j d}|rt|S d S )Nr   )r   r!   dict)r   requestr   r   r   r   get_error_urisi   s   z"AuthorizationServer.get_error_urisc                 C   s
   t |tS N)r   r   r   r3   r   r   r   create_oauth2_requestn   s   
z)AuthorizationServer.create_oauth2_requestc                 C   s   t |tdS )NT)r   r   r6   r   r   r   create_json_requestq   s   z'AuthorizationServer.create_json_requestc                 C   s"   t |tr
t|}t|||dS )N)statusheaders)
isinstancer2   r   dumpsr   )r   status_codepayloadr:   r   r   r   handle_responset   s   

z#AuthorizationServer.handle_responsec                 O   sL   |dkrt j| g|R i | d S |dkr$tj| g|R i | d S d S )NZafter_authenticate_clientZafter_revoke_token)r   sendr   )r   nameargskwargsr   r   r   send_signaly   s
   zAuthorizationServer.send_signalc                 C   s   | d}t|S )a  Create a generator function for generating ``expires_in`` value.
        Developers can re-implement this method with a subclass if other means
        required. The default expires_in value is defined by ``grant_type``,
        different ``grant_type`` has different value. It can be configured
        with::

            OAUTH2_TOKEN_EXPIRES_IN = {
                'authorization_code': 864000,
                'urn:ietf:params:oauth:grant-type:jwt-bearer': 3600,
            }
        ZOAUTH2_TOKEN_EXPIRES_IN)r!   !create_token_expires_in_generator)r   r   Zexpires_confr   r   r   rE      s   
z5AuthorizationServer.create_token_expires_in_generatorc                 C   sB   | dd}t|d}| dd}t|d}| |}t|||S )aJ  Create a generator function for generating ``token`` value. This
        method will create a Bearer Token generator with
        :class:`authlib.oauth2.rfc6750.BearerToken`. By default, it will not
        generate ``refresh_token``, which can be turn on by configuration
        ``OAUTH2_REFRESH_TOKEN_GENERATOR=True``.
        ZOAUTH2_ACCESS_TOKEN_GENERATORT*   ZOAUTH2_REFRESH_TOKEN_GENERATORF0   )r!   create_token_generatorrE   r	   )r   r   confZaccess_token_generatorZrefresh_token_generatorZexpires_generatorr   r   r   r       s   


z1AuthorizationServer.create_bearer_token_generatorc                 C   s6   |  |}||_| |}|  t|dsd|_|S )a  Validate current HTTP request for authorization page. This page
        is designed for resource owner to grant or deny the authorization::

            @app.route('/authorize', methods=['GET'])
            def authorize():
                try:
                    grant = server.validate_consent_request(end_user=current_user)
                    return render_template(
                        'authorize.html',
                        grant=grant,
                        user=current_user
                    )
                except OAuth2Error as error:
                    return render_template(
                        'error.html',
                        error=error
                    )
        promptN)r7   userZget_authorization_grantvalidate_consent_requesthasattrrJ   )r   r3   Zend_userreqZgrantr   r   r   rL      s   


z,AuthorizationServer.validate_consent_request)NNN)NN)__name__
__module____qualname____doc__r
   r#   r   r   r(   r4   r7   r8   r?   rD   rE   r    rL   __classcell__r   r   r   r   r      s    
	r   Nc                    s.   i    tj | r  |   fdd}|S )Nc                    s     |tjS r5   )r!   r	   ZDEFAULT_EXPIRES_IN)clientZ
grant_typedatar   r   
expires_in   s   z5create_token_expires_in_generator.<locals>.expires_in)updater	   ZGRANT_TYPES_EXPIRES_IN)Zexpires_in_confrW   r   rU   r   rE      s   
rE   rF   c                    s:   t | r| S t| trt| S | du r fdd}|S d S )NTc                     s   t  S r5   r   )rB   rC   lengthr   r   token_generator   s   z/create_token_generator.<locals>.token_generator)callabler;   strr   )Ztoken_generator_confrZ   r[   r   rY   r   rH      s   
rH   r5   )rF   )Zwerkzeug.utilsr   Zflaskr   r   Zauthlib.deprecater   Zauthlib.oauth2r   r   r   Z_AuthorizationServerZauthlib.oauth2.rfc6750r	   Zauthlib.oauth2.rfc8414r
   Zauthlib.common.securityr   Zauthlib.common.encodingr   Zsignalsr   r   Zflask_helpersr   rE   rH   r   r   r   r   <module>   s     
/