Пример #1
0
    def send_cdr(self, cdr_info):

        # Build CDRs
        data = []
        for cdr in cdr_info:
            time = cdr['time_stamp'].split(' ')
            time = time[0] + 'T' + time[1] + 'Z'

            data.append({
                'cdrSource': self._rss.aggregator_id,
                'productClass': cdr['product_class'],
                'correlationNumber': cdr['correlation'],
                'timestamp': time,
                'application': cdr['offering'],
                'transactionType': 'C',
                'event': cdr['event'],
                'referenceCode': cdr['purchase'],
                'description': cdr['description'],
                'chargedAmount': cdr['cost_value'],
                'chargedTaxAmount': cdr['tax_value'],
                'currency': cdr['cost_currency'],
                'customerId': cdr['customer'],
                'appProvider': cdr['provider']
            })

        # Make request
        url = urljoin(self._rss.host, 'fiware-rss/rss/cdrs')
        headers = {
            'content-type': 'application/json',
            'Authorization': 'Bearer ' + self._rss.access_token
        }

        request = MethodRequest('POST', url, json.dumps(data), headers)

        opener = urllib2.build_opener()
        try:
            try:
                opener.open(request)
            except HTTPError as e:
                if e.code == 401:
                    self._rss.refresh_token()
                    headers[
                        'Authorization'] = 'Bearer ' + self._rss.access_token
                    request = MethodRequest('POST', url, json.dumps(data),
                                            headers)
                    opener.open(request)
                else:
                    raise e
        except:

            db = get_database_connection()
            # Restore correlation numbers
            for cdr in cdr_info:
                org = Organization.objects.get(actor_id=cdr['provider'])
                db.wstore_organization.find_and_modify(
                    query={'_id': ObjectId(org.pk)},
                    update={'$inc': {
                        'correlation_number': -1
                    }})['correlation_number']
Пример #2
0
    def _make_request(self, method, url, params, headers, code):
        opener = urllib2.build_opener()

        # Include credentials in the header
        headers['Authorization'] = self._get_token()
        headers['Accept'] = 'application/json'

        request = MethodRequest(method, url, params, headers)
        response = opener.open(request)

        if response.code != code:
            raise HTTPError(response.url, response.code, response.msg, None, None)

        return response
Пример #3
0
    def start_redirection_payment(self, price, currency):
        url = Site.objects.all()[0].domain
        if url[-1] != '/':
            url += '/'

        # Load request data
        request_data = {
            'offering': {
                'organization':
                self._purchase.offering.owner_organization.name,
                'name': self._purchase.offering.name,
                'version': self._purchase.offering.version
            },
            'callback_url':
            url + 'api/contracting/' + self._purchase.ref + '/accept',
            'error_url':
            url + 'api/contracting/' + self._purchase.ref + '/cancel',
            'price': str(price)
        }
        # Build request
        token = self._purchase.customer.userprofile.access_token
        body = json.dumps(request_data)
        headers = {
            'Content-type': 'application/json',
            'Authorization': 'Bearer ' + token
        }

        request = MethodRequest('POST', FIPAY_ENDPOINT + '/api/payment', body,
                                headers)

        opener = urllib2.build_opener()

        try:
            response = opener.open(request)
        except HTTPError, e:
            if e.code == 401:
                msg = 'The connection with FiPay has returned an unauthorized code, this can happen if you have never accessed FiPay, so your user profile has not been created.'
            else:
                msg = 'The connection with FiPay has failed'
            raise Exception(msg)
Пример #4
0
    def end_redirection_payment(self, token, payer_id):

        # Build request
        request_data = {'token': token}

        # Build request
        user_token = self._purchase.customer.userprofile.access_token
        body = json.dumps(request_data)
        headers = {
            'Content-type': 'application/json',
            'Authorization': 'Bearer ' + user_token
        }

        request = MethodRequest('POST', FIPAY_ENDPOINT + '/api/end', body,
                                headers)

        opener = urllib2.build_opener()

        try:
            opener.open(request)
        except:
            raise Exception('The connection with FiPay has failed')
