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 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 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)
Beispiel #4
0
    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 _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)
Beispiel #6
0
    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)
class ScriptableRequestTokenAuthorization(RequestTokenAuthorizationEngine):
    """A request token process that doesn't need any user input.

    The RequestTokenAuthorizationEngine is supposed to be hooked up to a
    user interface, but that makes it difficult to test. This subclass
    is designed to be easy to test.
    """

    def __init__(self, consumer_name, username, password, choose_access_level,
                 allow_access_levels=[], max_failed_attempts=2,
                 web_root="http://launchpad.dev:8085/"):

        # Get a request token.
        self.credentials = Credentials(consumer_name)
        self.credentials.get_request_token(web_root=web_root)

        # Initialize the superclass with the new request token.
        super(ScriptableRequestTokenAuthorization, self).__init__(
            web_root, consumer_name, self.credentials._request_token.key,
                allow_access_levels, max_failed_attempts)

        self.username = username
        self.password = password
        self.choose_access_level = choose_access_level

    def __call__(self, exchange_for_access_token=True):
        super(ScriptableRequestTokenAuthorization, self).__call__()

        # Now verify that it worked by exchanging the authorized
        # request token for an access token.
        if (exchange_for_access_token and
            self.choose_access_level != self.UNAUTHORIZED_ACCESS_LEVEL):
            self.credentials.exchange_request_token_for_access_token(
                web_root=self.web_root)
            return self.credentials.access_token
        return None

    def open_page_in_user_browser(self, url):
        """Print a status message."""
        print ("[If this were a real application, the end-user's web "
               "browser would be opened to %s]" % url)

    def input_username(self, cached_username, suggested_message):
        """Collect the Launchpad username from the end-user."""
        print suggested_message
        if cached_username is not None:
            print "Cached email address: " + cached_username
        return self.username

    def input_password(self, suggested_message):
        """Collect the Launchpad password from the end-user."""
        print suggested_message
        return self.password

    def input_access_level(self, available_levels, suggested_message,
                           only_one_option):
        """Collect the desired level of access from the end-user."""
        print suggested_message
        print [level['value'] for level in available_levels]
 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
Beispiel #9
0
def get_launchpad():
    """Get a Launchpad instance.

    @raise RuntimeError: Raised if credentials are not available.
    """
    credentials_path = os.path.join(get_config_path(), "credentials.txt")
    if not os.path.exists(credentials_path):
        raise RuntimeError(
            "Run the launchpad-login command to create OAuth credentials.")
    credentials = Credentials()
    credentials.load(open(credentials_path, "r"))
    return Launchpad(credentials, SERVICE_ROOT, get_cache_path())
 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
Beispiel #11
0
    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
Beispiel #12
0
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)
Beispiel #13
0
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)
Beispiel #14
0
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)
Beispiel #15
0
    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 get_token_and_login(cls, consumer_name,
                            service_root=uris.STAGING_SERVICE_ROOT,
                            cache=None, timeout=None, proxy_info=None,
                            authorizer_class=AuthorizeRequestTokenWithBrowser,
                            allow_access_levels=[], max_failed_attempts=3,
                            version=DEFAULT_VERSION):
        """Get credentials from Launchpad and log into the service root.

        This is a convenience method which will open up the user's preferred
        web browser and thus should not be used by most applications.
        Applications should, instead, use Credentials.get_request_token() to
        obtain the authorization URL and
        Credentials.exchange_request_token_for_access_token() to obtain the
        actual OAuth access token.

        This method will negotiate an OAuth access token with the service
        provider, but to complete it we will need the user to log into
        Launchpad and authorize us, so we'll open the authorization page in
        a web browser and ask the user to come back here and tell us when they
        finished the authorization process.

        :param consumer_name: The consumer name, as appropriate for the
            `Consumer` constructor
        :type consumer_name: string
        :param service_root: The URL to the root of the web service.
        :type service_root: string
        :return: The web service root
        :rtype: `Launchpad`
        """
        credentials = Credentials(consumer_name)
        service_root = uris.lookup_service_root(service_root)
        web_root_uri = URI(service_root)
        web_root_uri.path = ""
        web_root_uri.host = web_root_uri.host.replace("api.", "", 1)
        web_root = str(web_root_uri.ensureSlash())
        authorization_json = credentials.get_request_token(
            web_root=web_root, token_format=Credentials.DICT_TOKEN_FORMAT)
        authorizer = authorizer_class(
            web_root, authorization_json['oauth_token_consumer'],
            authorization_json['oauth_token'], allow_access_levels,
            max_failed_attempts)
        authorizer()
        credentials.exchange_request_token_for_access_token(web_root)
        return cls(credentials, service_root, cache, timeout, proxy_info,
                   version)
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
Beispiel #18
0
 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
