def launchpadlib_credentials_for(consumer_name, person, permission=OAuthPermission.WRITE_PRIVATE, context=None): """Create launchpadlib credentials for the given person. :param consumer_name: An OAuth consumer name. :param person: A person (or the name of a person) for whom to create or find credentials. :param permission: An OAuthPermission (or its token) designating the level of permission the credentials should have. :param context: The OAuth context for the credentials. :return: A launchpadlib Credentials object. """ # Start an interaction so that oauth_access_token_for will # succeed. oauth_access_token_for may be called in any layer, but # launchpadlib_credentials_for is only called in the # PageTestLayer, when a Launchpad instance is running for # launchpadlib to use. login(ANONYMOUS) access_token = oauth_access_token_for(consumer_name, person, permission, context) logout() launchpadlib_token = AccessToken(access_token.key, access_token.secret) return Credentials(consumer_name=consumer_name, access_token=launchpadlib_token)
def launchpadlib_for(consumer_name, person=None, permission=OAuthPermission.WRITE_PRIVATE, context=None, version="devel", service_root="http://api.launchpad.dev/"): """Create a Launchpad object for the given person. :param consumer_name: An OAuth consumer name. :param person: A person (or the name of a person) for whom to create or find credentials. :param permission: An OAuthPermission (or its token) designating the level of permission the credentials should have. :param context: The OAuth context for the credentials. :param version: The version of the web service to access. :param service_root: The root URL of the web service to access. :return: A launchpadlib Launchpad object. """ if person is None: token = AnonymousAccessToken() credentials = Credentials(consumer_name, access_token=token) else: credentials = launchpadlib_credentials_for(consumer_name, person, permission, context) transaction.commit() cache = tempfile.mkdtemp(prefix='launchpadlib-cache-') zope.testing.cleanup.addCleanUp(_clean_up_cache, (cache, )) return Launchpad(credentials, None, None, service_root=service_root, version=version, cache=cache)
def test_existing_credentials_arguments_passed_on(self): # When re-using existing credentials, the arguments login_with # is called with are passed on the the __init__() method. os.makedirs( os.path.join(self.temp_dir, 'api.example.com', 'credentials')) credentials_file_path = os.path.join( self.temp_dir, 'api.example.com', 'credentials', 'app name') credentials = Credentials( 'app name', consumer_secret='consumer_secret:42', access_token=AccessToken('access_key:84', 'access_secret:168')) credentials.save_to_path(credentials_file_path) timeout = object() proxy_info = object() version = "foo" launchpad = NoNetworkLaunchpad.login_with( 'app name', launchpadlib_dir=self.temp_dir, service_root=SERVICE_ROOT, timeout=timeout, proxy_info=proxy_info, version=version) expected_arguments = dict( service_root=SERVICE_ROOT, timeout=timeout, proxy_info=proxy_info, version=version, cache=os.path.join(self.temp_dir, 'api.example.com', 'cache')) for key, expected in expected_arguments.items(): actual = launchpad.passed_in_args[key] self.assertEqual(actual, expected)
def create_session(): lplib_cachedir = os.path.expanduser("~/.cache/launchpadlib/") hydrazine_cachedir = os.path.expanduser("~/.cache/hydrazine/") rrd_dir = os.path.expanduser("~/.cache/hydrazine/rrd") for d in [lplib_cachedir, hydrazine_cachedir, rrd_dir]: if not os.path.isdir(d): os.makedirs(d, mode=0700) hydrazine_credentials_filename = os.path.join(hydrazine_cachedir, 'credentials') if os.path.exists(hydrazine_credentials_filename): credentials = Credentials() credentials.load(file( os.path.expanduser("~/.cache/hydrazine/credentials"), "r")) trace('loaded existing credentials') return Launchpad(credentials, service_root, lplib_cachedir) # TODO: handle the case of having credentials that have expired etc else: launchpad = Launchpad.get_token_and_login( 'Hydrazine', service_root, lplib_cachedir) trace('saving credentials...') launchpad.credentials.save(file( hydrazine_credentials_filename, "w")) return launchpad
def _authorize_token_and_login( cls, consumer_name, service_root, cache, timeout, proxy_info, authorization_engine, allow_access_levels, credential_store, credential_save_failed, version): """Authorize a request token. Log in with the resulting access token. This is the private, non-deprecated implementation of the deprecated method get_token_and_login(). Once get_token_and_login() is removed, this code can be streamlined and moved into its other call site, login_with(). """ if isinstance(consumer_name, Consumer): consumer = consumer_name else: # Create a system-wide consumer. lazr.restfulclient won't # do this automatically, but launchpadlib's default is to # do a desktop-wide integration. consumer = SystemWideConsumer(consumer_name) # Create the credentials with no Consumer, then set its .consumer # property directly. credentials = Credentials(None) credentials.consumer = consumer if authorization_engine is None: authorization_engine = cls.authorization_engine_factory( service_root, consumer_name, None, allow_access_levels) if credential_store is None: credential_store = cls.credential_store_factory( credential_save_failed) else: # A credential store was passed in, so we won't be using # any provided value for credential_save_failed. But at # least make sure we weren't given a conflicting value, # since that makes the calling code look confusing. cls._assert_login_argument_consistency( "credential_save_failed", credential_save_failed, credential_store.credential_save_failed, "credential_store") # Try to get the credentials out of the credential store. cached_credentials = credential_store.load( authorization_engine.unique_consumer_id) if cached_credentials is None: # They're not there. Acquire new credentials using the # authorization engine. credentials = authorization_engine(credentials, credential_store) else: # We acquired credentials. But, the application name # wasn't stored along with the credentials, because in a # desktop integration scenario, a single set of # credentials may be shared by many applications. We need # to set the application name for this specific instance # of the credentials. credentials = cached_credentials credentials.consumer.application_name = ( authorization_engine.application_name) return cls(credentials, authorization_engine, credential_store, service_root, cache, timeout, proxy_info, version)
def login(cls, consumer_name, token_string, access_secret, service_root=uris.STAGING_SERVICE_ROOT, cache=None, timeout=None, proxy_info=None, authorization_engine=None, allow_access_levels=None, max_failed_attempts=None, credential_store=None, credential_save_failed=None, version=DEFAULT_VERSION): """Convenience method for setting up access credentials. When all three pieces of credential information (the consumer name, the access token and the access secret) are available, this method can be used to quickly log into the service root. This method is deprecated as of launchpadlib version 1.9.0. You should use Launchpad.login_anonymously() for anonymous access, and Launchpad.login_with() for all other purposes. :param consumer_name: the application name. :type consumer_name: string :param token_string: the access token, as appropriate for the `AccessToken` constructor :type token_string: string :param access_secret: the access token's secret, as appropriate for the `AccessToken` constructor :type access_secret: string :param service_root: The URL to the root of the web service. :type service_root: string :param authorization_engine: See `Launchpad.__init__`. If you don't provide an authorization engine, a default engine will be constructed using your values for `service_root` and `credential_save_failed`. :param allow_access_levels: This argument is ignored, and only present to preserve backwards compatibility. :param max_failed_attempts: This argument is ignored, and only present to preserve backwards compatibility. :return: The web service root :rtype: `Launchpad` """ cls._warn_of_deprecated_login_method("login") access_token = AccessToken(token_string, access_secret) credentials = Credentials(consumer_name=consumer_name, access_token=access_token) if authorization_engine is None: authorization_engine = cls.authorization_engine_factory( service_root, consumer_name, allow_access_levels) if credential_store is None: credential_store = cls.credential_store_factory( credential_save_failed) return cls(credentials, authorization_engine, credential_store, service_root, cache, timeout, proxy_info, version)
def login_anonymously( cls, consumer_name, service_root=uris.STAGING_SERVICE_ROOT, launchpadlib_dir=None, timeout=None, proxy_info=proxy_info_from_environment, version=DEFAULT_VERSION): """Get access to Launchpad without providing any credentials.""" (service_root, launchpadlib_dir, cache_path, service_root_dir) = cls._get_paths(service_root, launchpadlib_dir) token = AnonymousAccessToken() credentials = Credentials(consumer_name, access_token=token) return cls(credentials, None, None, service_root=service_root, cache=cache_path, timeout=timeout, proxy_info=proxy_info, version=version)
def get_lp(self): launchpad = False cachedir = os.path.expanduser('~/.launchpadlib/cache') if not os.path.exists(cachedir): os.makedirs(cachedir,0700) credfile = os.path.expanduser('~/.launchpadlib/credentials') try: credentials = Credentials() credentials.load(open(credfile)) launchpad = Launchpad(credentials, EDGE_SERVICE_ROOT, cachedir) except: launchpad = Launchpad.get_token_and_login(sys.argv[0], EDGE_SERVICE_ROOT, cachedir) return launchpad
def process_launchpad_authorization(): global user_agents credentials = Credentials() SimpleLaunchpad.set_credentials_consumer(credentials, "launchpad-reporting-www") if 'should_authorize' in session and session['should_authorize']: if 'request_token_parts' in session: return get_access_token(credentials) elif 'access_token_parts' in session: return use_access_token(credentials) else: return get_and_authorize_request_token(credentials) else: return (False, None, False)
def get_lp(self): if not os.path.isdir(self.cachedir): os.makedirs(self.cachedir) if not os.path.isfile(self.credential_file): launchpad = Launchpad.get_token_and_login(self.application, STAGING_SERVICE_ROOT, self.cachedir) launchpad.credentials.save(file(self.credential_file, "w")) else: credentials = Credentials() credentials.load(open(self.credential_file)) launchpad = Launchpad(credentials, STAGING_SERVICE_ROOT, self.cachedir) return launchpad
def get_launchpad(): if not HAVE_LPLIB: return None try: return Launchpad.login_anonymously("bzr-builddeb", service_root=LPNET_SERVICE_ROOT) except AttributeError: # older version of launchpadlib creds_path = os.path.join(config_dir(), "builddeb.lp_creds.txt") if not os.path.exists(creds_path): return None creds = Credentials("bzr-builddeb") f = open(creds_path) try: creds.load(f) finally: f.close() return Launchpad(creds, service_root=LPNET_SERVICE_ROOT)
def connect(): cachedir = os.path.expanduser('~/.launchpadlib/cache') if not os.path.exists(cachedir): os.makedirs(cachedir, 0700) credfile = os.path.expanduser('~/.launchpadlib/credentials') try: credentials = Credentials() credentials.load(open(credfile)) launchpad = Launchpad(credentials, EDGE_SERVICE_ROOT, cachedir) except: launchpad = Launchpad.get_token_and_login(sys.argv[0], EDGE_SERVICE_ROOT, cachedir) credfd = tempfile.NamedTemporaryFile(dir=os.path.dirname(credfile)) launchpad.credentials.save(credfd) os.link(credfd.name, credfile) credfd.close() return launchpad
def get_lp(self): launchpad = False if not os.path.isdir(self.cachedir): try: os.makedirs(self.cachedir) except: raise if not os.path.isfile(self.lp_credential_file): try: launchpad = Launchpad.get_token_and_login( 'openerp', EDGE_SERVICE_ROOT, self.cachedir) launchpad.credentials.save(file(self.lp_credential_file, "w")) except: print 'Service Unavailable !' else: credentials = Credentials() credentials.load(open(self.lp_credential_file)) launchpad = Launchpad(credentials, EDGE_SERVICE_ROOT, self.cachedir) return launchpad
def login(self): if self.launchpad is not None: return cachedir = os.path.expanduser('~/.cache/launchpadlib') creddir = os.path.expanduser('~/.config/launchpadlib') credfile = creddir + '/credentials.txt' root = EDGE_SERVICE_ROOT if not os.path.exists(cachedir): os.makedirs(cachedir, 0700) try: credentials = Credentials() credentials.load(open(credfile)) self.launchpad = Launchpad(credentials, root, cachedir) except: self.launchpad = Launchpad.get_token_and_login('igotu2gpx-launchpad-tools', root, cachedir) if not os.path.exists(creddir): os.makedirs(creddir, 0700) self.launchpad.credentials.save(open(credfile, "w", 0600)) self.project = self.launchpad.projects['igotu2gpx']
def launchpad(self): '''Return Launchpad instance.''' if self.__launchpad: return self.__launchpad if self.options.get('staging') or os.getenv('APPORT_STAGING'): launchpad_instance = STAGING_SERVICE_ROOT else: launchpad_instance = EDGE_SERVICE_ROOT auth_dir = os.path.dirname(self.auth) if auth_dir and not os.path.isdir(auth_dir): os.makedirs(auth_dir) try: if os.path.exists(self.auth): # use existing credentials credentials = Credentials() credentials.load(open(self.auth)) self.__launchpad = Launchpad(credentials, launchpad_instance, self.__lpcache) else: # get credentials and save them try: self.__launchpad = Launchpad.get_token_and_login( 'apport-collect', launchpad_instance, self.__lpcache) except HTTPError, e: print >> sys.stderr, 'Error connecting to Launchpad: %s\nYou have to allow "Change anything" privileges.' % str( e) sys.exit(1) f = open(self.auth, 'w') os.chmod(self.auth, 0600) self.__launchpad.credentials.save(f) f.close() except (socket.error, ServerNotFoundError), e: print >> sys.stderr, 'Error connecting to Launchpad: %s' % str(e) sys.exit(99) # transient error
def lp_login(): cachedir = os.path.expanduser('~/.cache/launchpadlib/') if not os.path.isdir(cachedir): os.makedirs(cachedir) creddir = os.path.expanduser("~/.cache/lp_credentials") if not os.path.isdir(creddir): os.makedirs(creddir) os.chmod(creddir, 0o700) credpath = os.path.join(creddir, 'close_launchpad_bugs.txt') try: credfile = open(credpath, 'r') credentials = Credentials() credentials.load(credfile) credfile.close() launchpad = Launchpad(credentials, EDGE_SERVICE_ROOT, cachedir) except IOError: launchpad = Launchpad.get_token_and_login('close_launchpad_bugs', EDGE_SERVICE_ROOT, cachedir) credfile = open(credpath, 'w') launchpad.credentials.save(credfile) credfile.close() return launchpad
sys.exit(1) changelog = 'debian/changelog' if not os.path.exists(changelog): changelog = "./changelog" if not os.path.exists(changelog): print "File " + changelog + " not found" sys.exit(2) home = os.environ['HOME'] cachedir = home + '/.launchpadlib/cache/' launchpad_key = home + "/.launchpadlib/key.txt" credentials = Credentials() credentials.load(open(launchpad_key)) #launchpad = Launchpad(credentials, EDGE_SERVICE_ROOT, cachedir) launchpad = Launchpad.login_with('GetDeb.net Bug Manager', 'production') me = launchpad.me project_name = "GetDeb Software Portal" if sys.argv[1] == 'start' or sys.argv[1].startswith('s'): current_changelog = get_changelog(1, changelog) previous_changelog = get_changelog(2, changelog) bug_ids = current_changelog['bugs_to_be_closed'] check_not_empty(bug_ids)
try: bug = LP.bugs[bug_id] except Exception, e: self.msg(dst, 'Could not find lp bug %i, %s' % (bug_id, str(e))) return owner = str(bug.owner).split('~', 1)[1] self.msg( dst, str('LP bug #%i, %s (%s) by %s' % (bug_id, bug.title, bug.self_link, owner))) # this is the module initialization process if we are imported. if __name__ == 'lpbugs': creds = Credentials() creds.load(open('%s/lpcreds.txt' % CONFDIR)) LP = Launchpad(creds, EDGE_SERVICE_ROOT, CACHEDIR) core.MODULES.append(__name__) log('%s Loaded Successfully' % __name__) # This is the setup initialization process if __name__ == '__main__': if not os.path.exists(CACHEDIR): print "Creating conf and cache dir" try: os.makedirs(CACHEDIR) except Exception, e: print 'Error creating directories, %s' % str(e) sys.exit(1)
def make_credential(self, consumer_key): """Helper method to make a fake credential.""" return Credentials("app name", consumer_secret='consumer_secret:42', access_token=AccessToken(consumer_key, 'access_secret:168'))
# Free Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program. If not, see <http://www.gnu.org/licenses/>. import subprocess import sys from launchpadlib.credentials import Credentials web_root = "https://launchpad.net/" creds = Credentials("tarmac") url = creds.get_request_token(web_root=web_root) subprocess.call(['xdg-open', url]) print("Once you have authenticated then press enter") sys.stdin.readline() creds.exchange_request_token_for_access_token(web_root=web_root) f = open("credentials", "wb") try: creds.save(f) finally: f.close()
import json, time from launchpadlib.credentials import Credentials from lazr.restfulclient.errors import HTTPError credentials = Credentials("launchpad-reporting-www") request_token_info = credentials.get_request_token(web_root="production") print request_token_info print '**** *** sleeping (while you validate token in the browser) *** ***' time.sleep(15) print '**** *** continuing *** ***' credentials.exchange_request_token_for_access_token(web_root="production") print json.dumps(credentials)
def __init__(self, token_string, access_secret): self.token_string = token_string self.access_secret = access_secret self.token = AccessToken(token_string, access_secret) self.credentials = Credentials(consumer_name="launchpad-library", access_token=self.token)
# Free Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program. If not, see <http://www.gnu.org/licenses/>. import subprocess import sys from launchpadlib.credentials import Credentials web_root = "https://launchpad.net/" creds = Credentials("process-merge-requests") url = creds.get_request_token(web_root=web_root) subprocess.call(['xdg-open', url]) print("Once you have authenticated then press enter") sys.stdin.readline() creds.exchange_request_token_for_access_token(web_root=web_root) f = open("credentials", "wb") try: creds.save(f) finally: f.close()
def __init__(self, web_root, consumer_name, context): """Initialize.""" self.web_root = lookup_web_root(web_root) self.credentials = Credentials(consumer_name) self.context = context