o
    ©D®f-6  ã                   @   sT   d dl mZmZ ddlmZ ddlmZmZmZm	Z	m
Z
mZmZ G dd„ deƒZdS )é    )Úis_valid_urlÚadd_params_to_urié   )Ú
BaseServer)ÚOAuth1ErrorÚInvalidRequestErrorÚMissingRequiredParameterErrorÚInvalidClientErrorÚInvalidTokenErrorÚAccessDeniedErrorÚMethodNotAllowedErrorc                   @   s”   e Zd Zg d¢ZdZdd„ Zdd„ Zdd„ Zd	d
„ Zdd„ Z	d"dd„Z
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S )#ÚAuthorizationServer))zContent-Typez!application/x-www-form-urlencoded)zCache-Controlzno-store)ÚPragmazno-cacheÚPOSTc                 C   s   |   |j¡}||_|S ©N)Úget_client_by_idÚ	client_idÚclient)ÚselfÚrequestr   © r   úd/home/ubuntu/webapp/venv/lib/python3.10/site-packages/authlib/oauth1/rfc5849/authorization_server.pyÚ_get_client   s   zAuthorizationServer._get_clientc                 C   ó   t ƒ ‚r   ©ÚNotImplementedError©r   r   r   r   r   Úcreate_oauth1_request   ó   z)AuthorizationServer.create_oauth1_requestc                 C   r   r   r   )r   Ústatus_codeÚpayloadÚheadersr   r   r   Úhandle_response   r   z#AuthorizationServer.handle_responsec                 C   s   |   |j| ¡ | ¡ ¡S r   )r"   r   Úget_bodyÚget_headers)r   Úerrorr   r   r   Úhandle_error_response"   s
   ýz)AuthorizationServer.handle_error_responsec                 C   s|   |j  ¡ | jkrtƒ ‚|jstdƒ‚|j}|jstdƒ‚|dkr(t|ƒs(tdƒ‚|  	|¡}|s2t
ƒ ‚|  |¡ |  |¡ |S )z0Validate HTTP request for temporary credentials.Úoauth_consumer_keyÚoauth_callbackÚoobzInvalid "oauth_callback" value)ÚmethodÚupperÚTEMPORARY_CREDENTIALS_METHODr   r   r   Úredirect_urir   r   r   r	   Úvalidate_timestamp_and_nonceÚvalidate_oauth_signature)r   r   r(   r   r   r   r   Ú&validate_temporary_credentials_request)   s   


z:AuthorizationServer.validate_temporary_credentials_requestNc              
   C   s|   z|   |¡}|  |¡ W n ty# } z|  |¡W  Y d}~S d}~ww |  |¡}d| ¡ fd| ¡ fdg}|  d|| j¡S )a”  Validate temporary credentials token request and create response
        for temporary credentials token. Assume the endpoint of temporary
        credentials request is ``https://photos.example.net/initiate``:

        .. code-block:: http

            POST /initiate HTTP/1.1
            Host: photos.example.net
            Authorization: OAuth realm="Photos",
                oauth_consumer_key="dpf43f3p2l4k3l03",
                oauth_signature_method="HMAC-SHA1",
                oauth_timestamp="137131200",
                oauth_nonce="wIjqoS",
                oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready",
                oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D"

        The server validates the request and replies with a set of temporary
        credentials in the body of the HTTP response:

        .. code-block:: http

            HTTP/1.1 200 OK
            Content-Type: application/x-www-form-urlencoded

            oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&
            oauth_callback_confirmed=true

        :param request: OAuth1Request instance.
        :returns: (status_code, body, headers)
        NÚoauth_tokenÚoauth_token_secret)Úoauth_callback_confirmedTéÈ   )	r   r0   r   r&   Úcreate_temporary_credentialÚget_oauth_tokenÚget_oauth_token_secretr"   ÚTOKEN_RESPONSE_HEADER©r   r   r%   Ú
credentialr    r   r   r   Ú%create_temporary_credentials_responseI   s   
€ÿ


