
    KiS6                         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e      Zd Zy)    )ContinueIteration)	deprecate   )ClientAuthentication)InvalidScopeError)OAuth2Error)UnsupportedGrantTypeError)UnsupportedResponseTypeError)Hookable)hooked)JsonRequest)OAuth2Request)scope_to_listc                        e Zd ZdZd fd	Zd Zd Z	 	 	 	 ddZd ZddZ	d Z
d	 Zd
 Zd ZdefdZdefdZd Zd ZddZd Zed        ZddZd ZddZedd       ZddZd Z xZS )AuthorizationServerzAuthorization server that handles Authorization Endpoint and Token
    Endpoint.

    :param scopes_supported: A list of supported scopes by this authorization server.
    c                     t         |           || _        i | _        d | _        g | _        g | _        i | _        g | _        y N)	super__init__scopes_supported_token_generators_client_auth_authorization_grants_token_grants
_endpoints_extensions)selfr   	__class__s     w/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/authlib/oauth2/rfc6749/authorization_server.pyr   zAuthorizationServer.__init__   sE     0!# %'"    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_ids     r   query_clientz AuthorizationServer.query_client!   s    
 "##r    c                     t               )z:Define function to save the generated token into database.r"   )r   tokenrequests      r   
save_tokenzAuthorizationServer.save_token(       !##r    c                     | j                   j                  |      }|s| j                   j                  d      }|st        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/   r0   r1   r2   funcs           r   generate_tokenz"AuthorizationServer.generate_token,   sa    ( %%))*5))--i8D>??!!"7
 	
r    c                 "    || j                   |<   y)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-   r5   s      r   register_token_generatorz,AuthorizationServer.register_token_generatorP   s    F .2z*r    c                     | j                   &| j                  rt        | j                        | _         | j                  |||      S )zAuthenticate client via HTTP request information with the given
        methods, such as ``client_secret_basic``, ``client_secret_post``.
        )r   r%   r   )r   r(   methodsendpoints       r   authenticate_clientz'AuthorizationServer.authenticate_clientu   s@     $):): 4T5F5F GD  '8<<r    c                     | j                   &| j                  rt        | j                        | _         | j                   j                  ||       y)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   methodr5   s      r   register_client_auth_methodz/AuthorizationServer.register_client_auth_method}   sA    0 $):): 4T5F5F GD""640r    c                 F    | j                   j                   ||              y r   )r   append)r   	extensions     r   register_extensionz&AuthorizationServer.register_extension   s    	$0r    c                      y)zFReturn a URI for the given error, framework may implement this method.N r   r(   errors      r   get_error_uriz!AuthorizationServer.get_error_uri   s    r    c                     t               )z]Framework integration can re-implement this method to support
        signal system.
        r"   )r   nameargskwargss       r   send_signalzAuthorizationServer.send_signal   s     "##r    returnc                     t               )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(   s     r   create_oauth2_requestz)AuthorizationServer.create_oauth2_request        "##r    c                     t               )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"   rQ   s     r   create_json_requestz'AuthorizationServer.create_json_request   rS   r    c                     t               )z=Return HTTP response. Framework MUST implement this function.r"   )r   statusbodyheaderss       r   handle_responsez#AuthorizationServer.handle_response   r*   r    c                     |rP| j                   rCt        t        |            }t        | j                         j                  |      s
t	               yyy)zValidate if requested scope is supported by Authorization Server.
        Developers CAN re-write this method to meet your needs.
        N)r   setr   
