o
    ^[2h:4                     @   s   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 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 ddlmZ ddlmZ G dd deZdd ZdS )    )ContinueIteration)	deprecate   )ClientAuthentication)InvalidScopeError)OAuth2Error)UnsupportedGrantTypeError)UnsupportedResponseTypeError)Hookable)hooked)JsonRequest)OAuth2Request)scope_to_listc                       s   e Zd ZdZd4 fdd	Zdd Zdd Z					d5d
dZdd Zd6ddZ	dd Z
dd Zdd Zdd ZdefddZdefddZdd Zd d! Zd4d"d#Zd$d% Zed&d' Zd7d(d)Zd*d+ Zd4d,d-Zed8d.d/Zd4d0d1Zd2d3 Z  ZS )9AuthorizationServerzAuthorization server that handles Authorization Endpoint and Token
    Endpoint.

    :param scopes_supported: A list of supported scopes by this authorization server.
    Nc                    s8   t    || _i | _d | _g | _g | _i | _g | _d S N)	super__init__scopes_supported_token_generators_client_auth_authorization_grants_token_grants
_endpoints_extensions)selfr   	__class__ |/home/skpark/git/infrasmart_work/infrasmart/venv/lib/python3.10/site-packages/authlib/oauth2/rfc6749/authorization_server.pyr      s   

zAuthorizationServer.__init__c                 C      t  )zQuery OAuth client by client_id. The client model class MUST
        implement the methods described by
        :class:`~authlib.oauth2.rfc6749.ClientMixin`.
        NotImplementedError)r   	client_idr   r   r   query_client!   s   z AuthorizationServer.query_clientc                 C   r   )z:Define function to save the generated token into database.r    )r   tokenrequestr   r   r   
save_token(      zAuthorizationServer.save_tokenTc                 C   s<   | j |}|s| j d}|std|||||||dS )a  Generate the token dict.

        :param grant_type: current requested grant_type.
        :param client: the client that making the request.
        :param user: current authorized user.
        :param expires_in: if provided, use this value as expires_in.
        :param scope: current requested scope.
        :param include_refresh_token: should refresh_token be included.
        :return: Token dict
        defaultzNo configured token generator)
grant_typeclientuserscope
expires_ininclude_refresh_token)r   getRuntimeError)r   r)   r*   r+   r,   r-   r.   funcr   r   r   generate_token,   s   z"AuthorizationServer.generate_tokenc                 C   s   || j |< dS )ay  Register a function as token generator for the given ``grant_type``.
        Developers MUST register a default token generator with a special
        ``grant_type=default``::

            def generate_bearer_token(
                grant_type,
                client,
                user=None,
                scope=None,
                expires_in=None,
                include_refresh_token=True,
            ):
                token = {"token_type": "Bearer", "access_token": ...}
                if include_refresh_token:
                    token["refresh_token"] = ...
                ...
                return token


            authorization_server.register_token_generator(
                "default", generate_bearer_token
            )

        If you register a generator for a certain grant type, that generator will only works
        for the given grant type::

            authorization_server.register_token_generator(
                "client_credentials",
                generate_bearer_token,
            )

        :param grant_type: string name of the grant type
        :param func: a function to generate token
        N)r   )r   r)   r1   r   r   r   register_token_generatorP   s   #z,AuthorizationServer.register_token_generatorr$   c                 C   s*   | j du r| jrt| j| _ |  |||S )zAuthenticate client via HTTP request information with the given
        methods, such as ``client_secret_basic``, ``client_secret_post``.
        N)r   r#   r   )r   r%   methodsendpointr   r   r   authenticate_clientu   s   z'AuthorizationServer.authenticate_clientc                 C   s.   | j du r| jrt| j| _ | j || dS )at  Add more client auth method. The default methods are:

        * none: The client is a public client and does not have a client secret
        * client_secret_post: The client uses the HTTP POST parameters
        * client_secret_basic: The client uses HTTP Basic

        :param method: Name of the Auth method
        :param func: Function to authenticate the client

        The auth method accept two parameters: ``query_client`` and ``request``,
        an example for this method::

            def authenticate_client_via_custom(query_client, request):
                client_id = request.headers["X-Client-Id"]
                client = query_client(client_id)
                do_some_validation(client)
                return client


            authorization_server.register_client_auth_method(
                "custom", authenticate_client_via_custom
            )
        N)r   r#   r   register)r   methodr1   r   r   r   register_client_auth_method}   s   z/AuthorizationServer.register_client_auth_methodc                 C   s   | j ||  d S r   )r   append)r   	extensionr   r   r   register_extension   s   z&AuthorizationServer.register_extensionc                 C   s   dS )zFReturn a URI for the given error, framework may implement this method.Nr   r   r%   errorr   r   r   get_error_uri   s   z!AuthorizationServer.get_error_uric                 O   r   )z]Framework integration can re-implement this method to support
        signal system.
        r    )r   nameargskwargsr   r   r   send_signal   s   zAuthorizationServer.send_signalreturnc                 C   r   )zThis method MUST be implemented in framework integrations. It is
        used to create an OAuth2Request instance.

        :param request: the "request" instance in framework
        :return: OAuth2Request instance
        r    r   r%   r   r   r   create_oauth2_request      z)AuthorizationServer.create_oauth2_requestc                 C   r   )zThis method MUST be implemented in framework integrations. It is
        used to create an HttpRequest instance.

        :param request: the "request" instance in framework
        :return: HttpRequest instance
        r    rE   r   r   r   create_json_request   rG   z'AuthorizationServer.create_json_requestc                 C   r   )z=Return HTTP response. Framework MUST implement this function.r    )r   statusbodyheadersr   r   r   handle_response   r'   z#AuthorizationServer.handle_responsec                 C   s8   |r| j rtt|}t| j |st dS dS dS )zValidate if requested scope is supported by Authorization Server.
        Developers CAN re-write this method to meet your needs.
        N)r   setr   
