Example #1
0
def create_account():
    """ Create a PythonAnywhere account """
    if not request.vars:
        raise HTTP(400)
    
    if request.vars.username and request.vars.web2py_admin_password:
        # Check if web2py is already there otherwise we get an error 500 too.
        client = ServerProxy('https://%(username)s:%(web2py_admin_password)s@%(username)s.pythonanywhere.com/admin/webservices/call/jsonrpc' % request.vars)
        try:
            if client.login() is True:
                return response.json({'status': 'ok'})
        except ProtocolError as error:
            pass

    url = 'https://www.pythonanywhere.com/api/web2py/create_account'
    data = urlencode(request.vars)
    req = urllib2.Request(url, data)
    
    try:
        reply = urllib2.urlopen(req)
    except urllib2.HTTPError as error:
        if error.code == 400:
            reply = error
        elif error.code == 500:
            return response.json({'status':'error', 'errors':{'username': ['An App other than web2py is installed in the domain %(username)s.pythonanywhere.com' % request.vars]}})
        else:
            raise
    response.headers['Content-Type'] = 'application/json'
    return reply.read()
Example #2
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)
Example #3
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)
Example #4
0
    def __oauth_login(self, next):
        """
        This method redirects the user to the authenticating form
        on authentication server if the authentication code
        and the authentication token are not available to the
        application yet.

        Once the authentication code has been received this method is
        called to set the access token into the session by calling
        accessToken()
        """

        token = self.accessToken()
        if not token:
            current.session.redirect_uri = self.__redirect_uri(next)
            data = dict(redirect_uri=current.session.redirect_uri,
                        response_type='code',
                        client_id=self.client_id)
            if self.args:
                data.update(self.args)
            auth_request_url = self.auth_url + "?" + urlencode(data)
            raise HTTP(302,
                       "You are not authenticated: you are being redirected to the <a href='" + auth_request_url + "'> authentication server</a>",
                       Location=auth_request_url)
        return
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
Example #6
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
Example #7
0
    def get_user(self):
        request = self.request
        # Janrain now sends the token via both a POST body and the query
        # string, so we should keep only one of these.
        token = request.post_vars.token or request.get_vars.token
        if token:
            user = Storage()
            data = urlencode(
                dict(apiKey=self.api_key, token=token))
            auth_info_json = fetch(self.auth_url + '?' + data)
            auth_info = json.loads(auth_info_json)

            if auth_info['stat'] == 'ok':
                self.profile = auth_info['profile']
                provider = re.sub('[^\w\-]', '', self.profile['providerName'])
                user = self.mappings.get(
                    provider, self.mappings.default)(self.profile)
                return user
            elif self.on_login_failure:
                redirect(self.on_login_failure)
        return None
Example #8
0
def create_account():
    """ Create a PythonAnywhere account """
    if not request.vars:
        raise HTTP(400)

    if request.vars.username and request.vars.web2py_admin_password:
        # Check if web2py is already there otherwise we get an error 500 too.
        client = ServerProxy(
            'https://%(username)s:%(web2py_admin_password)s@%(username)s.pythonanywhere.com/admin/webservices/call/jsonrpc'
            % request.vars)
        try:
            if client.login() is True:
                return response.json({'status': 'ok'})
        except ProtocolError as error:
            pass

    url = 'https://www.pythonanywhere.com/api/web2py/create_account'
    data = urlencode(request.vars)
    req = urllib2.Request(url, data)

    try:
        reply = urllib2.urlopen(req)
    except urllib2.HTTPError as error:
        if error.code == 400:
            reply = error
        elif error.code == 500:
            return response.json({
                'status': 'error',
                'errors': {
                    'username': [
                        'An App other than web2py is installed in the domain %(username)s.pythonanywhere.com'
                        % request.vars
                    ]
                }
            })
        else:
            raise
    response.headers['Content-Type'] = 'application/json'
    return reply.read()
Example #9
0
    def __redirect_uri(self, next=None):
        """
        Build the uri used by the authenticating server to redirect
        the client back to the page originating the auth request.
        Appends the _next action to the generated url so the flows continues.
        """

        r = current.request
        http_host = r.env.http_host

        if r.env.https == 'on':
            url_scheme = 'https'
        else:
            url_scheme = r.env.wsgi_url_scheme
        if next:
            path_info = next
        else:
            path_info = r.env.path_info
        uri = '%s://%s%s' % (url_scheme, http_host, path_info)
        if r.get_vars and not next:
            uri += '?' + urlencode(r.get_vars)
        return uri