ýz9AuthorizationServer.create_temporary_credentials_responsec                 C   s,   |j stdƒ‚|  |¡}|stƒ ‚||_|S )z6Validate the request for resource owner authorization.r1   )Útokenr   Úget_temporary_credentialr
   r:   )r   r   r:   r   r   r   Úvalidate_authorization_requestv   s   
z2AuthorizationServer.validate_authorization_requestc                 C   s¸   |   |¡}|  |¡ |j}| ¡ }|r|dkr$| ¡ }|  |¡}| ¡ }|du r<tƒ }t|| 	¡ ƒ}|  
ddd|fg¡S ||_|  |¡}	d|jfd|	fg}
t||
ƒ}|  
ddd|fg¡S )aP  Validate authorization request and create authorization response.
        Assume the endpoint for authorization request is
        ``https://photos.example.net/authorize``, the client redirects Jane's
        user-agent to the server's Resource Owner Authorization endpoint to
        obtain Jane's approval for accessing her private photos::

            https://photos.example.net/authorize?oauth_token=hh5s93j4hdidpola

        The server requests Jane to sign in using her username and password
        and if successful, asks her to approve granting 'printer.example.com'
        access to her private photos.  Jane approves the request and her
        user-agent is redirected to the callback URI provided by the client
        in the previous request (line breaks are for display purposes only)::

            http://printer.example.com/ready?
            oauth_token=hh5s93j4hdidpola&oauth_verifier=hfdp7dh39dks9884

        :param request: OAuth1Request instance.
        :param grant_user: if granted, pass the grant user, otherwise None.
        :returns: (status_code, body, headers)
        r)   Ni.  Ú ÚLocationr1   Úoauth_verifier)r   r>   r:   Úget_redirect_uriÚget_client_idr   Úget_default_redirect_urir   r   r#   r"   ÚuserÚcreate_authorization_verifierr<   )r   r   Ú
grant_userÚtemporary_credentialsr-   r   r   r%   ÚlocationÚverifierÚparamsr   r   r   Úcreate_authorization_responseƒ   s&   



þ
z1AuthorizationServer.create_authorization_responsec                 C   sŒ   |j stdƒ‚|  |¡}|stƒ ‚|jstdƒ‚|  |¡}|s"tƒ ‚|j d¡}|s.tdƒ‚| 	|¡s7t
dƒ‚||_|  |¡ |  |¡ |S )z#Validate request for issuing token.r'   r1   rA   zInvalid "oauth_verifier")r   r   r   r	   r<   r=   r
   Úoauth_paramsÚgetÚcheck_verifierr   r:   r.   r/   )r   r   r   r<   rJ   r   r   r   Úvalidate_token_request³   s&   




z*AuthorizationServer.validate_token_requestc              
   C   sÂ   z|   |¡}W n ty } z|  |¡W  Y d}~S d}~ww z|  |¡ W n tyB } z|  |¡ |  |¡W  Y d}~S d}~ww |  |¡}d| ¡ fd| ¡ fg}|  |¡ |  d|| j	¡S )a6  Validate token request and create token response. Assuming the
        endpoint of token request is ``https://photos.example.net/token``,
        the callback request informs the client that Jane completed the
        authorization process.  The client then requests a set of token
        credentials using its temporary credentials (over a secure Transport
        Layer Security (TLS) channel):

        .. code-block:: http

            POST /token HTTP/1.1
            Host: photos.example.net
            Authorization: OAuth realm="Photos",
                oauth_consumer_key="dpf43f3p2l4k3l03",
                oauth_token="hh5s93j4hdidpola",
                oauth_signature_method="HMAC-SHA1",
                oauth_timestamp="137131201",
                oauth_nonce="walatlh",
                oauth_verifier="hfdp7dh39dks9884",
                oauth_signature="gKgrFCywp7rO0OXSjdot%2FIHF7IU%3D"

        The server validates the request and replies with a set of token
        credentials in the body of the HTTP response:

        .. code-block:: http

            HTTP/1.1 200 OK
            Content-Type: application/x-www-form-urlencoded

            oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00

        :param request: OAuth1Request instance.
        :returns: (status_code, body, headers)
        Nr1   r2   r4   )