Пример #5
0
    def oauth2_login(self, username='******'):
        from wstore.selenium_tests.tests import TESTING_PORT
        self.driver.get(
            self.live_server_url +
            '/oauth2/auth?response_type=code&client_id=test_app&redirect_uri=http://localhost:'
            + unicode(TESTING_PORT))

        self.login(username)

        self.driver.find_element_by_class_name('btn-blue').click()
        time.sleep(1)

        # Get authorization code
        while self._server.call_received() < 1:
            pass

        code = self._server.get_path().split('=')[1]

        # Get access token
        opener = urllib2.build_opener()

        url = self.live_server_url + '/oauth2/token'

        data = 'client_id=test_app'
        data += '&client_secret=secret'
        data += '&grant_type=authorization_code'
        data += '&code=' + code
        data += '&redirect_uri=' + 'http://localhost:' + unicode(TESTING_PORT)

        headers = {
            'content-type': 'application/form-url-encoded',
        }
        request = MethodRequest('POST', url, data, headers)

        response = opener.open(request)

        token = json.loads(response.read())['access_token']

        return token
Пример #6
0
    def _make_request(self, method, url, data={}):
        """
           Makes requests to the RSS
        """
        opener = urllib2.build_opener()

        auth_header = self._get_auth_header()

        headers = {
            'content-type': 'application/json'
        }

        headers[auth_header] = self._get_token_type() + self._credentials

        request = MethodRequest(method, url, json.dumps(data), headers)

        response = opener.open(request)

        if not (response.code > 199 and response.code < 300):
            raise HTTPError(response.url, response.code, response.msg, None, None)

        return response
Пример #7
0
    def send_cdr(self, cdr_info):

        # Build XML document
        root = etree.Element('cdrs')

        for cdr in cdr_info:
            node = etree.Element('cdr')

            id_serv = etree.Element('id_service_provider')
            id_serv.text = cdr['provider']
            node.append(id_serv)

            id_app = etree.Element('id_application')
            id_app.text = cdr['service']
            node.append(id_app)

            id_evnt = etree.Element('id_event')
            id_evnt.text = cdr['defined_model']
            node.append(id_evnt)

            id_corr = etree.Element('id_correlation')
            id_corr.text = cdr['correlation']
            node.append(id_corr)

            purch_code = etree.Element('purchase_code')
            purch_code.text = cdr['purchase']
            node.append(purch_code)

            par_app_id = etree.Element('parent_app_id')
            par_app_id.text = cdr['offering']
            node.append(par_app_id)

            prod_class = etree.Element('product_class')
            prod_class.text = cdr['product_class']
            node.append(prod_class)

            desc = etree.Element('description')
            desc.text = cdr['description']
            node.append(desc)

            cost_curr = etree.Element('cost_currency')
            cost_curr.text = cdr['cost_currency']
            node.append(cost_curr)

            cost_units = etree.Element('cost_units')
            cost_units.text = cdr['cost_value']
            node.append(cost_units)

            tax_curr = etree.Element('tax_currency')
            tax_curr.text = cdr['tax_currency']
            node.append(tax_curr)

            tax_units = etree.Element('tax_units')
            tax_units.text = cdr['tax_value']
            node.append(tax_units)

            source = etree.Element('cdr_source')
            source.text = cdr['source']
            node.append(source)

            id_op = etree.Element('id_operator')
            id_op.text = cdr['operator']
            node.append(id_op)

            id_country = etree.Element('id_country')
            id_country.text = cdr['country']
            node.append(id_country)

            time_stamp = etree.Element('time_stamp')
            time_stamp.text = cdr['time_stamp']
            node.append(time_stamp)

            id_user = etree.Element('id_user')
            id_user.text = cdr['customer']
            node.append(id_user)

            root.append(node)

        rss_url = self._rss.host
        opener = urllib2.build_opener()

        if not rss_url.endswith('/'):
            rss_url += '/'

        url = urljoin(rss_url, 'fiware-rss/rss/cdrs')
        data = etree.tostring(root, pretty_print=True, xml_declaration=True)

        headers = {
            'content-type': 'application/xml',
            'X-Auth-Token': self._rss.access_token
        }
        request = MethodRequest('POST', url, data, headers)

        response = opener.open(request)

        if not (response.code > 199 and response.code < 300):
            raise HTTPError(response.url, response.code, response.msg, None,
                            None)
    def test_remote_purchase_form(self):

        token = self.oauth2_login()

        # Make API request to initiate the process
        opener = urllib2.build_opener()
        url = self.live_server_url + '/api/contracting/form'

        data = {
            'offering': {
                'organization': 'provider',
                'name': 'test_offering1',
                'version': '1.1'
            },
            'redirect_uri': 'http://localhost:' + unicode(TESTING_PORT)
        }

        headers = {
            'content-type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer ' + token
        }
        request = MethodRequest('POST', url, json.dumps(data), headers)

        response = opener.open(request)

        # Redirect browser to the remote purchase form
        form_url = json.loads(response.read())['url']
        self.driver.get(form_url)

        # Fill purchase form
        self.fill_tax_address({
            'street': 'fake street',
            'postal': '12345',
            'city': 'fake city',
            'country': 'Spain'
        })

        self.driver.find_element_by_css_selector(
            '.modal-footer .btn-basic').click()

        # Wait until the purchase modal dissapears
        element = WebDriverWait(self.driver,
                                5).until(self.get_modal_wait('postal'))

        # Close download resources modal
        WebDriverWait(self.driver, 5).until(
            EC.element_to_be_clickable(
                (By.CSS_SELECTOR, '.modal-footer .btn-basic'))).click()

        # Wait until the dowload modal dissapears
        element = WebDriverWait(self.driver,
                                5).until(self.get_modal_wait('message'))

        # End the purchase
        element.click()

        # Check redirection
        WebDriverWait(self.driver, 5).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, "hr")))
        expected_url = 'http://localhost:' + unicode(TESTING_PORT) + '/'
        self.assertEquals(self.driver.current_url, expected_url)