Example #10
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)
Example #11
0
    def post(self,
             url,
             data=None,
             cookies=None,
             headers=None,
             auth=None,
             method='auto',
             charset='utf-8'):
        self.url = self.app + url

        # if this POST form requires a postback do it
        if data and '_formname' in data and self.postbacks and \
                self.history and self.history[-1][1] != self.url:
            # to bypass the web2py CSRF need to get formkey
            # before submitting the form
            self.get(url, cookies=cookies, headers=headers, auth=auth)

        # unless cookies are specified, recycle cookies
        if cookies is None:
            cookies = self.cookies
        cookies = cookies or {}
        headers = headers or {}

        args = [
            urllib2.HTTPCookieProcessor(self.cookiejar),
            urllib2.HTTPHandler(debuglevel=0)
        ]
        # if required do basic auth
        if auth:
            auth_handler = urllib2.HTTPBasicAuthHandler()
            auth_handler.add_password(**auth)
            args.append(auth_handler)

        opener = urllib2.build_opener(*args)

        # copy headers from dict to list of key,value
        headers_list = []
        for key, value in iteritems(self.default_headers):
            if not key in headers:
                headers[key] = value
        for key, value in iteritems(headers):
            if isinstance(value, (list, tuple)):
                for v in value:
                    headers_list.append((key, v))
            else:
                headers_list.append((key, value))

        # move cookies to headers
        for key, value in iteritems(cookies):
            headers_list.append(('Cookie', '%s=%s' % (key, value)))

        # add headers to request
        for key, value in headers_list:
            opener.addheaders.append((key, str(value)))

        # assume everything is ok and make http request
        error = None
        try:
            if isinstance(data, str):
                self.method = 'POST' if method == 'auto' else method
            elif isinstance(data, dict):
                self.method = 'POST' if method == 'auto' else method
                # if there is only one form, set _formname automatically
                if not '_formname' in data and len(self.forms) == 1:
                    data['_formname'] = next(iter(
                        self.forms.keys()))  # Use the first key

                # if there is no formkey but it is known, set it
                if '_formname' in data and not '_formkey' in data and \
                        data['_formname'] in self.forms:
                    data['_formkey'] = self.forms[data['_formname']]

                # time the POST request
                data = urlencode(data, doseq=True)
            else:
                self.method = 'GET' if method == 'auto' else method
                data = None
            t0 = time.time()
            self.response = opener.open(self.url, to_bytes(data))
            self.time = time.time() - t0
        except urllib2.HTTPError as er:
            error = er
            # catch HTTP errors
            self.time = time.time() - t0
            self.response = er

        if hasattr(self.response, 'getcode'):
            self.status = self.response.getcode()
        else:  #python2.5
            self.status = None

        self.text = self.response.read()
        if charset:
            if charset == 'auto':
                charset = self.response.headers.getparam('charset')
            self.text = to_native(self.text, charset)
        # In PY3 self.response.headers are case sensitive
        self.headers = dict()
        for h in self.response.headers:
            self.headers[h.lower()] = self.response.headers[h]

        # treat web2py tickets as special types of errors
        if error is not None:
            if 'web2py_error' in self.headers:
                raise RuntimeError(self.headers['web2py_error'])
            else:
                raise error

        self._parse_headers_in_cookies()

        # check is a new session id has been issued, symptom of broken session
        if self.session_regex is not None:
            for cookie, value in iteritems(self.cookies):
                match = self.session_regex.match(cookie)
                if match:
                    name = match.group('name')
                    if name in self.sessions and self.sessions[name] != value:
                        print(RuntimeError('Changed session ID %s' % name))
                    self.sessions[name] = value

        # find all forms and formkeys in page
        if charset:
            self.forms = {}
            for match in FORM_REGEX.finditer(self.text):
                self.forms[match.group('formname')] = match.group('formkey')

        # log this request
        self.history.append((self.method, self.url, self.status, self.time))