issupersetr   )r   r,   scopesr   r   r   validate_requested_scope   s   
z,AuthorizationServer.validate_requested_scopec                 C   s<   t |dr| j||f t |dr| j||f dS dS )a  Register a grant class into the endpoint registry. Developers
        can implement the grants in ``authlib.oauth2.rfc6749.grants`` and
        register with this method::

            class AuthorizationCodeGrant(grants.AuthorizationCodeGrant):
                def authenticate_user(self, credential):
                    # ...

            authorization_server.register_grant(AuthorizationCodeGrant)

        :param grant_cls: a grant class.
        :param extensions: extensions for the grant class.
        check_authorization_endpointcheck_token_endpointN)hasattrr   r:   r   )r   	grant_cls
extensionsr   r   r   register_grant   s
   

z"AuthorizationServer.register_grantc                 C   s8   t |tr
|| }n| |_| j|jg }|| dS )zAdd extra endpoint to authorization server. e.g.
        RevocationEndpoint::

            authorization_server.register_endpoint(RevocationEndpoint)

        :param endpoint_cls: A endpoint class or instance.
        N)
isinstancetypeserverr   
setdefaultENDPOINT_NAMEr:   )r   r5   	endpointsr   r   r   register_endpoint   s
   

z%AuthorizationServer.register_endpointc                 C   sN   | j D ]\}}||rt||||   S qtd|jj d|jj|jjd)zFind the authorization grant for current request.

        :param request: OAuth2Request instance.
        :return: grant instance
        zThe response type 'z!' is not supported by the server.)redirect_uri)r   rQ   _create_grantr	   payloadresponse_typer^   r   r%   rT   rU   r   r   r   get_authorization_grant   s   
z+AuthorizationServer.get_authorization_grantc              
   C   sX   z|  |}||_| |}|| |  W |S  ty+ } z|jj|_ d}~ww )zValidate current HTTP request for authorization page. This page
        is designed for resource owner to grant or deny the authorization.
        N)rF   r+   rc   &validate_no_multiple_request_parametervalidate_consent_requestr   r`   state)r   r%   end_usergrantr>   r   r   r   get_consent_grant   s   




z%AuthorizationServer.get_consent_grantc                 C   s8   | j D ]\}}||rt||||   S qt|jj)zFind the token grant for current request.

        :param request: OAuth2Request instance.
        :return: grant instance
        )r   rR   r_   r   r`   r)   rb   r   r   r   get_token_grant  s
   
z#AuthorizationServer.get_token_grantc                 C   s   || j vrtd| d| j | }|D ]3}||}z
| j|| W   S  ty.   Y q tyG } z| ||W  Y d}~  S d}~ww dS )zValidate endpoint request and create endpoint response.

        :param name: Endpoint name
        :param request: HTTP request instance.
        :return: Response
        zThere is no 'z' endpoint.N)r   r0   create_endpoint_requestrL   r   r   handle_error_response)r   r@   r%   r\   r5   r>   r   r   r   create_endpoint_response  s   


z,AuthorizationServer.create_endpoint_responsec              
   C   s   t |ts
| |}|s7tddd z| |}W n ty6 } z|jj|_| ||W  Y d}~S d}~ww z|	 }|
||}| j| }W n tye } z|jj|_| ||}W Y d}~nd}~ww |d| |S )zValidate authorization request and create authorization response.

        :param request: HTTP request instance.
        :param grant_user: if granted, it is resource owner. If denied,
            it is None.
        :returns: Response
        z,The 'grant' parameter will become mandatory.z1.8)versionNafter_authorization_response)rW   r   rF   r   rc   r	   r`   rf   rl   validate_authorization_requestcreate_authorization_responserL   r   execute_hook)r   r%   
grant_userrh   r>   r^   rA   responser   r   r   rq   -  s,   
	


z1AuthorizationServer.create_authorization_responsec              
   C   s   |  |}z| |}W n ty$ } z| ||W  Y d}~S d}~ww z|  | }| j| W S  tyK } z| ||W  Y d}~S d}~ww )ziValidate token request and create token response.

        :param request: HTTP request instance
        N)rF   rj   r   rl   validate_token_requestcreate_token_responserL   r   )r   r%   rh   r>   rA   r   r   r   rv   L  s   
z)AuthorizationServer.create_token_responsec                 C   s   | j || || S r   )rL   r?   r=   r   r   r   rl   ^  s   z)AuthorizationServer.handle_error_responser   )NNNT)r$   )NN)NNN)__name__
__module____qualname____doc__r   r#   r&   r2   r3   r6   r9   r<   r?   rC   r   rF   r   rH   rL   rP   rV   r]   r   rc   ri   rj   rm   rq   rv   rl   __classcell__r   r   r   r   r      s>    

$
%		
	



r   c                 C   s$   | ||}|r|D ]}|| q	|S r   r   )rT   rU   r%   rY   rh   extr   r   r   r_   b  s
   

r_   N)authlib.common.errorsr   authlib.deprecater   r6   r   errorsr   r   r   r	   hooksr
   r   requestsr   r   utilr   r   r_   r   r   r   r   <module>   s       T