o ΔaZy@sddlmZ eZgdZzddlmZWney$ddlmZYnwddl Z ddl Z ddl Z ddl m Z ddl Z ddlmZddlZzddlmZWney\ddlmZYnwzddlmZWneytddlmZYnwddlZdd lmZmZdd lmZeeureZneZdd l m!Z!dd l"m#Z$m%Z%m&Z&m'Z'dd l(m)Z)dZ*dZ+dZ,dZ-dZ.e/e0e1fZ2ddZ3ddZ4Gddde&Z5Gddde$Z#Gddde$Z6Gddde7Z8Gdd d e8Z9Gd!d"d"e8Z:Gd#d$d$e8Z;Gd%d&d&e7ZGd+d,d,e?Z@Gd-d.d.e@ZAGd/d0d0e@ZBGd1d2d2eBZCGd3d4d4eBZDGd5d6d6eDZEGd7d8d8e@ZFGd9d:d:e@ZGGd;d<dd>e@ZIdS)?)print_function) AccessTokenAnonymousAccessToken AuthorizeRequestTokenWithBrowserCredentialStoreRequestTokenAuthorizationEngineConsumer Credentials)StringION)select)stdin) urlencode)urljoin) b64decode b64encode)parse_qs) HTTPError)rrOAuthAuthorizerSystemWideConsumer)urisz+request-tokenz +access-tokenz+authorize-tokenicCsttjddS)zWhether the user has disabled SSL certificate connection. Some testing servers have broken certificates. Rather than raising an error, we allow an environment variable, ``LP_DISABLE_SSL_CERTIFICATE_VALIDATION`` to disable the check. %LP_DISABLE_SSL_CERTIFICATE_VALIDATIONF)boolosenvirongetrr:/usr/lib/python3/dist-packages/launchpadlib/credentials.py$_ssl_certificate_validation_disabledVs rcCsDt}tj|dj|d|t|d\}}|jdkrt||||fS)zPOST to ``url`` with ``headers`` and a body of urlencoded ``params``. Wraps it up to make sure we avoid the SSL certificate validation if our environment tells us to. Also, raises an error on non-200 statuses. )"disable_ssl_certificate_validationPOST)methodheadersbody)rhttplib2Httprequestr statusr)urlr"params cert_disabledresponsecontentrrr _http_postcs  r.c@sXeZdZdZdZdZdZdZdZddZ e d d Z de j efd d Ze j fd dZdS)r zStandard credentials storage and usage class. :ivar consumer: The consumer (application) :type consumer: `Consumer` :ivar access_token: Access information on behalf of the user :type access_token: `AccessToken` Nuridictz
 cCs0t}|||}t|tr|d}|S)zeTurn this object into a string. This should probably be moved into OAuthAuthorizer. utf-8)r savegetvalue isinstance unicode_typeencode)selfsio serializedrrr serializes    zCredentials.serializecCs,|}t|ts |d}|t||S)z}Create a `Credentials` object from a serialized string. This should probably be moved into OAuthAuthorizer. r2)r5r6decodeloadr )clsvalue credentialsrrr from_strings   zCredentials.from_stringc Cs|jdus Jd|jdusJdt|}t|jjddd}|t}d|i}||jkr1d|d <t|||\}}t |t rC| d }||jkr]t |}|durU||d <t||_|St||_d |t|jjf}|durz||j_|d |7}|S)aRequest an OAuth token to Launchpad. Also store the token in self._request_token. This method must not be called on an object with no consumer specified or if an access token has already been obtained. :param context: The context of this token, that is, its scope of validity within Launchpad. :param web_root: The URL of the website on which the token should be requested. :token_format: How the token should be presented. URI_TOKEN_FORMAT means just return the URL to the page that authorizes the token. DICT_TOKEN_FORMAT means return a dictionary describing the token and the site's authentication policy. :return: If token_format is URI_TOKEN_FORMAT, the URL for the user to authorize the `AccessToken` provided by Launchpad. If token_format is DICT_TOKEN_FORMAT, a dict of information about the new access token. NzConsumer not specified.zAccess token already obtained. PLAINTEXT&)oauth_consumer_keyoauth_signature_methodoauth_signatureRefererzapplication/jsonAcceptr2 lp.contextz%s%s?oauth_token=%sz&lp.context=%s)consumer access_tokenrlookup_web_rootr0keyrequest_token_pageDICT_TOKEN_FORMATr.r5bytesr<jsonloadsr from_params_request_tokenrAauthorize_token_pagecontext) r8rVweb_root token_formatr*r)r"r,r-rrrget_request_tokens>         zCredentials.get_request_tokencCsl|jdus Jdt|}t|jjd|jjd|jjd}|t}d|i}t|||\}}t ||_ dS)adExchange the previously obtained request token for an access token. This method must not be called unless get_request_token() has been called and completed successfully. The access token will be stored as self.access_token. :param web_root: The base URL of the website that granted the request token. Nz5get_request_token() doesn't seem to have been called.rBz&%s)rDrE oauth_tokenrFrG) rTrrLr0rJrMsecretaccess_token_pager.rrArK)r8rWr*r)r"r,r-rrr'exchange_request_token_for_access_tokens   z3Credentials.exchange_request_token_for_access_token)__name__ __module__ __qualname____doc__rTURI_TOKEN_FORMATrOITEM_SEPARATORNEWLINEr; classmethodrArSTAGING_WEB_ROOTrYr]rrrrr rs    >r c@s(eZdZdZeddZeddZdS)rzAn OAuth access token.cCs&|d}|d}|d}||||S)z:Create and return a new `AccessToken` from the given dict.rZoauth_token_secretrI)r)r>r*rMr[rVrrrrSs  zAccessToken.from_paramscCst|ts |d}t|dd}|d}t|dksJd|d}|d}t|dks0Jd |d}|d }|d urKt|dksGJd |d}||||S) z query_stringr*rMr[rVrrrrAs     zAccessToken.from_stringN)r^r_r`rarerSrArrrrrs  rcs eZdZdZfddZZS)rzoAn OAuth access token that doesn't authenticate anybody. This token can be used for anonymous access. cstt|dddS)N)superr__init__r8 __class__rrrmszAnonymousAccessToken.__init__)r^r_r`rarm __classcell__rrrorrsrc@s:eZdZdZd ddZddZddZd d Zd d ZdS)rzStore OAuth credentials locally. This is a generic superclass. To implement a specific way of storing credentials locally you'll need to subclass this class, and implement `do_save` and `do_load`. NcCs ||_dS)aConstructor. :param credential_save_failed: A callback to be invoked if the save to local storage fails. You should never invoke this callback yourself! Instead, you should raise an exception from do_save(). N)credential_save_failedr8rrrrrrm&s zCredentialStore.__init__c Cs^z |||W|Styty.}z|jdur||WYd}~|Sd}~ww)zSave the credentials and invoke the callback on failure. Do not override this method when subclassing. Override do_save() instead. N)do_saveEXPLOSIVE_ERRORS Exceptionrr)r8r@unique_consumer_iderrrr30s  zCredentialStore.savecCt)zStore newly-authorized credentials locally for later use. :param credentials: A Credentials object to save. :param unique_consumer_id: A string uniquely identifying an OAuth consumer on a Launchpad instance. NotImplementedError)r8r@rwrrrrt@szCredentialStore.do_savecCs ||S)a0Retrieve credentials from a local store. This method is the inverse of `save`. There's no special behavior in this method--it just calls `do_load`. There _is_ special behavior in `save`, and this way, developers can remember to implement `do_save` and `do_load`, not `do_save` and `load`. :param unique_key: A string uniquely identifying an OAuth consumer on a Launchpad instance. :return: A `Credentials` object if one is found in the local store, and None otherise. )do_loadr8 unique_keyrrrr=Is zCredentialStore.loadcCry)a@Retrieve credentials from a local store. This method is the inverse of `do_save`. :param unique_key: A string uniquely identifying an OAuth consumer on a Launchpad instance. :return: A `Credentials` object if one is found in the local store, and None otherise. rzr}rrrr|[s zCredentialStore.do_loadN) r^r_r`rarmr3rtr=r|rrrrrs   rcsBeZdZdZdZd fdd ZeddZd d Zd d Z Z S)KeyringCredentialStorezStore credentials in the GNOME keyring or KDE wallet. This is a good solution for desktop applications and interactive scripts. It doesn't work for non-interactive scripts, or for integrating third-party websites into Launchpad. sNFcs,tt||d|_|rt||_dSdSr)rlrrm _fallbackMemoryCredentialStore)r8rrfallbackrorrrmss zKeyringCredentialStore.__init__cCsLdtvr ddladtvr$z ddlmaWdSty#taYdSwdS)aGEnsure the keyring module is imported (postponing side effects). The keyring module initializes the environment-dependent backend at import time (nasty). We want to avoid that initialization because it may do things like prompt the user to unlock their password store (e.g., KWallet). keyringrNNoKeyringError)r)globalsrkeyring.errorsr ImportError RuntimeErrorrrrr_ensure_keyring_importedys    z/KeyringCredentialStore._ensure_keyring_importedc Cs||}|jt|}z td||dWdStyF}zttkr/dt |vr/|j r:|j ||nWYd}~dSd}~ww)z2Store newly-authorized credentials in the keyring. launchpadlibr2$No recommended backend was availableN) rr; B64MARKERrr set_passwordr<rrstrrr3)r8r@r~r:rxrrrrts"   zKeyringCredentialStore.do_savec Cs|ztd|}Wn'ty3}zttkrdt|vr|jr.|j|WYd}~Sd}~ww|durst|t rB| d}| |j r`z t |t|j d}Wn ty_YdSwzt|}|WStyrYdSwdS)z&Retrieve credentials from the keyring.rrNutf8)rr get_passwordrrrrr=r5r6r7 startswithrrri TypeErrorr rArv)r8r~credential_stringrxr@rrrr|s@       zKeyringCredentialStore.do_load)NF) r^r_r`rarrm staticmethodrrtr|rqrrrorris rc2eZdZdZd fdd ZddZddZZS) UnencryptedFileCredentialStorezStore credentials unencrypted in a file on disk. This is a good solution for scripts that need to run without any user interaction. Ncstt||||_dSr)rlrrmfilename)r8rrrrorrrms  z'UnencryptedFileCredentialStore.__init__cCs||jdS)zSave the credentials to disk.N) save_to_pathrr8r@r~rrrrtsz&UnencryptedFileCredentialStore.do_savecCs4tj|jrt|jtjdkst|jSdS)zLoad the credentials from disk.rN)rpathexistsrstatST_SIZEr load_from_pathr}rrrr|s  z&UnencryptedFileCredentialStore.do_loadrr^r_r`rarmrtr|rqrrrorrs rcr) rzCredentialStore that stores keys only in memory. This can be used to provide a CredentialStore instance without actually saving any key to persistent storage. Ncstt||i|_dSr)rlrrm _credentialsrsrorrrms zMemoryCredentialStore.__init__cCs||j|<dS)z!Store the credentials in our dictN)rrrrrrtszMemoryCredentialStore.do_savecCs |j|S)z&Retrieve the credentials from our dict)rrr}rrrr|s zMemoryCredentialStore.do_loadrrrrrorrs rc@sPeZdZdZdZ   dddZeddZdd Zd d Z d d Z ddZ dS)ra/The superclass of all request token authorizers. This base class does not implement request token authorization, since that varies depending on how you want the end-user to authorize a request token. You'll need to subclass this class and implement `make_end_user_authorize_token`. UNAUTHORIZEDNcCst||_t||_|dur|durtd|dur(|dur(td||f|dur4dg}t|}nt|}|}||_||_ |pCg|_ dS)aDBase class initialization. :param service_root: The root of the Launchpad instance being used. :param application_name: The name of the application that wants to use launchpadlib. This is used in conjunction with a desktop-wide integration. If you specify this argument, your values for consumer_name and allow_access_levels are ignored. :param consumer_name: The OAuth consumer name, for an application that wants its own point of integration into Launchpad. In almost all cases, you want to specify application_name instead and do a desktop-wide integration. The exception is when you're integrating a third-party website into Launchpad. :param allow_access_levels: A list of the Launchpad access levels to present to the user. ('READ_PUBLIC' and so on.) Your value for this argument will be ignored during a desktop-wide integration. :type allow_access_levels: A list of strings. Nz:You must provide either application_name or consumer_name.zZYou must provide only one of application_name and consumer_name. (You provided %r and %r.)DESKTOP_INTEGRATION) rlookup_service_root service_rootweb_root_for_service_rootrW ValueErrorrrrJapplication_nameallow_access_levels)r8rr consumer_namerrJrrrrm s(  z(RequestTokenAuthorizationEngine.__init__cCs|jjd|jS)z7Return a string identifying this consumer on this host.@)rJrMrrnrrrrwIsz2RequestTokenAuthorizationEngine.unique_consumer_idcCs>dt|f}d}t|jdkr||||j7}t|j|S)zReturn the authorization URL for a request token. This is the URL the end-user must visit to authorize the token. How exactly does this happen? That depends on the subclass implementation. z%s?oauth_token=%sz&allow_permission=r)rUrirjoinrrW)r8 request_tokenpageallow_permissionrrrauthorization_urlNs  z1RequestTokenAuthorizationEngine.authorization_urlcCs6||}||||jdurdS|||j|S)adAuthorize a token and associate it with the given credentials. If the credential store runs into a problem storing the credential locally, the `credential_save_failed` callback will be invoked. The callback will not be invoked if there's a problem authorizing the credentials. :param credentials: A `Credentials` object. If the end-user authorizes these credentials, this object will have its .access_token property set. :param credential_store: A `CredentialStore` object. If the end-user authorizes the credentials, they will be persisted locally using this object. :return: If the credentials are successfully authorized, the return value is the `Credentials` object originally passed in. Otherwise the return value is None. N)rYmake_end_user_authorize_tokenrKr3rw)r8r@credential_storerequest_token_stringrrr__call__]s   z(RequestTokenAuthorizationEngine.__call__cCs|j|jtjd}|dS)z\Get a new request token from the server. :param return: The request token. )rWrXrZ)rYrWr rO)r8r@authorization_jsonrrrrY{sz1RequestTokenAuthorizationEngine.get_request_tokencCry)a5Authorize the given request token using the given credentials. Your subclass must implement this method: it has no default implementation. Because an access token may expire or be revoked in the middle of a session, this method may be called at arbitrary points in a launchpadlib session, or even multiple times during a single session (with a different request token each time). In most cases, however, this method will be called at the beginning of a launchpadlib session, or not at all. rz)r8r@rrrrrsz=RequestTokenAuthorizationEngine.make_end_user_authorize_tokenNNN) r^r_r`raUNAUTHORIZED_ACCESS_LEVELrmpropertyrwrrrYrrrrrrs @  rc@s@eZdZdZdZdZddZddZdd Zd d Z d d Z dS)AuthorizeRequestTokenWithURLzAuthorize using a URL. This authorizer simply shows the URL for the user to open for authorization, and waits until the server responds. zPlease open this authorization page: (%s) in your browser. Use your browser to authorize this program to access Launchpad on your behalf.z.Press Enter after authorizing in your browser.cCs t|dS)zDisplay a message. By default, prints the message to standard output. The message does not require any user interaction--it's solely informative. N)print)r8messagerrroutputs z#AuthorizeRequestTokenWithURL.outputcCs||j|dS)Notify the end-user of the URL.N)rWAITING_FOR_USER)r8rrrr!notify_end_user_authorization_urlsz>AuthorizeRequestTokenWithURL.notify_end_user_authorization_urlc Cspz||jWn*ty2}z|jjdkrt|j|jjdkr)tdt|t|jd}~ww|j duS)z Check if the end-user authorizediiz#Unexpected response from Launchpad:N) r]rWrr,r(EndUserDeclinedAuthorizationr-rEndUserNoAuthorizationrK)r8r@rxrrrcheck_end_user_authorizations     z9AuthorizeRequestTokenWithURL.check_end_user_authorizationcCs"||jt||dS)"Wait for the end-user to authorizeN)rWAITING_FOR_LAUNCHPADr readliner)r8r@rrrwait_for_end_user_authorizations zs              Kf;f