Beispiel #19
0
 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 test_filename(self):
        ignore, filename = tempfile.mkstemp()
        launchpad = NoNetworkLaunchpad.login_with(
            application_name='not important', credentials_file=filename)

        # The credentials are stored unencrypted in the file you
        # specify.
        credentials = Credentials.load_from_path(filename)
        self.assertEquals(credentials.consumer.key,
                          launchpad.credentials.consumer.key)
        os.remove(filename)
Beispiel #21
0
    def test_filename(self):
        ignore, filename = tempfile.mkstemp()
        launchpad = NoNetworkLaunchpad.login_with(
            application_name='not important', credentials_file=filename)

        # The credentials are stored unencrypted in the file you
        # specify.
        credentials = Credentials.load_from_path(filename)
        self.assertEquals(credentials.consumer.key,
                          launchpad.credentials.consumer.key)
        os.remove(filename)
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, 0700)
        try:
                credfile = open(os.path.join(creddir, 'close_launchpad_bugs.txt'), '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(os.path.join(creddir, 'close_launchpad_bugs.txt'), 'w')
                launchpad.credentials.save(credfile)
                credfile.close()
        return launchpad
Beispiel #23
0
 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
Beispiel #24
0
 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)
Beispiel #25
0
    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 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 test_existing_credentials_are_reused(self):
        # If a credential file for the application already exists, that
        # one is used.
        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)

        launchpad = NoNetworkLaunchpad.login_with(
            'app name', launchpadlib_dir=self.temp_dir,
            service_root='http://api.example.com/beta')
        self.assertFalse(launchpad.get_token_and_login_called)
        self.assertEqual(launchpad.credentials.consumer.key, 'app name')
        self.assertEqual(
            launchpad.credentials.consumer.secret, 'consumer_secret:42')
        self.assertEqual(
            launchpad.credentials.access_token.key, 'access_key:84')
        self.assertEqual(
            launchpad.credentials.access_token.secret, 'access_secret:168')
Beispiel #28
0
    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
Beispiel #29
0
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
Beispiel #30
0
class RequestTokenApp(object):
    """An application that creates request tokens."""
    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

    def run(self):
        """Get a request token and return JSON information about it."""
        token = self.credentials.get_request_token(
            self.context,
            self.web_root,
            token_format=Credentials.DICT_TOKEN_FORMAT)
        return simplejson.dumps(token)
Beispiel #31
0
class RequestTokenApp(object):
    """An application that creates request tokens."""

    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

    def run(self):
        """Get a request token and return JSON information about it."""
        token = self.credentials.get_request_token(
            self.context, self.web_root,
            token_format=Credentials.DICT_TOKEN_FORMAT)
        return simplejson.dumps(token)
    def __init__(self, consumer_name, username, password, choose_access_level,
                 allow_access_levels=[], max_failed_attempts=2,
                 web_root="http://launchpad.dev:8085/"):

        # Get a request token.
        self.credentials = Credentials(consumer_name)
        self.credentials.get_request_token(web_root=web_root)

        # Initialize the superclass with the new request token.
        super(ScriptableRequestTokenAuthorization, self).__init__(
            web_root, consumer_name, self.credentials._request_token.key,
                allow_access_levels, max_failed_attempts)

        self.username = username
        self.password = password
        self.choose_access_level = choose_access_level
 def test_new_credentials_are_saved(self):
     # After get_token_and_login() have been called, the created
     # credentials are saved.
     launchpad = NoNetworkLaunchpad.login_with(
         'app name', launchpadlib_dir=self.temp_dir,
         service_root='http://api.example.com/beta')
     credentials_path = os.path.join(
         self.temp_dir, 'api.example.com', 'credentials', 'app name')
     self.assertTrue(os.path.exists(credentials_path))
     # Make sure that the credentials can be loaded, thus were
     # written correctly.
     loaded_credentials = Credentials.load_from_path(credentials_path)
     self.assertEqual(loaded_credentials.consumer.key, 'app name')
     self.assertEqual(
         loaded_credentials.consumer.secret, 'consumer_secret:42')
     self.assertEqual(
         loaded_credentials.access_token.key, 'access_key:84')
     self.assertEqual(
         loaded_credentials.access_token.secret, 'access_secret:168')
