
    -_g                          d dl Z 	 d dlZdZd dlZd dlmZmZ d dlmZ dZ	dZ
 e j                  d      Z G d	 d
      Zy# e$ r dZY <w xY w)    NTF)datetime	timedelta)TIMEOUT_DEFAULTz	sos-toolsz,urn:ietf:params:oauth:grant-type:device_codesosc                   H    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 ZddZy
)DeviceAuthorizationClassz$
    Device Authorization Class
    c                 j    d | _         d | _        d | _        || _        || _        | j                          y N)_access_token_access_expires_at&_DeviceAuthorizationClass__device_codeclient_identifier_urltoken_endpoint_use_device_code_grant)selfr   r   s      </usr/lib/python3/dist-packages/sos/policies/auth/__init__.py__init__z!DeviceAuthorizationClass.__init__!   s6    !"&!%:",##%    c                 t    | j                          t        d| j                          | j                          y)zv
        Start the device auth flow. In the future we will
        store the tokens in an in-memory keyring.

        z<Please visit the following URL to authenticate this device: N)_request_device_codeprint_verification_uri_completepoll_for_auth_completionr   s    r   r   z/DeviceAuthorizationClass._use_device_code_grant+   s<     	!!#778:	
 	%%'r   c                 ,   dt          }ddi}t        st        d      	 t        j                  | j
                  ||t              }|j                          |j                         }|j                  d      | _
        |j                  d      | _        |j                  d      | _        |j                  d	      | _        |j                  d
      | _        y# t        j                  $ r*}t        j                  dj                    d|       d}~ww xY w)zm
        Initialize new Device Authorization Grant attempt by
        requesting a new device code.

        z
client_id=zcontent-typez!application/x-www-form-urlencodedRpython3-requests is not installed and is required for obtaining device auth token.)dataheaderstimeout	user_codeverification_uriintervaldevice_codeverification_uri_completezNHTTP request failed while attempting to acquire the tokens.Error returned was  N)DEVICE_AUTH_CLIENT_IDREQUESTS_LOADED	Exceptionrequestspostr   r   raise_for_statusjsonget
_user_code_verification_uri	_intervalr   r   	HTTPErrorstatus_code)r   r   r   resresponsees         r   r   z-DeviceAuthorizationClass._request_device_code9   s    123!#FG @ A A	---**'	)C
   "xxzH&ll;7DO%-\\2D%ED"%\\*5DN!)m!<D.6ll+/-D+!! 	-$$ &;;>??:K1()s&, - -	-s   B5C D)%DDc                    t         t        | j                  d}t        st	        d      | j
                  t        j                  | j                         	 t        j                  | j                  |t              }|j                  }|dk(  r4t        j                  d       | j!                  |j#                                |dvrt	        ||j$                        |dk(  r+|j#                         d	   d
vrt	        ||j$                        | j
                  yy# t        j&                  j(                  $ r"}t        j+                  d|        Y d}~Id}~ww xY w)z
        Continuously poll OIDC token endpoint until the user is successfully
        authenticated or an error occurs.

        )
grant_type	client_idr#   r   Nr   r      z$The SSO authentication is successful)r:     r;   error)authorization_pending	slow_downz)Error was found while posting a request: )GRANT_TYPE_DEVICE_CODEr&   r   r'   r(   r   timesleepr0   r)   r*   r   r   r2   loggerinfo_set_token_datar,   text
exceptionsRequestExceptionr<   )r   
token_datacheck_auth_completionr2   r5   s        r   r   z1DeviceAuthorizationClass.poll_for_auth_completionX   sD    %;#8%)%7%79
  @ A A  (JJt~~&N(0d6I6I;E>M)O% 4??#%KK FG(()>)C)C)EFj0#K1F1K1KLL#%)..09>?#K1F1K1KLL#   ($ &&77 NHLMMNs   B5D E7EEc                    |j                  d      | _        t        j                         t	        |j                  d            z   | _        |j                  d      | _        |j                  d      | _        | j                  dk(  rt        j                  | _	        yt        j                         t	        | j                        z   | _	        y)a@  
        Set the class attributes as per the input token_data received.
        In the future we will persist the token data in a local,
        in-memory keyring, to avoid visting the browser frequently.
        :param token_data: Token data containing access_token, refresh_token
        and their expiry etc.
        access_token
expires_insecondsrefresh_tokenrefresh_expires_inr   N)
r-   r   r   utcnowr   r   _refresh_token_refresh_expires_inmax_refresh_expires_at)r   rH   s     r   rD   z(DeviceAuthorizationClass._set_token_dataz   s     (^^N;"*//"3jnn\:;#<(nn_=#->>2F#G ##q('/||D$'/'8$":":;(<D$r   c                     | j                         r| j                  S | j                         r| j                          | j                  S | j	                          | j                  S )zt
        Get the valid access_token at any given time.
        :return: Access_token
        :rtype: string
        )is_access_token_validr   is_refresh_token_valid_use_refresh_token_grantr   r   s    r   get_access_tokenz)DeviceAuthorizationClass.get_access_token   sX     %%'%%%&&())+%%%##%!!!r   c                     | j                   xr< | j                  xr. | j                  t        d      z
  t        j                         kD  S )z
        Check the validity of access_token. We are considering it invalid 180
        sec. prior to it's exact expiry time.
        :return: True/False

           rM   )r   r   r   r   rQ   r   s    r   rW   z.DeviceAuthorizationClass.is_access_token_valid   sF     !! d&=&= ##i&<<OO	r   c                     | j                   xr< | j                  xr. | j                  t        d      z
  t        j                         kD  S )z
        Check the validity of refresh_token. We are considering it invalid
        180 sec. prior to it's exact expiry time.

        :return: True/False

        r\   rM   )rR   rU   r   r   rQ   r   s    r   rX   z/DeviceAuthorizationClass.is_refresh_token_valid   sF     "" t'?'? $$y'==OO	r   Nc                 .   t         st        d      t        d|s| j                  n|d}t	        j
                  | j                  |t              }|j                  dk(  r | j                  |j                                y|j                  dk(  r]d|j                         d   v rHt        j                  d	|j                   d
|j                         d    d       | j                          yt        d|j                   d|j                         d          )z
        Fetch the new access_token and refresh_token using the existing
        refresh_token and persist it.
        :param refresh_token: optional param for refresh_token

        r   rO   )r8   r7   rO   r9   r:   r;   invalidr<   zAProblem while fetching the new tokens from refresh token grant - r%   z%. New Device code will be requested !zcSomething went wrong while using the Refresh token grant for fetching tokens: Returned status code z and error N)r'   r(   r&   rR   r)   r*   r   r   r2   rD   r,   rB   warningr   )r   rO   refresh_token_datarefresh_token_ress       r   rY   z1DeviceAuthorizationClass._use_refresh_token_grant   s6     @ A A+@,;+ 04/B/B1>@
 %MM$*=*=/A2AC ((C/  !2!7!7!9:**c1i!&&(172NN -->-J-J,K1/446w?@ ABB C ''))):)F)F(G/446w?@BC Cr   r
   )__name__
__module____qualname____doc__r   r   r   r   rD   rZ   rW   rX   rY    r   r   r   r      s7    &(-> ND<&"	
"Cr   r   )loggingr)   r'   ImportErrorr@   r   r   sos.utilitiesr   r&   r?   	getLoggerrB   r   rg   r   r   <module>rl      sd    O  ( )# G 			5	!xC xC  Os   ? A	A	