Ejemplo n.º 1
0
 def basic_login_aux(username, password, server=server):
     key = base64.b64encode(username + ':' + password)
     headers = {'Authorization': 'Basic ' + key}
     request = urllib2.Request(server, None, headers)
     try:
         urlopen(request)
         return True
     except (urllib2.URLError, urllib2.HTTPError):
         return False
Ejemplo n.º 2
0
 def basic_login_aux(username,
                     password,
                     server=server):
     key = base64.b64encode(username + ':' + password)
     headers = {'Authorization': 'Basic ' + key}
     request = urllib2.Request(server, None, headers)
     try:
         urlopen(request)
         return True
     except (urllib2.URLError, urllib2.HTTPError):
         return False
Ejemplo n.º 3
0
def check_new_version(myversion, version_url):
    """Compares current web2py's version with the latest stable web2py version.

    Args:
        myversion: the current version as stored in file `web2py/VERSION`
        version_URL: the URL that contains the version
                     of the latest stable release

    Returns:
        tuple: state, version

        - state : `True` if upgrade available, `False` if current
          version is up-to-date, -1 on error
        - version : the most up-to-version available

    """
    try:
        version = to_native(urlopen(version_url).read())
        pversion = parse_version(version)
        pmyversion = parse_version(myversion)
    except IOError:
        import traceback
        print(traceback.format_exc())
        return -1, myversion

    if pversion[:3]+pversion[-6:] > pmyversion[:3]+pmyversion[-6:]:
        return True, version
    else:
        return False, version
Ejemplo n.º 4
0
def check_new_version(myversion, version_url):
    """Compares current web2py's version with the latest stable web2py version.

    Args:
        myversion: the current version as stored in file `web2py/VERSION`
        version_URL: the URL that contains the version
                     of the latest stable release

    Returns:
        tuple: state, version

        - state : `True` if upgrade available, `False` if current
          version is up-to-date, -1 on error
        - version : the most up-to-version available

    """
    try:
        version = to_native(urlopen(version_url).read())
        pversion = parse_version(version)
        pmyversion = parse_version(myversion)
    except IOError:
        import traceback
        print(traceback.format_exc())
        return -1, myversion

    if pversion[:3] + pversion[-6:] > pmyversion[:3] + pmyversion[-6:]:
        return True, version
    else:
        return False, version
Ejemplo n.º 5
0
    def process(self):
        encoded_args = urlencode(self.parameters)
        if self.proxy is None:
            results = str(urlopen(
                self.url, encoded_args).read()).split(self.delimiter)
        else:
            opener = FancyURLopener(self.proxy)
            opened = opener.open(self.url, encoded_args)
            try:
                results = str(opened.read()).split(self.delimiter)
            finally:
                opened.close()

        for result in results:
            (key, val) = result.split('=')
            self.results[key] = val

        if self.results['response'] == '1':
            self.error = False
            self.success = True
            self.declined = False
        elif self.results['response'] == '2':
            self.error = False
            self.success = False
            self.declined = True
        elif self.results['response'] == '3':
            self.error = True
            self.success = False
            self.declined = False
        else:
            self.error = True
            self.success = False
            self.declined = False
            raise DowCommerce.DowCommerceError(self.results)
Ejemplo n.º 6
0
    def process(self):
        encoded_args = urlencode(self.parameters)
        if self.proxy is None:
            results = str(urlopen(self.url,
                                  encoded_args).read()).split(self.delimiter)
        else:
            opener = FancyURLopener(self.proxy)
            opened = opener.open(self.url, encoded_args)
            try:
                results = str(opened.read()).split(self.delimiter)
            finally:
                opened.close()

        for result in results:
            (key, val) = result.split('=')
            self.results[key] = val

        if self.results['response'] == '1':
            self.error = False
            self.success = True
            self.declined = False
        elif self.results['response'] == '2':
            self.error = False
            self.success = False
            self.declined = True
        elif self.results['response'] == '3':
            self.error = True
            self.success = False
            self.declined = False
        else:
            self.error = True
            self.success = False
            self.declined = False
            raise DowCommerce.DowCommerceError(self.results)
Ejemplo n.º 7
0
def websocket_send(url, message, hmac_key=None, group='default'):
    sig = hmac_key and hmac.new(to_bytes(hmac_key), to_bytes(message)).hexdigest() or ''
    params = urlencode(
        {'message': message, 'signature': sig, 'group': group})
    f = urlopen(url, to_bytes(params))
    data = f.read()
    f.close()
    return data
Ejemplo n.º 8
0
def websocket_send(url, message, hmac_key=None, group='default'):
    sig = hmac_key and hmac.new(to_bytes(hmac_key),
                                to_bytes(message)).hexdigest() or ''
    params = urlencode({'message': message, 'signature': sig, 'group': group})
    f = urlopen(url, to_bytes(params))
    data = f.read()
    f.close()
    return data
