Exemplo n.º 1
0
    def _GetOpener(self):
        """Returns an OpenerDirector that supports cookies and ignores redirects.

    Returns:
      A urllib2.OpenerDirector object.
    """
        opener = urllib2.OpenerDirector()
        opener.add_handler(fancy_urllib.FancyProxyHandler())
        opener.add_handler(urllib2.UnknownHandler())
        opener.add_handler(urllib2.HTTPHandler())
        opener.add_handler(urllib2.HTTPDefaultErrorHandler())
        opener.add_handler(fancy_urllib.FancyHTTPSHandler())
        opener.add_handler(urllib2.HTTPErrorProcessor())

        auth_domain = ''
        if 'AUTH_DOMAIN' in os.environ:
            auth_domain = os.environ['AUTH_DOMAIN'].lower()

        if self.save_cookies:
            if auth_domain == 'appscale':
                cookies_dir = os.path.expanduser(
                    HttpRpcServer.APPSCALE_COOKIE_DIR)
                if not os.path.exists(cookies_dir):
                    os.mkdir(cookies_dir)
            else:
                self.cookie_jar.filename = os.path.expanduser(
                    HttpRpcServer.DEFAULT_COOKIE_FILE_PATH)

                if os.path.exists(self.cookie_jar.filename):
                    try:
                        self.cookie_jar.load()
                        self.authenticated = True
                        logger.info("Loaded authentication cookies from %s",
                                    self.cookie_jar.filename)
                    except (OSError, IOError, cookielib.LoadError), e:
                        logger.debug(
                            "Could not load authentication cookies; %s: %s",
                            e.__class__.__name__, e)
                        self.cookie_jar.filename = None
                    else:
                        try:
                            fd = os.open(self.cookie_jar.filename, os.O_CREAT,
                                         0600)
                            os.close(fd)
                        except (OSError, IOError), e:
                            logger.debug(
                                "Could not create authentication cookies file; %s: %s",
                                e.__class__.__name__, e)
                            self.cookie_jar.filename = None
Exemplo n.º 2
0
def BuildClientLoginOpener(hostname, credentials):
  """Produce an urllib2 OpenerDirective that's logged in by client login.

  Args:
    hostname: host name for server
    credentials: A tuple of (email, password).

  Note: if necessary, "password" should be an application specific password.

  Returns:
    Tuple of (urllib2.OpenerDirective, cookielib.CookieJar) .
  Raises:
    AuthenticationError: when authentication fails.
  """
  cookiejar = cookielib.CookieJar()
  opener = urllib2.build_opener(
      urllib2.HTTPCookieProcessor(cookiejar),
      fancy_urllib.FancyHTTPSHandler(),
      fancy_urllib.FancyRedirectHandler())
  email, password = credentials

  # Step 1: We get an Auth token from ClientLogin.
  req = fancy_urllib.FancyRequest(
      'https://www.google.com/accounts/ClientLogin',
      urllib.urlencode({
          'accountType': 'HOSTED_OR_GOOGLE',
          'Email': email,
          'Passwd': password,
          'service': 'ah',
          'source': 'cauliflowervest',
          })
      )
  try:
    response = opener.open(req)
  except urllib2.HTTPError, e:
    error_body = e.read()
    # TODO(user): Consider more failure cases.
    if 'Error=BadAuthentication' in error_body:
      raise AuthenticationError('Bad email or password.')
    elif 'Error=CaptchaRequired' in error_body:
      # TODO(user): Provide a link to the page where users can fix this:
      #   https://www.google.com/accounts/DisplayUnlockCaptcha
      raise AuthenticationError(
          'Server responded with captcha request; captchas unsupported.')
    else:
      raise AuthenticationError('Authentication: Could not get service token.')
Exemplo n.º 3
0
    def _GetOpener(self):
        """Returns an OpenerDirector that supports cookies and ignores redirects.

    Returns:
      A urllib2.OpenerDirector object.
    """
        opener = urllib.request.OpenerDirector()
        opener.add_handler(fancy_urllib.FancyProxyHandler())
        opener.add_handler(urllib.request.UnknownHandler())
        opener.add_handler(urllib.request.HTTPHandler())
        opener.add_handler(urllib.request.HTTPDefaultErrorHandler())
        opener.add_handler(fancy_urllib.FancyHTTPSHandler())
        opener.add_handler(urllib.request.HTTPErrorProcessor())
        opener.add_handler(ContentEncodingHandler())

        if self.save_cookies:
            self.cookie_jar.filename = os.path.expanduser(
                HttpRpcServer.DEFAULT_COOKIE_FILE_PATH)

            if os.path.exists(self.cookie_jar.filename):
                try:
                    self.cookie_jar.load()
                    self.authenticated = True
                    logger.debug("Loaded authentication cookies from %s",
                                 self.cookie_jar.filename)
                except (OSError, IOError, http.cookiejar.LoadError) as e:

                    logger.debug(
                        "Could not load authentication cookies; %s: %s",
                        e.__class__.__name__, e)
                    self.cookie_jar.filename = None
            else:

                try:
                    fd = os.open(self.cookie_jar.filename, os.O_CREAT, 0o600)
                    os.close(fd)
                except (OSError, IOError) as e:

                    logger.debug(
                        "Could not create authentication cookies file; %s: %s",
                        e.__class__.__name__, e)
                    self.cookie_jar.filename = None

        opener.add_handler(urllib.request.HTTPCookieProcessor(self.cookie_jar))
        return opener
Exemplo n.º 4
0
    def _GetOpener(self):
        """Returns an OpenerDirector that supports cookies and ignores redirects.

    Returns:
      A urllib2.OpenerDirector object.
    """
        opener = urllib2.OpenerDirector()
        opener.add_handler(fancy_urllib.FancyProxyHandler())
        opener.add_handler(urllib2.UnknownHandler())
        opener.add_handler(urllib2.HTTPHandler())
        opener.add_handler(urllib2.HTTPDefaultErrorHandler())
        opener.add_handler(fancy_urllib.FancyHTTPSHandler())
        opener.add_handler(urllib2.HTTPErrorProcessor())
        opener.add_handler(ContentEncodingHandler())

        if self.save_cookies:
            self.cookie_jar.filename = os.path.expanduser(
                HttpRpcServer.DEFAULT_COOKIE_FILE_PATH)

            if os.path.exists(self.cookie_jar.filename):
                try:
                    self.cookie_jar.load()
                    self.authenticated = True
                    logger.debug("Loaded authentication cookies from %s",
                                 self.cookie_jar.filename)
                except (OSError, IOError, cookielib.LoadError), e:
                    # Failed to load cookies. The target file path is bad.
                    logger.debug(
                        "Could not load authentication cookies; %s: %s",
                        e.__class__.__name__, e)
                    self.cookie_jar.filename = None
            else:
                # Create an empty cookie file. This must be created with the file
                # permissions set upfront in order to be secure.
                try:
                    fd = os.open(self.cookie_jar.filename, os.O_CREAT, 0600)
                    os.close(fd)
                except (OSError, IOError), e:
                    # Failed to create cookie file. Don't try to save cookies.
                    logger.debug(
                        "Could not create authentication cookies file; %s: %s",
                        e.__class__.__name__, e)
                    self.cookie_jar.filename = None