11import getpass
2+ import importlib .metadata
23import logging
34import os
45from netrc import NetrcParseError
1112
1213from .daac import DAACS
1314
15+ try :
16+ user_agent = f"earthaccess v{ importlib .metadata .version ('earthaccess' )} "
17+ except importlib .metadata .PackageNotFoundError :
18+ user_agent = "earthaccess"
19+
20+
1421logger = logging .getLogger (__name__ )
1522
1623
1724class SessionWithHeaderRedirection (requests .Session ):
1825 """
1926 Requests removes auth headers if the redirect happens outside the
2027 original req domain.
21- This is taken from https://wiki.earthdata.nasa.gov/display/EL/How+To+Access+Data+With+Python
2228 """
2329
24- AUTH_HOST = "urs.earthdata.nasa.gov"
30+ AUTH_HOSTS : List [str ] = [
31+ "urs.earthdata.nasa.gov" ,
32+ "cumulus.asf.alaska.edu" ,
33+ "sentinel1.asf.alaska.edu" ,
34+ "nisar.asf.alaska.edu" ,
35+ "datapool.asf.alaska.edu" ,
36+ ]
2537
2638 def __init__ (
2739 self , username : Optional [str ] = None , password : Optional [str ] = None
2840 ) -> None :
2941 super ().__init__ ()
42+ self .headers .update ({"User-Agent" : user_agent })
43+
3044 if username and password :
3145 self .auth = (username , password )
3246
@@ -39,11 +53,13 @@ def rebuild_auth(self, prepared_request: Any, response: Any) -> None:
3953 if "Authorization" in headers :
4054 original_parsed = urlparse (response .request .url )
4155 redirect_parsed = urlparse (url )
42- if (
43- (original_parsed .hostname != redirect_parsed .hostname )
44- and redirect_parsed .hostname != self .AUTH_HOST
45- and original_parsed .hostname != self .AUTH_HOST
56+ if (original_parsed .hostname != redirect_parsed .hostname ) and (
57+ redirect_parsed .hostname not in self .AUTH_HOSTS
58+ or original_parsed .hostname not in self .AUTH_HOSTS
4659 ):
60+ logger .debug (
61+ f"Deleting Auth Headers: { original_parsed .hostname } -> { redirect_parsed .hostname } "
62+ )
4763 del headers ["Authorization" ]
4864 return
4965
@@ -208,7 +224,7 @@ def get_session(self, bearer_token: bool = True) -> requests.Session:
208224 Returns:
209225 class Session instance with Auth and bearer token headers
210226 """
211- session = requests . Session ()
227+ session = SessionWithHeaderRedirection ()
212228 if bearer_token and self .authenticated :
213229 # This will avoid the use of the netrc after we are logged in
214230 session .trust_env = False
0 commit comments