Ejemplo n.º 9
0
def upgrade(request, url='http://web2py.com'):
    """Upgrades web2py (src, osx, win) if a new version is posted.
    It detects whether src, osx or win is running and downloads the right one

    Args:
        request: the current request object
            (required to determine version and path)
        url: the incomplete url where to locate the latest web2py
             (actual url is url+'/examples/static/web2py_(src|osx|win).zip')

    Returns
        tuple: completed, traceback

        - completed: True on success, False on failure
          (network problem or old version)
        - traceback: None on success, raised exception details on failure

    """
    web2py_version = request.env.web2py_version
    gluon_parent = request.env.gluon_parent
    if not gluon_parent.endswith('/'):
        gluon_parent += '/'
    (check, version) = check_new_version(web2py_version,
                                         url + '/examples/default/version')
    if not check:
        return False, 'Already latest version'
    if os.path.exists(os.path.join(gluon_parent, 'web2py.exe')):
        version_type = 'win'
        destination = gluon_parent
        subfolder = 'web2py/'
    elif gluon_parent.endswith('/Contents/Resources/'):
        version_type = 'osx'
        destination = gluon_parent[:-len('/Contents/Resources/')]
        subfolder = 'web2py/web2py.app/'
    else:
        version_type = 'src'
        destination = gluon_parent
        subfolder = 'web2py/'

    full_url = url + '/examples/static/web2py_%s.zip' % version_type
    filename = abspath('web2py_%s_downloaded.zip' % version_type)
    try:
        write_file(filename, urlopen(full_url).read(), 'wb')
    except Exception as e:
        return False, e
    try:
        unzip(filename, destination, subfolder)
        return True, None
    except Exception as e:
        return False, e
Ejemplo n.º 10
0
def upgrade(request, url='http://web2py.com'):
    """Upgrades web2py (src, osx, win) if a new version is posted.
    It detects whether src, osx or win is running and downloads the right one

    Args:
        request: the current request object
            (required to determine version and path)
        url: the incomplete url where to locate the latest web2py
             (actual url is url+'/examples/static/web2py_(src|osx|win).zip')

    Returns
        tuple: completed, traceback

        - completed: True on success, False on failure
          (network problem or old version)
        - traceback: None on success, raised exception details on failure

    """
    web2py_version = request.env.web2py_version
    gluon_parent = request.env.gluon_parent
    if not gluon_parent.endswith('/'):
        gluon_parent += '/'
    (check, version) = check_new_version(web2py_version,
                                         url + '/examples/default/version')
    if not check:
        return False, 'Already latest version'
    if os.path.exists(os.path.join(gluon_parent, 'web2py.exe')):
        version_type = 'win'
        destination = gluon_parent
        subfolder = 'web2py/'
    elif gluon_parent.endswith('/Contents/Resources/'):
        version_type = 'osx'
        destination = gluon_parent[:-len('/Contents/Resources/')]
        subfolder = 'web2py/web2py.app/'
    else:
        version_type = 'src'
        destination = gluon_parent
        subfolder = 'web2py/'

    full_url = url + '/examples/static/web2py_%s.zip' % version_type
    filename = abspath('web2py_%s_downloaded.zip' % version_type)
    try:
        write_file(filename, urlopen(full_url).read(), 'wb')
    except Exception as e:
        return False, e
    try:
        unzip(filename, destination, subfolder)
        return True, None
    except Exception as e:
        return False, e
Ejemplo n.º 11
0
 def _CAS_login(self):
     """
     exposed as CAS.login(request)
     returns a token on success, None on failed authentication
     """
     self.ticket = current.request.vars.ticket
     if not current.request.vars.ticket:
         redirect("%s?service=%s" % (self.cas_login_url,
                                     self.cas_my_url))
     else:
         url = "%s?service=%s&ticket=%s" % (self.cas_check_url,
                                            self.cas_my_url,
                                            self.ticket)
         data = to_native(urlopen(url).read())
         if data.startswith('yes') or data.startswith('no'):
             data = data.split('\n')
             if data[0] == 'yes':
                 if ':' in data[1]:  # for Compatibility with Custom CAS
                     items = data[1].split(':')
                     a = items[0]
                     b = len(items) > 1 and items[1] or a
                     c = len(items) > 2 and items[2] or b
                 else:
                     a = b = c = data[1]
                 return dict(user=a, email=b, username=c)
             return None
         try:
             dxml = dom.parseString(data)
             envelop = dxml.getElementsByTagName("cas:authenticationSuccess")
             if len(envelop) > 0:
                 res = dict()
                 for x in envelop[0].childNodes:
                     if x.nodeName.startswith('cas:') and len(x.childNodes):
                         key = to_native(x.nodeName[4:])
                         value = to_native(x.childNodes[0].nodeValue)
                         if key not in res:
                             res[key] = value
                         else:
                             if not isinstance(res[key], list):
                                 res[key] = [res[key]]
                             res[key].append(value)
                 return res
         except expat.ExpatError:
             pass
         return None  # fallback
