| 1 |
# Copyright 2008-2009 Canonical Ltd. |
| 2 |
|
| 3 |
# This file is part of launchpadlib. |
| 4 |
# |
| 5 |
# launchpadlib is free software: you can redistribute it and/or modify it |
| 6 |
# under the terms of the GNU Lesser General Public License as published by the |
| 7 |
# Free Software Foundation, version 3 of the License. |
| 8 |
# |
| 9 |
# launchpadlib is distributed in the hope that it will be useful, but WITHOUT |
| 10 |
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 11 |
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License |
| 12 |
# for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU Lesser General Public License |
| 15 |
# along with launchpadlib. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
"""Root Launchpad API class.""" |
| 18 |
|
| 19 |
__all__ = [ |
| 20 |
"Launchpad", |
| 21 |
] |
| 22 |
|
| 23 |
import errno |
| 24 |
import os |
| 25 |
from urllib.parse import urlsplit |
| 26 |
import warnings |
| 27 |
|
| 28 |
try: |
| 29 |
from httplib2 import proxy_info_from_environment |
| 30 |
except ImportError: |
| 31 |
from httplib2 import ProxyInfo |
| 32 |
|
| 33 |
proxy_info_from_environment = ProxyInfo.from_environment |
| 34 |
|
| 35 |
from lazr.restfulclient.resource import ( # noqa: F401 |
| 36 |
CollectionWithKeyBasedLookup, |
| 37 |
HostedFile, # Re-import for client convenience |
| 38 |
ScalarValue, # Re-import for client convenience |
| 39 |
ServiceRoot, |
| 40 |
) |
| 41 |
from lazr.restfulclient.authorize.oauth import SystemWideConsumer |
| 42 |
from lazr.restfulclient._browser import RestfulHttp |
| 43 |
from launchpadlib.credentials import ( |
| 44 |
AccessToken, |
| 45 |
AnonymousAccessToken, |
| 46 |
AuthorizeRequestTokenWithBrowser, |
| 47 |
AuthorizeRequestTokenWithURL, |
| 48 |
Consumer, |
| 49 |
Credentials, |
| 50 |
MemoryCredentialStore, |
| 51 |
KeyringCredentialStore, |
| 52 |
UnencryptedFileCredentialStore, |
| 53 |
) |
| 54 |
from launchpadlib import uris |
| 55 |
|
| 56 |
|
| 57 |
# Import old constants for backwards compatibility |
| 58 |
from launchpadlib.uris import ( # noqa: F401 |
| 59 |
STAGING_SERVICE_ROOT, |
| 60 |
EDGE_SERVICE_ROOT, |
| 61 |
) |
| 62 |
|
| 63 |
OAUTH_REALM = "https://api.launchpad.net" |
| 64 |
|
| 65 |
|
| 66 |
class PersonSet(CollectionWithKeyBasedLookup): |
| 67 |
"""A custom subclass capable of person lookup by username.""" |
| 68 |
|
| 69 |
def _get_url_from_id(self, key): |
| 70 |
"""Transform a username into the URL to a person resource.""" |
| 71 |
return str(self._root._root_uri.ensureSlash()) + "~" + str(key) |
| 72 |
|
| 73 |
# The only way to determine whether a string corresponds to a |
| 74 |
# person or a team object is to ask the server, so looking up an |
| 75 |
# entry from the PersonSet always requires making an HTTP request. |
| 76 |
collection_of = "team" |
| 77 |
|
| 78 |
|
| 79 |
class BugSet(CollectionWithKeyBasedLookup): |
| 80 |
"""A custom subclass capable of bug lookup by bug ID.""" |
| 81 |
|
| 82 |
def _get_url_from_id(self, key): |
| 83 |
"""Transform a bug ID into the URL to a bug resource.""" |
| 84 |
return str(self._root._root_uri.ensureSlash()) + "bugs/" + str(key) |
| 85 |
|
| 86 |
collection_of = "bug" |
| 87 |
|
| 88 |
|
| 89 |
class PillarSet(CollectionWithKeyBasedLookup): |
| 90 |
"""A custom subclass capable of lookup by pillar name. |
| 91 |
|
| 92 |
Projects, project groups, and distributions are all pillars. |
| 93 |
""" |
| 94 |
|
| 95 |
def _get_url_from_id(self, key): |
| 96 |
"""Transform a project name into the URL to a project resource.""" |
| 97 |
return str(self._root._root_uri.ensureSlash()) + str(key) |
| 98 |
|
| 99 |
# The subclasses for projects, project groups, and distributions |
| 100 |
# all define this property differently. |
| 101 |
collection_of = None |
| 102 |
|
| 103 |
|
| 104 |
class ProjectSet(PillarSet): |
| 105 |
"""A custom subclass for accessing the collection of projects.""" |
| 106 |
|
| 107 |
collection_of = "project" |
| 108 |
|
| 109 |
|
| 110 |
class ProjectGroupSet(PillarSet): |
| 111 |
"""A custom subclass for accessing the collection of project groups.""" |
| 112 |
|
| 113 |
collection_of = "project_group" |
| 114 |
|
| 115 |
|
| 116 |
class DistributionSet(PillarSet): |
| 117 |
"""A custom subclass for accessing the collection of project groups.""" |
| 118 |
|
| 119 |
collection_of = "distribution" |
| 120 |
|
| 121 |
|
| 122 |
class LaunchpadOAuthAwareHttp(RestfulHttp): |
| 123 |
"""Detects expired/invalid OAuth tokens and tries to get a new token.""" |
| 124 |
|
| 125 |
def __init__(self, launchpad, authorization_engine, *args): |
| 126 |
self.launchpad = launchpad |
| 127 |
self.authorization_engine = authorization_engine |
| 128 |
super().__init__(*args) |
| 129 |
|
| 130 |
def _bad_oauth_token(self, response, content): |
| 131 |
"""Helper method to detect an error caused by a bad OAuth token.""" |
| 132 |
return response.status == 401 and ( |
| 133 |
content.startswith(b"Expired token") |
| 134 |
or content.startswith(b"Invalid token") |
| 135 |
or content.startswith(b"Unknown access token") |
| 136 |
) |
| 137 |
|
| 138 |
def _request(self, *args): |
| 139 |
response, content = super()._request(*args) |
| 140 |
return self.retry_on_bad_token(response, content, *args) |
| 141 |
|
| 142 |
def retry_on_bad_token(self, response, content, *args): |
| 143 |
"""If the response indicates a bad token, get a new token and retry. |
| 144 |
|
| 145 |
Otherwise, just return the response. |
| 146 |
""" |
| 147 |
if ( |
| 148 |
self._bad_oauth_token(response, content) |
| 149 |
and self.authorization_engine is not None |
| 150 |
): |
| 151 |
# This access token is bad. Scrap it and create a new one. |
| 152 |
self.launchpad.credentials.access_token = None |
| 153 |
self.authorization_engine( |
| 154 |
self.launchpad.credentials, self.launchpad.credential_store |
| 155 |
) |
| 156 |
# Retry the request with the new credentials. |
| 157 |
return self._request(*args) |
| 158 |
return response, content |
| 159 |
|
| 160 |
|
| 161 |
class Launchpad(ServiceRoot): |
| 162 |
"""Root Launchpad API class. |
| 163 |
|
| 164 |
:ivar credentials: The credentials instance used to access Launchpad. |
| 165 |
:type credentials: `Credentials` |
| 166 |
""" |
| 167 |
|
| 168 |
DEFAULT_VERSION = "1.0" |
| 169 |
|
| 170 |
RESOURCE_TYPE_CLASSES = { |
| 171 |
"bugs": BugSet, |
| 172 |
"distributions": DistributionSet, |
| 173 |
"people": PersonSet, |
| 174 |
"project_groups": ProjectGroupSet, |
| 175 |
"projects": ProjectSet, |
| 176 |
} |
| 177 |
RESOURCE_TYPE_CLASSES.update(ServiceRoot.RESOURCE_TYPE_CLASSES) |
| 178 |
|
| 179 |
def __init__( |
| 180 |
self, |
| 181 |
credentials, |
| 182 |
authorization_engine, |
| 183 |
credential_store, |
| 184 |
service_root=uris.STAGING_SERVICE_ROOT, |
| 185 |
cache=None, |
| 186 |
timeout=None, |
| 187 |
proxy_info=proxy_info_from_environment, |
| 188 |
version=DEFAULT_VERSION, |
| 189 |
): |
| 190 |
"""Root access to the Launchpad API. |
| 191 |
|
| 192 |
:param credentials: The credentials used to access Launchpad. |
| 193 |
:type credentials: `Credentials` |
| 194 |
:param authorization_engine: The object used to get end-user input |
| 195 |
for authorizing OAuth request tokens. Used when an OAuth |
| 196 |
access token expires or becomes invalid during a |
| 197 |
session, or is discovered to be invalid once launchpadlib |
| 198 |
starts up. |
| 199 |
:type authorization_engine: `RequestTokenAuthorizationEngine` |
| 200 |
:param service_root: The URL to the root of the web service. |
| 201 |
:type service_root: string |
| 202 |
""" |
| 203 |
service_root = uris.lookup_service_root(service_root) |
| 204 |
if service_root.endswith(version) or service_root.endswith( |
| 205 |
version + "/" |
| 206 |
): |
| 207 |
error = ( |
| 208 |
"It looks like you're using a service root that " |
| 209 |
"incorporates the name of the web service version " |
| 210 |
'("%s"). Please use one of the constants from ' |
| 211 |
"launchpadlib.uris instead, or at least remove " |
| 212 |
"the version name from the root URI." % version |
| 213 |
) |
| 214 |
raise ValueError(error) |
| 215 |
|
| 216 |
self.credential_store = credential_store |
| 217 |
|
| 218 |
# We already have an access token, but it might expire or |
| 219 |
# become invalid during use. Store the authorization engine in |
| 220 |
# case we need to authorize a new token during use. |
| 221 |
self.authorization_engine = authorization_engine |
| 222 |
|
| 223 |
super().__init__( |
| 224 |
credentials, service_root, cache, timeout, proxy_info, version |
| 225 |
) |
| 226 |
|
| 227 |
def httpFactory(self, credentials, cache, timeout, proxy_info): |
| 228 |
return LaunchpadOAuthAwareHttp( |
| 229 |
self, |
| 230 |
self.authorization_engine, |
| 231 |
credentials, |
| 232 |
cache, |
| 233 |
timeout, |
| 234 |
proxy_info, |
| 235 |
) |
| 236 |
|
| 237 |
@classmethod |
| 238 |
def _is_sudo(cls): |
| 239 |
return {"SUDO_USER", "SUDO_UID", "SUDO_GID"} & set(os.environ.keys()) |
| 240 |
|
| 241 |
@classmethod |
| 242 |
def authorization_engine_factory(cls, *args): |
| 243 |
if cls._is_sudo(): |
| 244 |
# Do not try to open browser window under sudo; |
| 245 |
# we probably don't have access to the X session, |
| 246 |
# and some browsers (e.g. chromium) won't run as root |
| 247 |
# LP: #1825014 |
| 248 |
return AuthorizeRequestTokenWithURL(*args) |
| 249 |
return AuthorizeRequestTokenWithBrowser(*args) |
| 250 |
|
| 251 |
@classmethod |
| 252 |
def credential_store_factory(cls, credential_save_failed): |
| 253 |
if cls._is_sudo(): |
| 254 |
# Do not try to store credentials under sudo; |
| 255 |
# it can be problematic with shared sudo access, |
| 256 |
# and we may not have access to the normal keyring provider |
| 257 |
# LP: #1862948 |
| 258 |
return MemoryCredentialStore(credential_save_failed) |
| 259 |
return KeyringCredentialStore(credential_save_failed, fallback=True) |
| 260 |
|
| 261 |
@classmethod |
| 262 |
def login( |
| 263 |
cls, |
| 264 |
consumer_name, |
| 265 |
token_string, |
| 266 |
access_secret, |
| 267 |
service_root=uris.STAGING_SERVICE_ROOT, |
| 268 |
cache=None, |
| 269 |
timeout=None, |
| 270 |
proxy_info=proxy_info_from_environment, |
| 271 |
authorization_engine=None, |
| 272 |
allow_access_levels=None, |
| 273 |
max_failed_attempts=None, |
| 274 |
credential_store=None, |
| 275 |
credential_save_failed=None, |
| 276 |
version=DEFAULT_VERSION, |
| 277 |
): |
| 278 |
"""Convenience method for setting up access credentials. |
| 279 |
|
| 280 |
When all three pieces of credential information (the consumer |
| 281 |
name, the access token and the access secret) are available, this |
| 282 |
method can be used to quickly log into the service root. |
| 283 |
|
| 284 |
This method is deprecated as of launchpadlib version |
| 285 |
1.9.0. You should use Launchpad.login_anonymously() for |
| 286 |
anonymous access, and Launchpad.login_with() for all other |
| 287 |
purposes. |
| 288 |
|
| 289 |
:param consumer_name: the application name. |
| 290 |
:type consumer_name: string |
| 291 |
:param token_string: the access token, as appropriate for the |
| 292 |
`AccessToken` constructor |
| 293 |
:type token_string: string |
| 294 |
:param access_secret: the access token's secret, as appropriate for |
| 295 |
the `AccessToken` constructor |
| 296 |
:type access_secret: string |
| 297 |
:param service_root: The URL to the root of the web service. |
| 298 |
:type service_root: string |
| 299 |
:param authorization_engine: See `Launchpad.__init__`. If you don't |
| 300 |
provide an authorization engine, a default engine will be |
| 301 |
constructed using your values for `service_root` and |
| 302 |
`credential_save_failed`. |
| 303 |
:param allow_access_levels: This argument is ignored, and only |
| 304 |
present to preserve backwards compatibility. |
| 305 |
:param max_failed_attempts: This argument is ignored, and only |
| 306 |
present to preserve backwards compatibility. |
| 307 |
:return: The web service root |
| 308 |
:rtype: `Launchpad` |
| 309 |
""" |
| 310 |
cls._warn_of_deprecated_login_method("login") |
| 311 |
access_token = AccessToken(token_string, access_secret) |
| 312 |
credentials = Credentials( |
| 313 |
consumer_name=consumer_name, access_token=access_token |
| 314 |
) |
| 315 |
if authorization_engine is None: |
| 316 |
authorization_engine = cls.authorization_engine_factory( |
| 317 |
service_root, consumer_name, allow_access_levels |
| 318 |
) |
| 319 |
if credential_store is None: |
| 320 |
credential_store = cls.credential_store_factory( |
| 321 |
credential_save_failed |
| 322 |
) |
| 323 |
return cls( |
| 324 |
credentials, |
| 325 |
authorization_engine, |
| 326 |
credential_store, |
| 327 |
service_root, |
| 328 |
cache, |
| 329 |
timeout, |
| 330 |
proxy_info, |
| 331 |
version, |
| 332 |
) |
| 333 |
|
| 334 |
@classmethod |
| 335 |
def get_token_and_login( |
| 336 |
cls, |
| 337 |
consumer_name, |
| 338 |
service_root=uris.STAGING_SERVICE_ROOT, |
| 339 |
cache=None, |
| 340 |
timeout=None, |
| 341 |
proxy_info=proxy_info_from_environment, |
| 342 |
authorization_engine=None, |
| 343 |
allow_access_levels=[], |
| 344 |
max_failed_attempts=None, |
| 345 |
credential_store=None, |
| 346 |
credential_save_failed=None, |
| 347 |
version=DEFAULT_VERSION, |
| 348 |
): |
| 349 |
"""Get credentials from Launchpad and log into the service root. |
| 350 |
|
| 351 |
This method is deprecated as of launchpadlib version |
| 352 |
1.9.0. You should use Launchpad.login_anonymously() for |
| 353 |
anonymous access and Launchpad.login_with() for all other |
| 354 |
purposes. |
| 355 |
|
| 356 |
:param consumer_name: Either a consumer name, as appropriate for |
| 357 |
the `Consumer` constructor, or a premade Consumer object. |
| 358 |
:type consumer_name: string |
| 359 |
:param service_root: The URL to the root of the web service. |
| 360 |
:type service_root: string |
| 361 |
:param authorization_engine: See `Launchpad.__init__`. If you don't |
| 362 |
provide an authorization engine, a default engine will be |
| 363 |
constructed using your values for `service_root` and |
| 364 |
`credential_save_failed`. |
| 365 |
:param allow_access_levels: This argument is ignored, and only |
| 366 |
present to preserve backwards compatibility. |
| 367 |
:return: The web service root |
| 368 |
:rtype: `Launchpad` |
| 369 |
""" |
| 370 |
cls._warn_of_deprecated_login_method("get_token_and_login") |
| 371 |
return cls._authorize_token_and_login( |
| 372 |
consumer_name, |
| 373 |
service_root, |
| 374 |
cache, |
| 375 |
timeout, |
| 376 |
proxy_info, |
| 377 |
authorization_engine, |
| 378 |
allow_access_levels, |
| 379 |
credential_store, |
| 380 |
credential_save_failed, |
| 381 |
version, |
| 382 |
) |
| 383 |
|
| 384 |
@classmethod |
| 385 |
def _authorize_token_and_login( |
| 386 |
cls, |
| 387 |
consumer_name, |
| 388 |
service_root, |
| 389 |
cache, |
| 390 |
timeout, |
| 391 |
proxy_info, |
| 392 |
authorization_engine, |
| 393 |
allow_access_levels, |
| 394 |
credential_store, |
| 395 |
credential_save_failed, |
| 396 |
version, |
| 397 |
): |
| 398 |
"""Authorize a request token. Log in with the resulting access token. |
| 399 |
|
| 400 |
This is the private, non-deprecated implementation of the |
| 401 |
deprecated method get_token_and_login(). Once |
| 402 |
get_token_and_login() is removed, this code can be streamlined |
| 403 |
and moved into its other call site, login_with(). |
| 404 |
""" |
| 405 |
if isinstance(consumer_name, Consumer): |
| 406 |
consumer = consumer_name |
| 407 |
else: |
| 408 |
# Create a system-wide consumer. lazr.restfulclient won't |
| 409 |
# do this automatically, but launchpadlib's default is to |
| 410 |
# do a desktop-wide integration. |
| 411 |
consumer = SystemWideConsumer(consumer_name) |
| 412 |
|
| 413 |
# Create the credentials with no Consumer, then set its .consumer |
| 414 |
# property directly. |
| 415 |
credentials = Credentials(None) |
| 416 |
credentials.consumer = consumer |
| 417 |
if authorization_engine is None: |
| 418 |
authorization_engine = cls.authorization_engine_factory( |
| 419 |
service_root, consumer_name, None, allow_access_levels |
| 420 |
) |
| 421 |
if credential_store is None: |
| 422 |
credential_store = cls.credential_store_factory( |
| 423 |
credential_save_failed |
| 424 |
) |
| 425 |
else: |
| 426 |
# A credential store was passed in, so we won't be using |
| 427 |
# any provided value for credential_save_failed. But at |
| 428 |
# least make sure we weren't given a conflicting value, |
| 429 |
# since that makes the calling code look confusing. |
| 430 |
cls._assert_login_argument_consistency( |
| 431 |
"credential_save_failed", |
| 432 |
credential_save_failed, |
| 433 |
credential_store.credential_save_failed, |
| 434 |
"credential_store", |
| 435 |
) |
| 436 |
|
| 437 |
# Try to get the credentials out of the credential store. |
| 438 |
cached_credentials = credential_store.load( |
| 439 |
authorization_engine.unique_consumer_id |
| 440 |
) |
| 441 |
if cached_credentials is None: |
| 442 |
# They're not there. Acquire new credentials using the |
| 443 |
# authorization engine. |
| 444 |
credentials = authorization_engine(credentials, credential_store) |
| 445 |
else: |
| 446 |
# We acquired credentials. But, the application name |
| 447 |
# wasn't stored along with the credentials, because in a |
| 448 |
# desktop integration scenario, a single set of |
| 449 |
# credentials may be shared by many applications. We need |
| 450 |
# to set the application name for this specific instance |
| 451 |
# of the credentials. |
| 452 |
credentials = cached_credentials |
| 453 |
credentials.consumer.application_name = ( |
| 454 |
authorization_engine.application_name |
| 455 |
) |
| 456 |
|
| 457 |
return cls( |
| 458 |
credentials, |
| 459 |
authorization_engine, |
| 460 |
credential_store, |
| 461 |
service_root, |
| 462 |
cache, |
| 463 |
timeout, |
| 464 |
proxy_info, |
| 465 |
version, |
| 466 |
) |
| 467 |
|
| 468 |
@classmethod |
| 469 |
def login_anonymously( |
| 470 |
cls, |
| 471 |
consumer_name, |
| 472 |
service_root=uris.STAGING_SERVICE_ROOT, |
| 473 |
launchpadlib_dir=None, |
| 474 |
timeout=None, |
| 475 |
proxy_info=proxy_info_from_environment, |
| 476 |
version=DEFAULT_VERSION, |
| 477 |
): |
| 478 |
"""Get access to Launchpad without providing any credentials.""" |
| 479 |
( |
| 480 |
service_root, |
| 481 |
launchpadlib_dir, |
| 482 |
cache_path, |
| 483 |
service_root_dir, |
| 484 |
) = cls._get_paths(service_root, launchpadlib_dir) |
| 485 |
token = AnonymousAccessToken() |
| 486 |
credentials = Credentials(consumer_name, access_token=token) |
| 487 |
return cls( |
| 488 |
credentials, |
| 489 |
None, |
| 490 |
None, |
| 491 |
service_root=service_root, |
| 492 |
cache=cache_path, |
| 493 |
timeout=timeout, |
| 494 |
proxy_info=proxy_info, |
| 495 |
version=version, |
| 496 |
) |
| 497 |
|
| 498 |
@classmethod |
| 499 |
def login_with( |
| 500 |
cls, |
| 501 |
application_name=None, |
| 502 |
service_root=uris.STAGING_SERVICE_ROOT, |
| 503 |
launchpadlib_dir=None, |
| 504 |
timeout=None, |
| 505 |
proxy_info=proxy_info_from_environment, |
| 506 |
authorization_engine=None, |
| 507 |
allow_access_levels=None, |
| 508 |
max_failed_attempts=None, |
| 509 |
credentials_file=None, |
| 510 |
version=DEFAULT_VERSION, |
| 511 |
consumer_name=None, |
| 512 |
credential_save_failed=None, |
| 513 |
credential_store=None, |
| 514 |
): |
| 515 |
"""Log in to Launchpad, possibly acquiring and storing credentials. |
| 516 |
|
| 517 |
Use this method to get a `Launchpad` object. If the end-user |
| 518 |
has no cached Launchpad credential, their browser will open |
| 519 |
and they'll be asked to log in and authorize a desktop |
| 520 |
integration. The authorized Launchpad credential will be |
| 521 |
stored securely: in the GNOME keyring, the KDE Wallet, or in |
| 522 |
an encrypted file on disk. |
| 523 |
|
| 524 |
The next time your program (or any other program run by that |
| 525 |
user on the same computer) invokes this method, the end-user |
| 526 |
will be prompted to unlock their keyring (or equivalent), and |
| 527 |
the credential will be retrieved from local storage and |
| 528 |
reused. |
| 529 |
|
| 530 |
You can customize this behavior in three ways: |
| 531 |
|
| 532 |
1. Pass in a filename to `credentials_file`. The end-user's |
| 533 |
credential will be written to that file, and on subsequent |
| 534 |
runs read from that file. Alternatively the filename can be |
| 535 |
given in the LP_CREDENTIALS_FILE environment variable. |
| 536 |
|
| 537 |
2. Subclass `CredentialStore` and pass in an instance of the |
| 538 |
subclass as `credential_store`. This lets you change how |
| 539 |
the end-user's credential is stored and retrieved locally. |
| 540 |
|
| 541 |
3. Subclass `RequestTokenAuthorizationEngine` and pass in an |
| 542 |
instance of the subclass as `authorization_engine`. This |
| 543 |
lets you change change what happens when the end-user needs |
| 544 |
to authorize the Launchpad credential. |
| 545 |
|
| 546 |
:param application_name: The application name. This is *not* |
| 547 |
the OAuth consumer name. Unless a consumer_name is also |
| 548 |
provided, the OAuth consumer will be a system-wide |
| 549 |
consumer representing the end-user's computer as a whole. |
| 550 |
:type application_name: string |
| 551 |
|
| 552 |
:param service_root: The URL to the root of the web service. |
| 553 |
:type service_root: string. Can either be the full URL to a service |
| 554 |
or one of the short service names. |
| 555 |
|
| 556 |
:param launchpadlib_dir: The directory used to store cached |
| 557 |
data obtained from Launchpad. The cache is shared by all |
| 558 |
consumers, and each Launchpad service root has its own |
| 559 |
cache. |
| 560 |
:type launchpadlib_dir: string |
| 561 |
|
| 562 |
:param authorization_engine: A strategy for getting the |
| 563 |
end-user to authorize an OAuth request token, for |
| 564 |
exchanging the request token for an access token, and for |
| 565 |
storing the access token locally so that it can be |
| 566 |
reused. By default, launchpadlib will open the end-user's |
| 567 |
web browser to have them authorize the request token. |
| 568 |
:type authorization_engine: `RequestTokenAuthorizationEngine` |
| 569 |
|
| 570 |
:param allow_access_levels: The acceptable access levels for |
| 571 |
this application. |
| 572 |
|
| 573 |
This argument is used to construct the default |
| 574 |
`authorization_engine`, so if you pass in your own |
| 575 |
`authorization_engine` any value for this argument will be |
| 576 |
ignored. This argument will also be ignored unless you |
| 577 |
also specify `consumer_name`. |
| 578 |
|
| 579 |
:type allow_access_levels: list of strings |
| 580 |
|
| 581 |
:param max_failed_attempts: Ignored; only present for |
| 582 |
backwards compatibility. |
| 583 |
|
| 584 |
:param credentials_file: The path to a file in which to store |
| 585 |
this user's OAuth access token. |
| 586 |
|
| 587 |
:param version: The version of the Launchpad web service to use. |
| 588 |
|
| 589 |
:param consumer_name: The consumer name, as appropriate for |
| 590 |
the `Consumer` constructor. You probably don't want to |
| 591 |
provide this, since providing it will prevent you from |
| 592 |
taking advantage of desktop-wide integration. |
| 593 |
:type consumer_name: string |
| 594 |
|
| 595 |
:param credential_save_failed: a callback that is called upon |
| 596 |
a failure to save the credentials locally. This argument is |
| 597 |
used to construct the default `credential_store`, so if |
| 598 |
you pass in your own `credential_store` any value for |
| 599 |
this argument will be ignored. |
| 600 |
:type credential_save_failed: A callable |
| 601 |
|
| 602 |
:param credential_store: A strategy for storing an OAuth |
| 603 |
access token locally. By default, tokens are stored in the |
| 604 |
GNOME keyring (or equivalent). If `credentials_file` is |
| 605 |
provided, then tokens are stored unencrypted in that file. |
| 606 |
:type credential_store: `CredentialStore` |
| 607 |
|
| 608 |
:return: A web service root authorized as the end-user. |
| 609 |
:rtype: `Launchpad` |
| 610 |
|
| 611 |
""" |
| 612 |
( |
| 613 |
service_root, |
| 614 |
launchpadlib_dir, |
| 615 |
cache_path, |
| 616 |
service_root_dir, |
| 617 |
) = cls._get_paths(service_root, launchpadlib_dir) |
| 618 |
|
| 619 |
if ( |
| 620 |
application_name is None |
| 621 |
and consumer_name is None |
| 622 |
and authorization_engine is None |
| 623 |
): |
| 624 |
raise ValueError( |
| 625 |
"At least one of application_name, consumer_name, or " |
| 626 |
"authorization_engine must be provided." |
| 627 |
) |
| 628 |
|
| 629 |
if credentials_file is None: |
| 630 |
credentials_file = os.environ.get("LP_CREDENTIALS_FILE") |
| 631 |
|
| 632 |
if credentials_file is not None and credential_store is not None: |
| 633 |
raise ValueError( |
| 634 |
"At most one of credentials_file and credential_store " |
| 635 |
"must be provided." |
| 636 |
) |
| 637 |
|
| 638 |
if credential_store is None: |
| 639 |
if credentials_file is not None: |
| 640 |
# The end-user wants credentials stored in an |
| 641 |
# unencrypted file. |
| 642 |
credential_store = UnencryptedFileCredentialStore( |
| 643 |
credentials_file, credential_save_failed |
| 644 |
) |
| 645 |
else: |
| 646 |
credential_store = cls.credential_store_factory( |
| 647 |
credential_save_failed |
| 648 |
) |
| 649 |
else: |
| 650 |
# A credential store was passed in, so we won't be using |
| 651 |
# any provided value for credential_save_failed. But at |
| 652 |
# least make sure we weren't given a conflicting value, |
| 653 |
# since that makes the calling code look confusing. |
| 654 |
cls._assert_login_argument_consistency( |
| 655 |
"credential_save_failed", |
| 656 |
credential_save_failed, |
| 657 |
credential_store.credential_save_failed, |
| 658 |
"credential_store", |
| 659 |
) |
| 660 |
credential_store = credential_store |
| 661 |
|
| 662 |
if authorization_engine is None: |
| 663 |
authorization_engine = cls.authorization_engine_factory( |
| 664 |
service_root, |
| 665 |
application_name, |
| 666 |
consumer_name, |
| 667 |
allow_access_levels, |
| 668 |
) |
| 669 |
else: |
| 670 |
# An authorization engine was passed in, so we won't be |
| 671 |
# using any provided values for application_name, |
| 672 |
# consumer_name, or allow_access_levels. But at least make |
| 673 |
# sure we weren't given conflicting values, since that |
| 674 |
# makes the calling code look confusing. |
| 675 |
cls._assert_login_argument_consistency( |
| 676 |
"application_name", |
| 677 |
application_name, |
| 678 |
authorization_engine.application_name, |
| 679 |
) |
| 680 |
|
| 681 |
cls._assert_login_argument_consistency( |
| 682 |
"consumer_name", |
| 683 |
consumer_name, |
| 684 |
authorization_engine.consumer.key, |
| 685 |
) |
| 686 |
|
| 687 |
cls._assert_login_argument_consistency( |
| 688 |
"allow_access_levels", |
| 689 |
allow_access_levels, |
| 690 |
authorization_engine.allow_access_levels, |
| 691 |
) |
| 692 |
|
| 693 |
return cls._authorize_token_and_login( |
| 694 |
authorization_engine.consumer, |
| 695 |
service_root, |
| 696 |
cache_path, |
| 697 |
timeout, |
| 698 |
proxy_info, |
| 699 |
authorization_engine, |
| 700 |
allow_access_levels, |
| 701 |
credential_store, |
| 702 |
credential_save_failed, |
| 703 |
version, |
| 704 |
) |
| 705 |
|
| 706 |
@classmethod |
| 707 |
def _warn_of_deprecated_login_method(cls, name): |
| 708 |
warnings.warn( |
| 709 |
( |
| 710 |
"The Launchpad.%s() method is deprecated. You should use " |
| 711 |
"Launchpad.login_anonymous() for anonymous access and " |
| 712 |
"Launchpad.login_with() for all other purposes." |
| 713 |
) |
| 714 |
% name, |
| 715 |
DeprecationWarning, |
| 716 |
) |
| 717 |
|
| 718 |
@classmethod |
| 719 |
def _assert_login_argument_consistency( |
| 720 |
cls, |
| 721 |
argument_name, |
| 722 |
argument_value, |
| 723 |
object_value, |
| 724 |
object_name="authorization engine", |
| 725 |
): |
| 726 |
"""Helper to find conflicting values passed into the login methods. |
| 727 |
|
| 728 |
Many of the arguments to login_with are used to build other |
| 729 |
objects--the authorization engine or the credential store. If |
| 730 |
these objects are provided directly, many of the arguments |
| 731 |
become redundant. We'll allow redundant arguments through, but |
| 732 |
if a argument *conflicts* with the corresponding value in the |
| 733 |
provided object, we raise an error. |
| 734 |
""" |
| 735 |
inconsistent_value_message = ( |
| 736 |
"Inconsistent values given for %s: " |
| 737 |
"(%r passed in, versus %r in %s). " |
| 738 |
"You don't need to pass in %s if you pass in %s, " |
| 739 |
"so just omit that argument." |
| 740 |
) |
| 741 |
if argument_value is not None and argument_value != object_value: |
| 742 |
raise ValueError( |
| 743 |
inconsistent_value_message |
| 744 |
% ( |
| 745 |
argument_name, |
| 746 |
argument_value, |
| 747 |
object_value, |
| 748 |
object_name, |
| 749 |
argument_name, |
| 750 |
object_name, |
| 751 |
) |
| 752 |
) |
| 753 |
|
| 754 |
@classmethod |
| 755 |
def _get_paths(cls, service_root, launchpadlib_dir=None): |
| 756 |
"""Locate launchpadlib-related user paths and ensure they exist. |
| 757 |
|
| 758 |
This is a helper function used by login_with() and |
| 759 |
login_anonymously(). |
| 760 |
|
| 761 |
:param service_root: The service root the user wants to |
| 762 |
connect to. This may be an alias (which will be |
| 763 |
dereferenced to a URL and returned) or a URL (which will |
| 764 |
be returned as is). |
| 765 |
:param launchpadlib_dir: The user's base launchpadlib |
| 766 |
directory, if known. This may be modified, expanded, or |
| 767 |
determined from the environment if missing. A definitive |
| 768 |
value will be returned. |
| 769 |
|
| 770 |
:return: A 4-tuple: |
| 771 |
(service_root_uri, launchpadlib_dir, cache_dir, service_root_dir) |
| 772 |
""" |
| 773 |
if launchpadlib_dir is None: |
| 774 |
launchpadlib_dir = os.path.join("~", ".launchpadlib") |
| 775 |
launchpadlib_dir = os.path.expanduser(launchpadlib_dir) |
| 776 |
if launchpadlib_dir[:1] == "~": |
| 777 |
raise ValueError( |
| 778 |
"Must set $HOME or pass 'launchpadlib_dir' to " |
| 779 |
"indicate location to store cached data" |
| 780 |
) |
| 781 |
try: |
| 782 |
os.makedirs(launchpadlib_dir, 0o700) |
| 783 |
except OSError as err: |
| 784 |
if err.errno != errno.EEXIST: |
| 785 |
raise |
| 786 |
os.chmod(launchpadlib_dir, 0o700) |
| 787 |
# Determine the real service root. |
| 788 |
service_root = uris.lookup_service_root(service_root) |
| 789 |
# Each service root has its own cache and credential dirs. |
| 790 |
scheme, host_name, path, query, fragment = urlsplit(service_root) |
| 791 |
service_root_dir = os.path.join(launchpadlib_dir, host_name) |
| 792 |
cache_path = os.path.join(service_root_dir, "cache") |
| 793 |
try: |
| 794 |
os.makedirs(cache_path, 0o700) |
| 795 |
except OSError as err: |
| 796 |
if err.errno != errno.EEXIST: |
| 797 |
raise |
| 798 |
return (service_root, launchpadlib_dir, cache_path, service_root_dir) |