Beispiel #34
0
	print "Uploading", f
	finalDesc = FILE_DESCRIPTIONS[fType]
	if lang: finalDesc = finalDesc % (lang)
	try:
		releaseFile = release.add_file(filename = os.path.basename(f), description = finalDesc, file_content = open(f, 'r').read(), content_type = FILE_CONTENTTYPES[fType], file_type = FILE_TYPES[fType], signature_filename = fSign, signature_content = open(fSign, 'r').read())
	# Don't know why, but an exception will always be thrown even though the file is uploaded
	except lazr.restfulclient.errors.HTTPError:
		pass

for arg in sys.argv:
	if arg == "--auth":
		manualAuthentication()

if not launchpad:
	if os.path.exists(credentialsfile):
		credentials = Credentials()
		credentials.load(open(credentialsfile))
		launchpad = Launchpad(credentials, serviceRoot, cachedir)
	else:
		manualAuthentication()

project = launchpad.projects[projectName]
for release in project.releases:
	if release.version == lpRelease:
		gpgPass = getpass.getpass("Found the release. I will now create signature files - please enter your GPG private key passphrase: ")
		# Upload the source tarball
		if options.uploadsource: uploadFile('pack/source/tagainijisho-' + releaseVersion + '.tar.gz', 'source', '', gpgPass)
		# Upload the mac binaries
		if options.uploadmac:
			for lang in LANGUAGES:
				uploadFile('pack/MacOS/Tagaini Jisho-' + releaseVersion + '-' + LANGUAGES_SUFFIXES[lang] + '.dmg', 'mac', lang, gpgPass)
    def login_with(cls, consumer_name,
                   service_root=uris.STAGING_SERVICE_ROOT,
                   launchpadlib_dir=None, timeout=None, proxy_info=None,
                   authorizer_class=AuthorizeRequestTokenWithBrowser,
                   allow_access_levels=[], max_failed_attempts=3,
                   credentials_file=None, version=DEFAULT_VERSION):
        """Log in to Launchpad with possibly cached credentials.

        This is a convenience method for either setting up new login
        credentials, or re-using existing ones. When a login token is generated
        using this method, the resulting credentials will be saved in
        `credentials_file`, or if not given, into the `launchpadlib_dir`
        directory. If the same `credentials_file`/`launchpadlib_dir` is passed
        in a second time, the credentials in for the consumer will be used
        automatically.

        Each consumer has their own credentials per service root in
        `launchpadlib_dir`. `launchpadlib_dir` is also used for caching
        fetched objects. The cache is per service root, and shared by
        all consumers.

        See `Launchpad.get_token_and_login()` for more information about
        how new tokens are generated.

        :param consumer_name: The consumer name, as appropriate for the
            `Consumer` constructor
        :type consumer_name: string
        :param service_root: The URL to the root of the web service.
        :type service_root: string.  Can either be the full URL to a service
            or one of the short service names.
        :param launchpadlib_dir: The directory where the cache and
            credentials are stored.
        :type launchpadlib_dir: string
        :param credentials_file: If given, the credentials are stored in that
            file instead in `launchpadlib_dir`.
        :type credentials_file: string
        :return: The web service root
        :rtype: `Launchpad`

        """
        (service_root, launchpadlib_dir, cache_path,
         service_root_dir) = cls._get_paths(service_root, launchpadlib_dir)
        credentials_path = os.path.join(service_root_dir, 'credentials')
        if not os.path.exists(credentials_path):
            os.makedirs(credentials_path)
        if credentials_file is None:
            consumer_credentials_path = os.path.join(credentials_path,
                consumer_name)
        else:
            consumer_credentials_path = credentials_file
        if os.path.exists(consumer_credentials_path):
            credentials = Credentials.load_from_path(
                consumer_credentials_path)
            launchpad = cls(
                credentials, service_root=service_root, cache=cache_path,
                timeout=timeout, proxy_info=proxy_info, version=version)
        else:
            launchpad = cls.get_token_and_login(
                consumer_name, service_root=service_root, cache=cache_path,
                timeout=timeout, proxy_info=proxy_info,
                authorizer_class=authorizer_class,
                allow_access_levels=allow_access_levels,
                max_failed_attempts=max_failed_attempts, version=version)
            launchpad.credentials.save_to_path(consumer_credentials_path)
            os.chmod(consumer_credentials_path, stat.S_IREAD | stat.S_IWRITE)
        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)
Beispiel #37
0
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)

Beispiel #38
0
    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)
Beispiel #39
0
 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("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()
# 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()
		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)
Beispiel #43
0
 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
Beispiel #44
0
			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)
# 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()
 def authenticateFromSaved(self):
   credentials = Credentials()
   credentials.load(file(self.credentialsFilename, 'r'))
   self.launchpad = Launchpad(credentials, self.service, self.cacheDir)
Beispiel #47
0
 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)
Beispiel #48
0
 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
Beispiel #49
0
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)