Ejemplo n.º 12
0
 def _CAS_login(self):
     """
     exposed as CAS.login(request)
     returns a token on success, None on failed authentication
     """
     self.ticket = current.request.vars.ticket
     if not current.request.vars.ticket:
         redirect("%s?service=%s" % (self.cas_login_url, self.cas_my_url))
     else:
         url = "%s?service=%s&ticket=%s" % (self.cas_check_url,
                                            self.cas_my_url, self.ticket)
         data = to_native(urlopen(url).read())
         if data.startswith('yes') or data.startswith('no'):
             data = data.split('\n')
             if data[0] == 'yes':
                 if ':' in data[1]:  # for Compatibility with Custom CAS
                     items = data[1].split(':')
                     a = items[0]
                     b = len(items) > 1 and items[1] or a
                     c = len(items) > 2 and items[2] or b
                 else:
                     a = b = c = data[1]
                 return dict(user=a, email=b, username=c)
             return None
         try:
             dxml = dom.parseString(data)
             envelop = dxml.getElementsByTagName(
                 "cas:authenticationSuccess")
             if len(envelop) > 0:
                 res = dict()
                 for x in envelop[0].childNodes:
                     if x.nodeName.startswith('cas:') and len(x.childNodes):
                         key = to_native(x.nodeName[4:])
                         value = to_native(x.childNodes[0].nodeValue)
                         if key not in res:
                             res[key] = value
                         else:
                             if not isinstance(res[key], list):
                                 res[key] = [res[key]]
                             res[key].append(value)
                 return res
         except expat.ExpatError:
             pass
         return None  # fallback
Ejemplo n.º 13
0
def check_new_version(myversion, version_url):
    """Compares current web2py's version with the latest stable web2py version.

    Args:
        myversion: the current version as stored in file `web2py/VERSION`
        version_URL: the URL that contains the version
                     of the latest stable release

    Returns:
        tuple: state, version

        - state : `True` if upgrade available, `False` if current
                  version is up-to-date, -1 on error,
                  -2 when the system is likely to be offline (no
                  internet link available)
        - version : the most up-to-version available

    """
    try:
        version = to_native(urlopen(version_url).read())
        pversion = parse_version(version)
        pmyversion = parse_version(myversion)
    except IOError as e:
        from socket import gaierror
        if isinstance(getattr(e, 'reason', None), gaierror) and \
            e.reason.errno == -2:
            # assuming the version_url is ok the socket.gaierror
            # (gaierror stands for getaddrinfo() error) that
            # originates the exception is probably due to a
            # missing internet link (i.e. the system is offline)
            print('system is offline, cannot retrieve latest web2py version')
            return -2, myversion
        else:
            print(traceback.format_exc())
            return -1, myversion

    if pversion[:3] + pversion[-6:] > pmyversion[:3] + pmyversion[-6:]:
        return True, version
    else:
        return False, version
Ejemplo n.º 14
0
    def process(self):
        encoded_args = urlencode(self.parameters)
        if self.testmode == True:
            url = 'https://test.authorize.net/gateway/transact.dll'
        else:
            url = 'https://secure.authorize.net/gateway/transact.dll'

        if self.proxy is None:
            self.results += str(urlopen(url, encoded_args).read()).split(
                self.delimiter)
        else:
            opener = FancyURLopener(self.proxy)
            opened = opener.open(url, encoded_args)
            try:
                self.results += str(opened.read()).split(self.delimiter)
            finally:
                opened.close()
        Results = namedtuple(
            'Results',
            'ResultResponse ResponseSubcode ResponseCode ResponseText AuthCode \
                                          AVSResponse TransactionID InvoiceNumber Description Amount PaymentMethod \
                                          TransactionType CustomerID CHFirstName CHLastName Company BillingAddress \
                                          BillingCity BillingState BillingZip BillingCountry Phone Fax Email ShippingFirstName \
                                          ShippingLastName ShippingCompany ShippingAddress ShippingCity ShippingState \
                                          ShippingZip ShippingCountry TaxAmount DutyAmount FreightAmount TaxExemptFlag \
                                          PONumber MD5Hash CVVResponse CAVVResponse'
        )
        self.response = Results(*tuple(r for r in self.results)[0:40])

        if self.getResultResponseFull() == 'Approved':
            self.error = False
            self.success = True
            self.declined = False
        elif self.getResultResponseFull() == 'Declined':
            self.error = False
            self.success = False
            self.declined = True
        else:
            raise AIM.AIMError(self.response.ResponseText)
Ejemplo n.º 15
0
def install_plugins(**urls):
    """ Installs required plugins from urls """
    for name, url in urls.items():
        plugin_install(request.application, urlopen(url), request,
                       "web2py.plugin.%s.w2p" % name)
        print "Required plugin %s installed successfully!" % name