Пример #9
0
def get_api_user(request):

    import json
    import urllib2
    from django.conf import settings
    from wstore.oauth2provider.models import Token
    from django.contrib.auth.models import User, AnonymousUser
    from wstore.social_auth_backend import FIWARE_USER_DATA_URL, fill_internal_user_info, FiwareBackend
    from wstore.store_commons.utils.method_request import MethodRequest

    # Get access_token from the request
    try:
        auth_info = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
        auth_type = auth_info[0]
        token = auth_info[1]
    except:
        return AnonymousUser()

    # If using the idM to authenticate users, validate the token

    if settings.OILAUTH:
        opener = urllib2.build_opener()
        url = FIWARE_USER_DATA_URL + '?access_token=' + token
        request = MethodRequest('GET', url)

        try:
            new_user = False
            response = opener.open(request)
            user_info = json.loads(response.read())
            # Try to get an internal user
            try:
                user_id = None
                if settings.FIWARE_IDM_API_VERSION == 1:
                    user_id = user_info['nickName']
                else:
                    user_id = user_info['id']

                user = User.objects.get(username=user_id)
            except:
                # The user is valid but she has never accessed wstore so
                # internal models should be created
                from social_auth.backends.pipeline.user import get_username
                from social_auth.backends.pipeline.user import create_user
                from social_auth.backends.pipeline.social import associate_user
                from social_auth.backends.pipeline.social import load_extra_data

                # The request is from a new user
                new_user = True

                # Get the internal username to be used
                details = {
                    'username': user_info['nickName'],
                    'email': user_info['email'],
                    'fullname': user_info['displayName']
                }
                username = get_username(details)

                # Create user structure
                auth_user = create_user('', details, '', user_info['actorId'], username['username'])

                # associate user with social user
                social_user = associate_user(FiwareBackend, auth_user['user'], user_info['actorId'])

                # Load  user extra data
                request = {
                    'access_token': token
                }
                load_extra_data(FiwareBackend, details, request, user_info['actorId'], social_user['user'], social_user=social_user['social_user'])

                # Refresh user info
                user = User.objects.get(username=user_info['nickName'])

            # If it is a new user the auth info contained in the userprofile is not valid
            if not new_user:
                # The user has been validated but the user info is not valid since the
                # used token belongs to an external application

                # Get FiPay token for the user
                token = user.userprofile.access_token

                # Get valid user info for Fipay
                url = FIWARE_USER_DATA_URL + '?access_token=' + token
                request = MethodRequest('GET', url)

                try:
                    response = opener.open(request)
                    user_info = json.loads(response.read())
                except Exception, e:

                    if e.code == 401:
                        # The access token may expired, try to refresh it
                        social = user.social_auth.filter(provider='fiware')[0]
                        social.refresh_token()

                        # Try to get user info with the new access token
                        social = user.social_auth.filter(provider='fiware')[0]
                        new_credentials = social.extra_data

                        user.userprofile.access_token = new_credentials['access_token']
                        user.userprofile.refresh_token = new_credentials['refresh_token']
                        user.userprofile.save()

                        token = user.userprofile.access_token
                        url = FIWARE_USER_DATA_URL + '?access_token=' + token
                        request = MethodRequest('GET', url)
                        response = opener.open(request)
                        user_info = json.loads(response.read())
                    else:
                        raise(e)

                user_info['access_token'] = token
                user_info['refresh_token'] = user.userprofile.refresh_token
                fill_internal_user_info((), response=user_info, user=user)

        except Exception, e:
            user = AnonymousUser()