-
Notifications
You must be signed in to change notification settings - Fork 91
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fixing searching for restricted datasets and accessing ASF on demand data from Opera #443
Merged
Changes from 9 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
e97e6f0
refactoring auth to allow other trusted domains besides NASA's URS
betolink 073e4ac
updated changelog and readme
betolink acade70
fix docstring
betolink 429324a
Update earthaccess/auth.py
betolink b320652
Update earthaccess/search.py
betolink 0ead9db
making ruff happy
betolink c692069
using user-agent to start tracing client usage
betolink b94897e
fix lintint
betolink 11686dd
fix lintint
betolink 2b14609
Update earthaccess/auth.py
betolink 72539dd
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 19b6be1
Update earthaccess/auth.py
betolink d20f713
reverting last commit, avoid importing the library
betolink File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
import getpass | ||
import importlib.metadata | ||
import logging | ||
import os | ||
from netrc import NetrcParseError | ||
|
@@ -11,22 +12,34 @@ | |
|
||
from .daac import DAACS | ||
|
||
try: | ||
user_agent = f"earthaccess v{importlib.metadata.version('earthacess')}" | ||
betolink marked this conversation as resolved.
Show resolved
Hide resolved
|
||
except importlib.metadata.PackageNotFoundError: | ||
user_agent = "earthaccess" | ||
|
||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class SessionWithHeaderRedirection(requests.Session): | ||
""" | ||
Requests removes auth headers if the redirect happens outside the | ||
original req domain. | ||
This is taken from https://wiki.earthdata.nasa.gov/display/EL/How+To+Access+Data+With+Python | ||
""" | ||
|
||
AUTH_HOST = "urs.earthdata.nasa.gov" | ||
AUTH_HOSTS: List[str] = [ | ||
"urs.earthdata.nasa.gov", | ||
"cumulus.asf.alaska.edu", | ||
mfisher87 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"sentinel1.asf.alaska.edu", | ||
betolink marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"datapool.asf.alaska.edu", | ||
] | ||
|
||
def __init__( | ||
self, username: Optional[str] = None, password: Optional[str] = None | ||
) -> None: | ||
super().__init__() | ||
self.headers.update({"User-Agent": user_agent}) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
||
if username and password: | ||
self.auth = (username, password) | ||
|
||
|
@@ -39,11 +52,13 @@ def rebuild_auth(self, prepared_request: Any, response: Any) -> None: | |
if "Authorization" in headers: | ||
original_parsed = urlparse(response.request.url) | ||
redirect_parsed = urlparse(url) | ||
if ( | ||
(original_parsed.hostname != redirect_parsed.hostname) | ||
and redirect_parsed.hostname != self.AUTH_HOST | ||
and original_parsed.hostname != self.AUTH_HOST | ||
if (original_parsed.hostname != redirect_parsed.hostname) and ( | ||
redirect_parsed.hostname not in self.AUTH_HOSTS | ||
or original_parsed.hostname not in self.AUTH_HOSTS | ||
): | ||
logger.debug( | ||
f"Deleting Auth Headers: {original_parsed.hostname} -> {redirect_parsed.hostname}" | ||
) | ||
del headers["Authorization"] | ||
return | ||
|
||
|
@@ -210,7 +225,7 @@ def get_session(self, bearer_token: bool = True) -> requests.Session: | |
Returns: | ||
class Session instance with Auth and bearer token headers | ||
""" | ||
session = requests.Session() | ||
session = SessionWithHeaderRedirection() | ||
if bearer_token and self.authenticated: | ||
# This will avoid the use of the netrc after we are logged in | ||
session.trust_env = False | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -60,7 +60,16 @@ def hits(self) -> int: | |
Returns: | ||
number of results reported by CMR | ||
""" | ||
return super().hits() | ||
url = self._build_url() | ||
|
||
response = self.session.get(url, headers=self.headers, params={"page_size": 0}) | ||
|
||
try: | ||
response.raise_for_status() | ||
except exceptions.HTTPError as ex: | ||
raise RuntimeError(ex.response.text) | ||
|
||
return int(response.headers["CMR-Hits"]) | ||
|
||
def concept_id(self, IDs: List[str]) -> Type[CollectionQuery]: | ||
"""Filter by concept ID (ex: C1299783579-LPDAAC_ECS or G1327299284-LPDAAC_ECS, S12345678-LPDAAC_ECS) | ||
|
@@ -106,6 +115,39 @@ def doi(self, doi: str) -> Type[CollectionQuery]: | |
self.params["doi"] = doi | ||
return self | ||
|
||
def instrument(self, instrument: str) -> Type[CollectionQuery]: | ||
"""Searh datasets by instrument | ||
|
||
???+ Tip | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
Not all datasets have an associated instrument. This works | ||
only at the dataset level but not the granule (data) level. | ||
|
||
Parameters: | ||
instrument (String): instrument of a datasets, e.g. instrument=GEDI | ||
""" | ||
if not isinstance(instrument, str): | ||
raise TypeError("instrument must be of type str") | ||
|
||
self.params["instrument"] = instrument | ||
return self | ||
|
||
def project(self, project: str) -> Type[CollectionQuery]: | ||
"""Searh datasets by associated project | ||
|
||
???+ Tip | ||
Not all datasets have an associated project. This works | ||
only at the dataset level but not the granule (data) level. | ||
Will return datasets across DAACs matching the project. | ||
|
||
Parameters: | ||
project (String): associated project of a datasets, e.g. project=EMIT | ||
""" | ||
if not isinstance(project, str): | ||
raise TypeError("project must be of type str") | ||
|
||
self.params["project"] = project | ||
return self | ||
|
||
def parameters(self, **kwargs: Any) -> Type[CollectionQuery]: | ||
"""Provide query parameters as keyword arguments. The keyword needs to match the name | ||
of the method, and the value should either be the value or a tuple of values. | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This one is only for the local dev environment and actually not necessary as we can just pip install the project locally.... I use it to bootstrap the environment and install some conda libs to test notebooks with (cartopy)