class SessionStore(requests.Session): """A ``requests.Session`` subclass implementing a file-based session store. """ def __init__(self, cookie_file=None): super(SessionStore, self).__init__() if cookie_file is None: cookie_file = conf.DEFAULT_COOKIE_FILE cookie_dir = os.path.dirname(cookie_file) self.cookies = MozillaCookieJar(cookie_file) # Create the $HOME/.slipstream dir if it doesn't exist if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # Load existing cookies if the cookies.txt exists if os.path.isfile(cookie_file): self.cookies.load(ignore_discard=True) self.cookies.clear_expired_cookies() def request(self, *args, **kwargs): response = super(SessionStore, self).request(*args, **kwargs) self.cookies.save(ignore_discard=True) return response def clear(self, domain): """Clear cookies for the specified domain.""" try: self.cookies.clear(domain) self.cookies.save() except KeyError: pass
class SessionStore(requests.Session): """A ``requests.Session`` subclass implementing a file-based session store. """ def __init__(self, cookie_file=None): super(SessionStore, self).__init__() if cookie_file is None: cookie_file = conf.DEFAULT_COOKIE_FILE cookie_dir = os.path.dirname(cookie_file) self.cookies = MozillaCookieJar(cookie_file) # Create the $HOME/.slipstream dir if it doesn't exist if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # Load existing cookies if the cookies.txt exists if os.path.isfile(cookie_file): self.cookies.load(ignore_discard=True) self.cookies.clear_expired_cookies() def request(self, *args, **kwargs): response = super(SessionStore, self).request(*args, **kwargs) self.cookies.save(ignore_discard=True) return response def clear(self, domain): """Clear cookies for the specified domain.""" try: self.cookies.clear(domain) self.cookies.save() except KeyError: pass
def __init__(self, cookie_file=None): super(SessionStore, self).__init__() if cookie_file is None: cookie_file = conf.DEFAULT_COOKIE_FILE cookie_dir = os.path.dirname(cookie_file) self.cookies = MozillaCookieJar(cookie_file) # Create the $HOME/.slipstream dir if it doesn't exist if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # Load existing cookies if the cookies.txt exists if os.path.isfile(cookie_file): self.cookies.load(ignore_discard=True) self.cookies.clear_expired_cookies()
def create_cookie_jar(cookie_file=None): """Return a cookie jar backed by cookie_file If cooie_file is not provided, we will default it. If the cookie_file does not exist, we will create it with the proper permissions. In the case where we default cookie_file, and it does not exist, we will attempt to copy the .post-review-cookies.txt file. """ home_path = get_home_path() if not cookie_file: cookie_file = os.path.join(home_path, RBTOOLS_COOKIE_FILE) post_review_cookies = os.path.join(home_path, '.post-review-cookies.txt') if (not os.path.isfile(cookie_file) and os.path.isfile(post_review_cookies)): try: shutil.copyfile(post_review_cookies, cookie_file) os.chmod(cookie_file, 0o600) except IOError as e: logging.warning("There was an error while copying " "post-review's cookies: %s", e) if not os.path.isfile(cookie_file): try: open(cookie_file, 'w').close() os.chmod(cookie_file, 0o600) except IOError as e: logging.warning('There was an error while creating a ' 'cookie file: %s', e) return MozillaCookieJar(cookie_file), cookie_file
def __init__(self, endpoint, reauthenticate, cookie_file=None): super(SessionStore, self).__init__() self.session_base_url = '{}/api/session'.format(endpoint) self.reauthenticate = reauthenticate self.login_params = None if cookie_file is None: cookie_file = DEFAULT_COOKIE_FILE cookie_dir = os.path.dirname(cookie_file) self.cookies = MozillaCookieJar(cookie_file) # Create the $HOME/.slipstream dir if it doesn't exist if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # Load existing cookies if the cookies.txt exists if os.path.isfile(cookie_file): self.cookies.load(ignore_discard=True) self.cookies.clear_expired_cookies()
def fresh_session( url, cert_file, key_file, cookie_filename="cookies.txt", ): logger.debug("Setting up fresh session using cert=%s key=%s", cert_file, key_file) s = requests.Session() s.cert = (cert_file, key_file) cookiejar = MozillaCookieJar(cookie_filename) s.cookies = cookiejar logger.info("Request #1, to get main redirect to authentication: %s", url) r1 = s.get(url, timeout=DEFAULT_TIMEOUT_SECONDS, verify=False) # Parse out the session keys from the GET arguments: redirect_url = urlparse(r1.url) logger.debug("Was redirected to SSO URL: %s", str(redirect_url)) # ...and inject them into the Kerberos authentication URL final_auth_url = "{0}?{1}".format(urljoin(r1.url, CERT_AUTH_URL_FRAGMENT), redirect_url.query) logger.info("Request #2, performing SSL Cert authentication against %s", final_auth_url) r2 = s.get(final_auth_url, cookies=cookiejar, verify=False, timeout=DEFAULT_TIMEOUT_SECONDS) # Did it work? Raise Exception otherwise. r2.raise_for_status() # Get the contents try: tree = ET.fromstring(r2.content) except ET.ParseError as e: logger.error("Could not parse response from server! " "The contents returned was:\n{}".format(r2.content)) raise e action = tree.findall("body/form")[0].get("action") # Unpack the hidden form data fields form_data = { elm.get("name"): elm.get("value") for elm in tree.findall("body/form/input") } # ...and submit the form (WHY IS THIS STEP EVEN HERE!?) logger.info("Performing final authentication POST to %s", action) r3 = s.post(url=action, data=form_data, timeout=DEFAULT_TIMEOUT_SECONDS) # Did _that_ work? r3.raise_for_status() # The session cookie jar should now contain the necessary cookies. logger.debug("Cookie jar now contains: %s", str(s.cookies)) return s
def __init__(self, cookie_file=None): super(SessionStore, self).__init__() if cookie_file is None: cookie_file = conf.DEFAULT_COOKIE_FILE cookie_dir = os.path.dirname(cookie_file) self.cookies = MozillaCookieJar(cookie_file) # Create the $HOME/.slipstream dir if it doesn't exist if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # Load existing cookies if the cookies.txt exists if os.path.isfile(cookie_file): self.cookies.load(ignore_discard=True) self.cookies.clear_expired_cookies()
def session_from_cookies_file( cert_file, key_file, cookie_filename="cookies.txt", ): logger.debug( "Setting up session using cert=%s key=%s based on cookies in %s", cert_file, key_file, cookie_filename, ) s = requests.Session() s.cert = (cert_file, key_file) s.cookies = MozillaCookieJar(cookie_filename) s.cookies.load(ignore_discard=True, ignore_expires=True) return s
from six.moves.http_cookiejar import Cookie from six.moves.html_parser import HTMLParser from six.moves.urllib_error import HTTPError from six.moves import urllib_request from six.moves import http_client from six.moves import urllib_response CACHE = simplecache.SimpleCache() CACHE.enable_mem_cache = False CACHE_ENABLED = True # False for debuging CACHE_EXPIRATION = datetime.timedelta(minutes=20) CACHE_PREFIX = ADDON.getAddonInfo('id') + '_' + ADDON_VERSION + '_' cookies_lock = Lock() cj = MozillaCookieJar() cookies_path = os.path.join(DATA_PATH, "cookies.dat") # Headers por defecto, si no se especifica nada default_headers = dict() default_headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0" default_headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" default_headers["Accept-Language"] = "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3" default_headers["Accept-Charset"] = "UTF-8" default_headers["Accept-Encoding"] = "gzip" default_headers["Upgrade-Insecure-Requests"] = '1' # No comprobar certificados if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context
version=__version__) args = arg_parser.parse_args() # DEBUG takes presedence over VERBOSE: if args.debug: logger.setLevel(logging.DEBUG) elif args.verbose: logger.setLevel(logging.INFO) cookie_filename = args.cookie_filename target_url = args.url cookiejar = MozillaCookieJar(cookie_filename) if args.kerberos: cern_sso.krb_sign_on(target_url, cookiejar=cookiejar) elif args.cert: cert_file = "%s.pem" % args.cert key_file = "%s.key" % args.cert logger.info("Using SSL certificate file %s and key %s" % (cert_file, key_file)) cern_sso.cert_sign_on(target_url, cert_file=cert_file, key_file=key_file, cookiejar=cookiejar) else:
class SessionStore(requests.Session): """A ``requests.Session`` subclass implementing a file-based session store.""" def __init__(self, endpoint, reauthenticate, cookie_file=None): super(SessionStore, self).__init__() self.session_base_url = '{}/api/session'.format(endpoint) self.reauthenticate = reauthenticate self.login_params = None if cookie_file is None: cookie_file = DEFAULT_COOKIE_FILE cookie_dir = os.path.dirname(cookie_file) self.cookies = MozillaCookieJar(cookie_file) # Create the $HOME/.slipstream dir if it doesn't exist if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # Load existing cookies if the cookies.txt exists if os.path.isfile(cookie_file): self.cookies.load(ignore_discard=True) self.cookies.clear_expired_cookies() def need_to_login(self, accessed_url, status_code): return self.reauthenticate and status_code in [401, 403] and accessed_url != self.session_base_url def request(self, *args, **kwargs): super_request = super(SessionStore, self).request response = super_request(*args, **kwargs) if not self.verify and response.cookies: self._unsecure_cookie(args[1], response) self.cookies.save(ignore_discard=True) url = args[1] if self.need_to_login(url, response.status_code): login_response = self.cimi_login(self.login_params) if login_response is not None and login_response.status_code == 201: # retry the call after reauthentication response = super_request(*args, **kwargs) return response def cimi_login(self, login_params): self.login_params = login_params if self.login_params: return self.request('POST', self.session_base_url, headers={'Content-Type': 'application/json', 'Accept': 'application/json'}, json={'sessionTemplate': login_params}) else: return None def _unsecure_cookie(self, url_str, response): url = urlparse(url_str) if url.scheme == 'http': for cookie in response.cookies: cookie.secure = False self.cookies.set_cookie_if_ok(cookie, MockRequest(response.request)) def clear(self, domain): """Clear cookies for the specified domain.""" try: self.cookies.clear(domain) self.cookies.save() except KeyError: pass