Example #12
0
    def post(self, url, data=None, cookies=None,
             headers=None, auth=None, method='auto'):
        self.url = self.app + url

        # if this POST form requires a postback do it
        if data and '_formname' in data and self.postbacks and \
                self.history and self.history[-1][1] != self.url:
            # to bypass the web2py CSRF need to get formkey
            # before submitting the form
            self.get(url, cookies=cookies, headers=headers, auth=auth)

        # unless cookies are specified, recycle cookies
        if cookies is None:
            cookies = self.cookies
        cookies = cookies or {}
        headers = headers or {}

        args = [
            urllib2.HTTPCookieProcessor(self.cookiejar),
            urllib2.HTTPHandler(debuglevel=0)
            ]
        # if required do basic auth
        if auth:
            auth_handler = urllib2.HTTPBasicAuthHandler()
            auth_handler.add_password(**auth)
            args.append(auth_handler)

        opener = urllib2.build_opener(*args)

        # copy headers from dict to list of key,value
        headers_list = []
        for key, value in iteritems(self.default_headers):
            if not key in headers:
                headers[key] = value
        for key, value in iteritems(headers):
            if isinstance(value, (list, tuple)):
                for v in value:
                    headers_list.append((key, v))
            else:
                headers_list.append((key, value))

        # move cookies to headers
        for key, value in iteritems(cookies):
            headers_list.append(('Cookie', '%s=%s' % (key, value)))

        # add headers to request
        for key, value in headers_list:
            opener.addheaders.append((key, str(value)))

        # assume everything is ok and make http request
        error = None
        try:
            if isinstance(data, str):
                self.method = 'POST' if method=='auto' else method
            elif isinstance(data, dict):
                self.method = 'POST' if method=='auto' else method
                # if there is only one form, set _formname automatically
                if not '_formname' in data and len(self.forms) == 1:
                    data['_formname'] = self.forms.keys()[0]

                # if there is no formkey but it is known, set it
                if '_formname' in data and not '_formkey' in data and \
                        data['_formname'] in self.forms:
                    data['_formkey'] = self.forms[data['_formname']]

                # time the POST request
                data = urlencode(data, doseq=True)
            else:
                self.method = 'GET' if method=='auto' else method
                data = None
            t0 = time.time()
            self.response = opener.open(self.url, to_bytes(data))
            self.time = time.time() - t0
        except urllib2.HTTPError as er:
            error = er
            # catch HTTP errors
            self.time = time.time() - t0
            self.response = er

        if hasattr(self.response, 'getcode'):
            self.status = self.response.getcode()
        else:#python2.5
            self.status = None

        self.text = to_native(self.response.read())
        # In PY3 self.response.headers are case sensitive
        self.headers = dict()
        for h in self.response.headers:
            self.headers[h.lower()] = self.response.headers[h]

        # treat web2py tickets as special types of errors
        if error is not None:
            if 'web2py_error' in self.headers:
                raise RuntimeError(self.headers['web2py_error'])
            else:
                raise error

        self._parse_headers_in_cookies()

        # check is a new session id has been issued, symptom of broken session
        if self.session_regex is not None:
            for cookie, value in iteritems(self.cookies):
                match = self.session_regex.match(cookie)
                if match:
                    name = match.group('name')
                    if name in self.sessions and self.sessions[name] != value:
                        print(RuntimeError('Changed session ID %s' % name))
                    self.sessions[name] = value

        # find all forms and formkeys in page
        self.forms = {}
        for match in FORM_REGEX.finditer(to_native(self.text)):
            self.forms[match.group('formname')] = match.group('formkey')

        # log this request
        self.history.append((self.method, self.url, self.status, self.time))
Example #13
0
    def accessToken(self):
        """
        Return the access token generated by the authenticating server.

        If token is already in the session that one will be used.
        If token has expired refresh_token is used to get another token. 
        Otherwise the token is fetched from the auth server.
        """
        refresh_token = None
        if current.session.token and 'expires' in current.session.token:
            expires = current.session.token['expires']
            # reuse token until expiration
            if expires == 0 or expires > time.time():
                return current.session.token['access_token']
            if 'refresh_token' in current.session.token:
                refresh_token = current.session.token['refresh_token']

        code = current.request.vars.code

        if code or refresh_token:
            data = dict(
                client_id=self.client_id,
                client_secret=self.client_secret,
            )
            if code:
                data.update(
                    redirect_uri=current.session.redirect_uri,
                    code=code,
                    grant_type='authorization_code'
                )
            elif refresh_token:
                data.update(
                    refresh_token=refresh_token,
                    grant_type='refresh_token'
                )

            open_url = None
            opener = self.__build_url_opener(self.token_url)
            try:
                open_url = opener.open(self.token_url, urlencode(data).encode(), self.socket_timeout)
            except urllib2.HTTPError as e:
                tmp = e.read()
                raise Exception(tmp)
            finally:
                if current.session.code:
                    del current.session.code  # throw it away

            if open_url:
                try:
                    data = open_url.read()

                    try:
                        resp_type = open_url.info().get_content_type()
                    except:
                        # Old python 2 version. This does not work for python3
                        resp_type = open_url.info().gettype()

                    # try json style first
                    if not resp_type or resp_type[:16] == 'application/json':
                        try:
                            tokendata = json.loads(data)
                            current.session.token = tokendata
                        except Exception as e:
                            raise Exception("Cannot parse oauth server response %s %s" % (data, e))
                    else: # try facebook style first with x-www-form-encoded
                        tokendata = cgi.parse_qs(data)
                        current.session.token = \
                          dict([(k, v[-1]) for k, v in tokendata.items()])
                    if not tokendata: # parsing failed?
                        raise Exception("Cannot parse oauth server response %s" % data)
                    # set expiration absolute time try to avoid broken
                    # implementations where "expires_in" becomes "expires"
                    if 'expires_in' in current.session.token:
                        exps = 'expires_in'
                    elif 'expires' in current.session.token:
                        exps = 'expires'
                    else:
                        exps = None
                    current.session.token['expires'] = exps and \
                        int(current.session.token[exps]) + \
                        time.time()
                finally:
                    opener.close()
                return current.session.token['access_token']

        current.session.token = None
        return None