issupersetr   )r   r0   scopess      r   validate_requested_scopez,AuthorizationServer.validate_requested_scope   sM     T**u-.Ft,,-88@')) A +5r    c                     t        |d      r| j                  j                  ||f       t        |d      r| j                  j                  ||f       yy)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   rB   r   )r   	grant_cls
extensionss      r   register_grantz"AuthorizationServer.register_grant   sQ     9<=&&--y*.EF945%%y*&=> 6r    c                     t        |t              r	 ||       }n| |_        | j                  j	                  |j
                  g       }|j                  |       y)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_NAMErB   )r   r;   	endpointss      r   register_endpointz%AuthorizationServer.register_endpoint   sH     h%~H"HOOO..x/E/ErJ	"r    c                    | j                   D ]&  \  }}|j                  |      st        ||||       c S  d}|j                  j                  x}rO| j                  |      x}r<|j                  j                  x}r|j                  |      r|}n|j                         }t        d|j                  j                   d|j                  j                  |      )zFind the authorization grant for current request.

        :param request: OAuth2Request instance.
        :return: grant instance
        NzThe response type 'z!' is not supported by the server.)redirect_uri)r   ra   _create_grantpayloadr$   r%   rp   check_redirect_uriget_default_redirect_urir
   response_type)r   r(   rd   re   rp   r$   r.   requested_uris           r   get_authorization_grantz+AuthorizationServer.get_authorization_grant   s     &*%?%? 	K!Iz55g>$Y
GTJJ	K 11191**955v5$+OO$@$@@=@00?'4#)#B#B#DL*!'//"?"?!@@abOO))%
 	
r    c                     | j                  |      }	 ||_        | j                  |      }|j                  |       |j	                          |S # t
        $ r!}|j                  j                  |_         d}~ww xY w)zValidate current HTTP request for authorization page. This page
        is designed for resource owner to grant or deny the authorization.
        N)rR   r/   rw   &validate_no_multiple_request_parametervalidate_consent_requestr   rr   state)r   r(   end_usergrantrH   s        r   get_consent_grantz%AuthorizationServer.get_consent_grant  sy     ,,W5	#GL009E88A**,   	 "////EK	s   9A 	A8A33A8c                     | j                   D ]&  \  }}|j                  |      st        ||||       c S  t        |j                  j
                        )zFind the token grant for current request.

        :param request: OAuth2Request instance.
        :return: grant instance
        )r   rb   rq   r	   rr   r-   )r   r(   rd   re   s       r   get_token_grantz#AuthorizationServer.get_token_grant  sV     &*%7%7 	K!Iz--g6$Y
GTJJ	K ((B(BCCr    c                 "   || j                   vrt        d| d      | j                   |   }|D ]*  }|j                  |      }	  | j                   ||       c S  y# t        $ r Y 9t
        $ r}| j                  ||      cY d}~c S d}~ww xY w)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   r4   create_endpoint_requestrZ   r   r   handle_error_response)r   rK   r(   rm   r;   rH   s         r   create_endpoint_responsez,AuthorizationServer.create_endpoint_response%  s     t&tfK@AAOOD)	! 	BH66w?GB+t++Xg->??	B %  B11'5AABs$   A	B(B0B	B	Bc                    t        |t              s| j                  |      }|st        dd       	 | j	                  |      }	 |j                         }|j                  ||      } | j                  | }|j                  d|       |S # t
        $ r7}|j                  j                  |_        | j                  ||      cY d}~S d}~ww xY w# t        $ r7}|j                  j                  |_        | j                  ||      }Y d}~d}~ww xY w)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)rh   r   rR   r   rw   r
   rr   r{   r   validate_authorization_requestcreate_authorization_responserZ   r   execute_hook)r   r(   
grant_userr}   rH   rp   rL   responses           r   r   z1AuthorizationServer.create_authorization_response9  s     '=1009GDeTB44W=
	B ??AL66|ZPD+t++T2H
 	98D 0 B%oo3311'5AAB  	B!////EK11'5AH	Bs5   B	 1C 		C	,C>C	C		D-DDc                 H   | j                  |      }	 | j                  |      }	 |j	                          |j                         } | j                  | S # t        $ r}| j                  ||      cY d}~S d}~ww xY w# t        $ r}| j                  ||      cY d}~S d}~ww xY w)ziValidate token request and create token response.

        :param request: HTTP request instance
        N)rR   r   r	   r   validate_token_requestcreate_token_responserZ   r   )r   r(   r}   rH   rL   s        r   r   z)AuthorizationServer.create_token_responseX  s    
 ,,W5	>((1E	>((*..0D'4''.. ) 	>--gu==	>  	>--gu==	>s:   A .A< 	A9A4.A94A9<	B!BB!B!c                 L     | j                    || j                  ||             S r   )rZ   rI   rG   s      r   r   z)AuthorizationServer.handle_error_responsej  s'    #t##U4+=+=gu+M%NOOr    r   )NNNT)r'   )NN)NNN)__name__
__module____qualname____doc__r   r%   r)   r6   r8   r<   r@   rD   rI   rN   r   rR   r   rU   rZ   r_   rf   rn   r   rw   r~   r   r   r   r   r   __classcell__)r   s   @r   r   r      s    $$ ""
H#2J=1:1$$ $$k $$*?&#  
 
6*	DB(  <>$Pr    r   c                 :     | ||      }|r|D ]
  } ||        |S r   rF   )rd   re   r(   rj   r}   exts         r   rq   rq   n  s,    gv&E 	CJ	Lr    N)authlib.common.errorsr   authlib.deprecater   r<   r   errorsr   r   r	   r
   hooksr   r   requestsr   r   utilr   r   rq   rF   r    r   <module>r      s?    3 ' 5 %  - 0   ! # [P( [P|
r    