r   r   r&   rP   Údelete_temporary_credentialÚcreate_token_credentialr6   r7   r"   r8   r9   r   r   r   Úcreate_token_responseÐ   s&   "€ÿ
€þ


þ
z)AuthorizationServer.create_token_responsec                 C   r   )ap  Generate and save a temporary credential into database or cache.
        A temporary credential is used for exchanging token credential. This
        method should be re-implemented::

            def create_temporary_credential(self, request):
                oauth_token = generate_token(36)
                oauth_token_secret = generate_token(48)
                temporary_credential = TemporaryCredential(
                    oauth_token=oauth_token,
                    oauth_token_secret=oauth_token_secret,
                    client_id=request.client_id,
                    redirect_uri=request.redirect_uri,
                )
                # if the credential has a save method
                temporary_credential.save()
                return temporary_credential

        :param request: OAuth1Request instance
        :return: TemporaryCredential instance
        r   r   r   r   r   r5     ó   z/AuthorizationServer.create_temporary_credentialc                 C   r   )a;  Get the temporary credential from database or cache. A temporary
        credential should share the same methods as described in models of
        ``TemporaryCredentialMixin``::

            def get_temporary_credential(self, request):
                key = 'a-key-prefix:{}'.format(request.token)
                data = cache.get(key)
                # TemporaryCredential shares methods from TemporaryCredentialMixin
                return TemporaryCredential(data)

        :param request: OAuth1Request instance
        :return: TemporaryCredential instance
        r   r   r   r   r   r=     s   z,AuthorizationServer.get_temporary_credentialc                 C   r   )aK  Delete temporary credential from database or cache. For instance,
        if temporary credential is saved in cache::

            def delete_temporary_credential(self, request):
                key = 'a-key-prefix:{}'.format(request.token)
                cache.delete(key)

        :param request: OAuth1Request instance
        r   r   r   r   r   rQ   ,  s   
z/AuthorizationServer.delete_temporary_credentialc                 C   r   )aÓ  Create and bind ``oauth_verifier`` to temporary credential. It
        could be re-implemented in this way::

            def create_authorization_verifier(self, request):
                verifier = generate_token(36)

                temporary_credential = request.credential
                user_id = request.user.id

                temporary_credential.user_id = user_id
                temporary_credential.oauth_verifier = verifier
                # if the credential has a save method
                temporary_credential.save()

                # remember to return the verifier
                return verifier

        :param request: OAuth1Request instance
        :return: A string of ``oauth_verifier``
        r   r   r   r   r   rF   8  rT   z1AuthorizationServer.create_authorization_verifierc                 C   r   )a^  Create and save token credential into database. This method would
        be re-implemented like this::

            def create_token_credential(self, request):
                oauth_token = generate_token(36)
                oauth_token_secret = generate_token(48)
                temporary_credential = request.credential

                token_credential = TokenCredential(
                    oauth_token=oauth_token,
                    oauth_token_secret=oauth_token_secret,
                    client_id=temporary_credential.get_client_id(),
                    user_id=temporary_credential.get_user_id()
                )
                # if the credential has a save method
                token_credential.save()
                return token_credential

        :param request: OAuth1Request instance
        :return: TokenCredential instance
        r   r   r   r   r   rR   O  s   z+AuthorizationServer.create_token_credentialr   )Ú__name__Ú
__module__Ú__qualname__r8   r,   r   r   r"   r&   r0   r;   r>   rL   rP   rS   r5   r=   rQ   rF   rR   r   r   r   r   r      s$    
 -
05r   N)Úauthlib.common.urlsr   r   Úbase_serverr   Úerrorsr   r   r   r	   r
   r   r   r   r   r   r   r   Ú<module>   s    $