def provide_authorization_code(request): params = dict(request.GET) if 'response_type' not in params: return build_response(request, 400, 'Missing parameter response_type in URL query') if 'client_id' not in params: return build_response(request, 400, 'Missing parameter client_id in URL query') if 'redirect_uri' not in params: return build_response(request, 400, 'Missing parameter redirect_uri in URL query') params = { 'response_type': params['response_type'][0], 'client_id': params['client_id'][0], 'redirect_uri': params['redirect_uri'][0] } if request.method == 'GET': return render(request, 'oauth2provider/auth.html', {'app': provider.get_client(params['client_id'])}) else: return provider.get_authorization_code(request.user, **params)
def create(self, request): # In case the user cancels the payment is necessary to update # the database in order to avoid an inconsistent state try: data = json.loads(request.body) order = Order.objects.get(order_id=data['orderId']) # Get the payment client # Load payment client cln_str = settings.PAYMENT_CLIENT client_package, client_class = cln_str.rsplit('.', 1) payment_client = getattr(importlib.import_module(client_package), client_class) # build the payment client client = payment_client(order) for sale in order.sales_ids: client.refund(sale) # Only those orders with all its order items in ack state can be refunded # that means that all the contracts have been refunded for contract in order.contracts: cdr_manager = CDRManager(order, contract) charge = contract.charges[-1] cdr_manager.refund_cdrs(charge['cost'], charge['duty_free'], charge['date'].isoformat() + 'Z') # Create a refund CDR for each contract order.delete() except: return build_response(request, 400, 'Sales cannot be refunded') return build_response(request, 200, 'Ok')
def create(self, request): if not request.user.is_staff: # Only an admin could register the store in a marketplace return build_response(request, 403, 'Forbidden') name = None host = None # Get contents from the request try: content = json.loads(request.raw_post_data) name = content['name'] host = content['host'] except: msg = "Request body is not valid JSON data" return build_response(request, 400, msg) # Check data formats if not is_valid_id(name): return build_response(request, 400, 'Invalid name format') if not is_valid_url(host): return build_response(request, 400, 'Invalid URL format') code = 201 msg = 'Created' try: # Register the store in the selected marketplace register_on_market(name, host, get_current_site(request).domain) except Exception, e: if e.message == 'Bad Gateway': code = 502 msg = e.message else: code = 400 msg = 'Bad request'
def update(self, request, organization, name, version): user = request.user # Get the offering try: offering, org = _get_offering(organization, name, version) except ObjectDoesNotExist as e: return build_response(request, 404, unicode(e)) except Exception as e: return build_response(request, 400, unicode(e)) # Update the offering try: # Check if the user is the owner of the offering or if is a manager of the # owner organization if user.userprofile.current_organization != org \ or (not offering.is_owner(user) and user.pk not in org.managers): return build_response(request, 403, 'You are not allowed to edit the current offering') data = json.loads(request.raw_post_data) update_offering(user, offering, data) except Exception, e: return build_response(request, 400, e.message)
def update(self, request, currency): """ This method is used to change the default currency """ if not request.user.is_staff: build_response(request, 403, 'Forbidden') # Get the context context = Context.objects.all()[0] # Check that the currency exist if not 'default' in context.allowed_currencies: return build_response(request, 404, 'Not found') if not currency.lower() == context.allowed_currencies['default'].lower(): for c in context.allowed_currencies['allowed']: if c['currency'].lower() == currency.lower(): break else: return build_response(request, 404, 'Not found') # Make the currency the default currency context.allowed_currencies['default'] = currency context.save() # Return response return build_response(request, 200, 'OK')
def create(self, request): try: data = json.loads(request.body) except: return build_response( request, 400, 'The request does not contain a valid JSON object') if 'orderId' not in data or 'productId' not in data: return build_response( request, 422, 'Missing required field, it must include orderId and productId' ) # Get order and product info try: order = Order.objects.get(order_id=data['orderId']) except: return build_response( request, 404, 'The oid specified in the product name is not valid') try: contract = order.get_product_contract(data['productId']) except: return build_response(request, 404, 'The specified product id is not valid') # Refresh accounting information on_usage_refreshed(order, contract) return build_response(request, 200, 'Ok')
def delete(self, request, repository): result = _manage_repository(request.user, repository, unregister_repository) if result[0]: return build_response(request, result[1], result[2]) else: return build_response(request, 204, 'No content')
def read(self, request, org, name, version): # Get resource model try: organization = Organization.objects.get(name=org) resource = WStore_resource.objects.get(provider=organization, name=name, version=version) except: return build_response(request, 404, 'Resource not found') # Check resource state if resource.state == 'deleted': return build_response(request, 404, 'Resource not found') # Get offering where the resource is included response = [] try: for off in resource.offerings: offering = Offering.objects.get(pk=off) if offering.state == 'published': response.append(get_offering_info(offering, request.user)) except Exception as e: return build_response(request, 400, unicode(e)) return HttpResponse(json.dumps(response), status=200, mimetype='application/json')
def update(self, request, reference): purchase = Purchase.objects.get(ref=reference) data = json.loads(request.raw_post_data) try: if data['method'] == 'paypal': charging_engine = ChargingEngine(purchase, payment_method='paypal') elif data['method'] == 'credit_card': # Get the payment info if 'credit_card' in data: credit_card = data['credit_card'] else: if purchase.organization_owned: credit_card = purchase.owner_organization.payment_info else: credit_card = purchase.customer.userprofile.payment_info charging_engine = ChargingEngine(purchase, payment_method='credit_card', credit_card=credit_card) charging_engine.resolve_charging() except: # Refresh the purchase info purchase = Purchase.objects.get(ref=reference) rollback(purchase) return build_response(request, 400, 'Invalid JSON content') return build_response(request, 200, 'OK')
def create(self, request): if not request.user.is_staff: # Only an admin could register a new repository return build_response(request, 403, 'Forbidden') # Get request info name = None host = None try: content = json.loads(request.raw_post_data) name = content['name'] host = content['host'] except: msg = "Request body is not valid JSON data" return build_response(request, 400, msg) # Check data formats if not is_valid_id(name): return build_response(request, 400, 'Invalid name format') if not is_valid_url(host): return build_response(request, 400, 'Invalid URL format') # Register repository try: register_repository(name, host) except Exception, e: return build_response(request, 400, e.message)
def create(self, request): try: # Extract SDR document from the HTTP request data = json.loads(request.body) except: # The usage document is not valid, so the state cannot be changed return build_response(request, 400, 'The request does not contain a valid JSON object') # Validate usage information response = None try: sdr_manager = SDRManager() sdr_manager.validate_sdr(data) except PermissionDenied as e: response = build_response(request, 403, unicode(e)) except ValueError as e: response = build_response(request, 422, unicode(e)) except: response = build_response(request, 500, 'The SDR document could not be processed due to an unexpected error') usage_client = UsageClient() if response is not None: # The usage document is not valid, change its state to Rejected usage_client.update_usage_state('Rejected', data) else: # The usage document is valid, change its state to Guided usage_client.update_usage_state('Guided', data) response = build_response(request, 200, 'OK') # Update usage document state return response
def read(self, request): pagination = { 'start': request.GET.get('start', None), 'limit': request.GET.get('limit', None) } if pagination['start'] == None or pagination['limit'] == None: pagination = None profile = request.user.userprofile filter_ = request.GET.get('open', None) if filter_ and filter_ != 'true' and filter_ != 'false': return build_response(request, 400, 'Invalid open param') open_res = None if filter_ is not None: open_res = False if filter_ == 'true': open_res = True if 'provider' in profile.get_current_roles(): try: response = get_provider_resources(request.user, filter_=open_res, pagination=pagination) except Exception, e: return build_response(request, 400, e.message)
def create(self, request): user = request.user profile = user.userprofile content_type = get_content_type(request)[0] if 'provider' in profile.get_current_roles(): try: if content_type == 'application/json': data = json.loads(request.raw_post_data) register_resource(user, data) else: data = json.loads(request.POST['json']) f = request.FILES['file'] register_resource(user, data, file_=f) except ConflictError as e: return build_response(request, 409, unicode(e)) except Exception as e: return build_response(request, 400, unicode(e)) else: return build_response(request, 403, "You don't have the provider role") return build_response(request, 201, 'Created')
def delete(self, request, rss): if not request.user.is_staff: return build_response(request, 403, 'Forbidden') # Get rss entry try: rss_model = RSS.objects.get(name=rss) except: return build_response(request, 404, 'Not found') # Delete provider limits rss_factory = RSSManagerFactory(rss_model) exp_manager = rss_factory.get_expenditure_manager(request.user.userprofile.access_token) call_result = _make_rss_request(exp_manager, exp_manager.delete_provider_limit, request.user) if call_result[0]: return build_response(request, call_result[1], call_result[2]) # Delete rs models model_manager = rss_factory.get_model_manager(request.user.userprofile.access_token) call_result = _make_rss_request(model_manager, model_manager.delete_provider_models, request.user) if call_result[0]: return build_response(request, call_result[1], call_result[2]) # Delete rss model rss_model.delete() return build_response(request, 204, 'No content')
def _call_resource_entry_method(request, resource_id_info, method, data=None): response = build_response(request, 204, 'No Content') if data: response = build_response(request, 200, 'OK') error = False try: resource = _get_resource(resource_id_info) except: error = True response = build_response(request, 404, 'Resource not found') # Check permissions if not error and (not 'provider' in request.user.userprofile.get_current_roles() or\ not request.user.userprofile.current_organization == resource.provider): error = True response = build_response(request, 403, 'Forbidden') # Try to make the specified action if not error: try: args = (resource, ) if data: args = args + data method(*args) except Exception as e: response = build_response(request, 400, unicode(e)) # Return the response return response
def create(self, request): # In case the user cancels the payment is necessary to update # the database in order to avoid an inconsistent state try: data = json.loads(request.body) order = Order.objects.get(order_id=data['orderId']) # Get the payment client # Load payment client cln_str = settings.PAYMENT_CLIENT client_package, client_class = cln_str.rsplit('.', 1) payment_client = getattr(importlib.import_module(client_package), client_class) # build the payment client client = payment_client(order) for sale in order.sales_ids: client.refund(sale) order.delete() except: return build_response(request, 400, 'Sales cannot be refunded') return build_response(request, 200, 'Ok')
def create(self, request): # In case the user cancels the payment is necessary to update # the database in order to avoid an inconsistent state try: data = json.loads(request.body) order = Order.objects.get(order_id=data['orderId']) # Get the payment client # Load payment client cln_str = settings.PAYMENT_CLIENT client_package, client_class = cln_str.rsplit('.', 1) payment_client = getattr(importlib.import_module(client_package), client_class) # build the payment client client = payment_client(order) for sale in order.sales_ids: client.refund(sale) # Only those orders with all its order items in ack state can be refunded # that means that all the contracts have been refunded for contract in order.contracts: if len(contract.charges) > 0: cdr_manager = CDRManager(order, contract) charge = contract.charges[-1] # Create a refund CDR for each contract cdr_manager.refund_cdrs(charge['cost'], charge['duty_free'], charge['date'].isoformat() + 'Z') order.delete() except: return build_response(request, 400, 'Sales cannot be refunded') return build_response(request, 200, 'Ok')
def read(self, request, organization, name, version): # Get offering try: org = Organization.objects.get(name=organization) offering = Offering.objects.get(owner_organization=org, name=name, version=version) except: return build_response(request, 404, 'Not found') # Check if is a tagging recommendation or a tags request action = request.GET.get('action', None) if action: if action == 'recommend': # Get user tags tags = request.GET.get('tags', '') # Split tags tags = set(tags.split(',')) # Get recommended tags rec_man = RecommendationManager(offering, tags) response = { 'tags': [tag for tag, r in rec_man.get_recommended_tags()] } else: return build_response(request, 400, 'Invalid action') else: response = { 'tags': offering.tags } # Build response return HttpResponse(json.dumps(response), status=200, mimetype='application/json')
def _call_resource_entry_method(request, resource_id_info, method, data, is_del=False): response = build_response(request, 200, 'OK') if is_del: response = build_response(request, 204, 'No Content') error = False try: resource = _get_resource(resource_id_info) except: error = True response = build_response(request, 404, 'Resource not found') # Check permissions if not error and ('provider' not in request.user.userprofile.get_current_roles() or not request.user.userprofile.current_organization == resource.provider): error = True response = build_response(request, 403, 'Forbidden') # Try to make the specified action if not error: try: args = (resource, ) + data method(*args) except Exception as e: response = build_response(request, 400, unicode(e)) # Return the response return response
def read(self, request, organization, name, version): # Get offering try: org = Organization.objects.get(name=organization) offering = Offering.objects.get(owner_organization=org, name=name, version=version) except: return build_response(request, 404, 'Not found') # Check if is a tagging recommendation or a tags request action = request.GET.get('action', None) if action: if action == 'recommend': # Get user tags tags = request.GET.get('tags', '') # Split tags tags = set(tags.split(',')) # Get recommended tags rec_man = RecommendationManager(offering, tags) response = { 'tags': [tag for tag, r in rec_man.get_recommended_tags()] } else: return build_response(request, 400, 'Invalid action') else: response = {'tags': offering.tags} # Build response return HttpResponse(json.dumps(response), status=200, mimetype='application/json')
def update(self, request, organization, name, version): logger.debug("OfferingEntry.update()") user = request.user # Get the offering try: offering, org = _get_offering(organization, name, version) except ObjectDoesNotExist as e: return build_response(request, 404, unicode(e)) except Exception as e: return build_response(request, 400, unicode(e)) # Update the offering try: # Check if the user is the owner of the offering or if is a manager of the # owner organization if user.userprofile.current_organization != org\ or (not offering.is_owner(user) and not user.pk in org.managers): return build_response(request, 403, 'You are not allowed to edit the current offering') data = json.loads(request.raw_post_data) update_offering(offering, data) except Exception, e: import traceback import StringIO buff = StringIO.StringIO() traceback.print_exc(file=buff) print("EXCEPTION: %s %s" % (str(e), buff.getvalue())) return build_response(request, 400, e.message)
def update(self, request, currency): """ This method is used to change the default currency """ if not request.user.is_staff: build_response(request, 403, 'Forbidden') # Get the context context = Context.objects.all()[0] # Check that the currency exist if not 'default' in context.allowed_currencies: return build_response(request, 404, 'Not found') if not currency.lower() == context.allowed_currencies['default'].lower( ): for c in context.allowed_currencies['allowed']: if c['currency'].lower() == currency.lower(): break else: return build_response(request, 404, 'Not found') # Make the currency the default currency context.allowed_currencies['default'] = currency context.save() # Return response return build_response(request, 200, 'OK')
def _validate_catalog_element(request, element, validator): # Validate user permissions user = request.user if "provider" not in user.userprofile.get_current_roles() and not user.is_staff: return build_response(request, 403, "You don't have the seller role") # Parse content try: data = json.loads(request.body) except: return build_response(request, 400, "The content is not a valid JSON document") if "action" not in data: return build_response(request, 400, "Missing required field: action") if element not in data: return build_response(request, 400, "Missing required field: product") try: validator.validate(data["action"], user.userprofile.current_organization, data[element]) except ValueError as e: return build_response(request, 400, unicode(e)) except ProductError as e: return build_response(request, 400, unicode(e)) except PluginError as e: return build_response(request, 422, unicode(e)) except PermissionDenied as e: return build_response(request, 403, unicode(e)) except: return build_response(request, 500, "An unexpected error has occurred") return build_response(request, 200, "OK")
def create(self, request): try: event = json.loads(request.body) except: return build_response( request, 400, 'The provided data is not a valid JSON object') if event['eventType'] != 'ProductCreationNotification': return build_response(request, 200, 'OK') product = event['event']['product'] # Extract order id order_id = product['name'].split('=')[1] # Get order order = Order.objects.get(order_id=order_id) contract = None # Search contract for cont in order.contracts: if product['productOffering']['id'] == cont.offering.off_id: contract = cont if contract is None: return build_response( request, 404, 'There is not a contract for the specified product') # Save contract id contract.product_id = product['id'] order.save() # Activate asset try: on_product_acquired(order, contract) except: return build_response(request, 400, 'The asset has failed to be activated') # Change product state to active inventory_client = InventoryClient() inventory_client.activate_product(product['id']) # Create the initial charge in the billing API if len(contract.charges) == 1: billing_client = BillingClient() valid_to = None # If the initial charge was a subscription is needed to determine the expiration date if 'subscription' in contract.pricing_model: valid_to = contract.pricing_model['subscription'][0][ 'renovation_date'] billing_client.create_charge(contract.charges[0], contract.product_id, start_date=None, end_date=valid_to) return build_response(request, 200, 'OK')
def read(self, request): """ Retrives the existing digital assets associated with a given seller :param request: :return: JSON List containing the existing assets """ pagination = { 'start': request.GET.get('start', None), 'limit': request.GET.get('limit', None) } if pagination['start'] is None or pagination['limit'] is None: pagination = None profile = request.user.userprofile if 'provider' not in profile.get_current_roles(): return build_response(request, 403, 'You are not authorized to retrieve digital asset information') try: asset_manager = AssetManager() response = asset_manager.get_provider_assets_info(request.user, pagination=pagination) except Exception as e: return build_response(request, 400, unicode(e)) return HttpResponse(json.dumps(response), status=200, mimetype='application/json; charset=utf-8')
def read(self, request, text): index_path = os.path.join(settings.BASEDIR, 'wstore') index_path = os.path.join(index_path, 'search') index_path = os.path.join(index_path, 'indexes') search_engine = SearchEngine(index_path) filter_ = request.GET.get('filter', None) action = request.GET.get('action', None) start = request.GET.get('start', None) limit = request.GET.get('limit', None) sort = request.GET.get('sort', None) # Check the filter value if filter_ and filter_ != 'published' and filter_ != 'provided' and filter_ != 'purchased': return build_response(request, 400, 'Invalid filter') count = False pagination = None # Check if the action is count if action != None: if action == 'count': count = True else: return build_response(request, 400, 'Invalid action') else: # Check pagination params (Only when action is none) if start != None and limit != None: pagination = { 'start': int(start), 'limit': int(limit) } elif (start != None and limit == None) or (start == None and limit != None): return build_response(request, 400, 'Missing pagination param') # Check sorting values if sort != None: if sort != 'date' and sort != 'popularity' and sort != 'name': return build_response(request, 400, 'Invalid sorting') if not filter_: response = search_engine.full_text_search(request.user, text, count=count, pagination=pagination, sort=sort) elif filter_ == 'provided': state = request.GET.get('state', 'all') # Check the state value if state != 'all' and state != 'uploaded'\ and state != 'published' and state != 'deleted': return build_response(request, 400, 'Invalid state') response = search_engine.full_text_search(request.user, text, state=state, count=count, pagination=pagination, sort=sort) elif filter_ == 'purchased': response = search_engine.full_text_search(request.user, text, state='purchased', count=count, pagination=pagination, sort=sort) return HttpResponse(json.dumps(response), status=200, mimetype='application/json')
def payout_reports(self, request): try: reports = json.loads(request.body) except: return build_response(request, 400, 'The provided data is not a valid JSON object') # Check reports? payouteng = PayoutEngine() payouteng.process_reports(reports) return build_response(request, 201)
def create(self, request): """ Receives notifications from the ordering API when a new order is created :param request: :return: """ user = request.user try: order = json.loads(request.body) except: return build_response( request, 400, 'The provided data is not a valid JSON object') client = OrderingClient() client.update_state(order, 'InProgress') try: # Check that the user has a billing address response = None om = OrderingManager() redirect_url = om.process_order(user, order) if redirect_url is not None: client.update_state(order, 'Pending') response = HttpResponse( json.dumps({'redirectUrl': redirect_url}), status=200, mimetype='application/json; charset=utf-8') else: # All the order items are free so digital assets can be set as Completed digital_items = [] order_model = Order.objects.get(order_id=order['id']) for item in order['orderItem']: contract = order_model.get_item_contract( item_id=item['id']) if contract.offering.is_digital: digital_items.append(item) client.update_items_state(order, 'Completed', digital_items) response = build_response(request, 200, 'OK') except OrderingError as e: response = build_response(request, 400, unicode(e.value)) client.update_items_state(order, 'Failed') except Exception as e: response = build_response(request, 500, 'Your order could not be processed') client.update_items_state(order, 'Failed') return response
def read(self, request): logger.debug("OfferingCollection.read()") try: # Read the query string in order to know the filter and the page filter_ = request.GET.get('filter', 'published') user = request.user action = request.GET.get('action', None) sort = request.GET.get('sort', None) # Check sorting values if sort != None: if sort != 'date' and sort != 'popularity' and sort != 'name': return build_response(request, 400, 'Invalid sorting') pagination = { 'skip': request.GET.get('start', None), 'limit': request.GET.get('limit', None) } if action != 'count': if pagination['skip'] and pagination['limit']: if filter_ == 'provided': result = get_offerings(user, request.GET.get('state'), owned=True, pagination=pagination, sort=sort) elif filter_ == 'published': result = get_offerings(user, pagination=pagination, sort=sort) elif filter_ == 'purchased': result = get_offerings(user, 'purchased', owned=True, pagination=pagination, sort=sort) else: if filter_ == 'provided': result = get_offerings(user, request.GET.get('state'), owned=True, sort=sort) elif filter_ == 'published': result = get_offerings(user, sort=sort) elif filter_ == 'purchased': result = get_offerings(user, 'purchased', owned=True, sort=sort) else: if filter_ == 'provided': result = count_offerings(user, request.GET.get('state'), owned=True) elif filter_ == 'published': result = count_offerings(user) elif filter_ == 'purchased': result = count_offerings(user, 'purchased', owned=True) except Exception as e: return build_response(request, 400, unicode(e)) mime_type = 'application/JSON; charset=UTF-8' return HttpResponse(json.dumps(result), status=200, mimetype=mime_type)
def create(self, request): try: order = json.loads(request.body) except: return build_response(request, 400, 'The provided data is not a valid JSON object') if order.get('status') != 'COMPLETED': print("Order status: {}".format(order.get('status'))) return build_response(request, 200) payouteng = PayoutEngine() payouteng.process_unpaid() return build_response(request, 200)
def read(self, request, organization, name, version): user = request.user try: org = Organization.objects.get(name=organization) offering = Offering.objects.get(name=name, owner_organization=org, version=version) except: return build_response(request, 404, 'Not found') try: result = get_offering_info(offering, user) except Exception, e: return build_response(request, 400, e.message)
def create(self, request): if not request.user.is_staff: return build_response(request, 403, 'Forbidden') try: data = json.loads(request.raw_post_data) if not len(data['name']) > 4 or not is_valid_id(data['name']): raise Exception('Invalid name format') if 'notification_url' in data: if data['notification_url'] and not is_valid_url(data['notification_url']): raise Exception('Invalid notification URL format') else: data['notification_url'] = '' tax_address = {} if 'tax_address' in data: tax_address = { 'street': data['tax_address']['street'], 'postal': data['tax_address']['postal'], 'city': data['tax_address']['city'], 'country': data['tax_address']['country'] } payment_info = {} if 'payment_info' in data: if not is_valid_credit_card(data['payment_info']['number']): raise Exception() payment_info = { 'type': data['payment_info']['type'], 'number': data['payment_info']['number'], 'expire_month': data['payment_info']['expire_month'], 'expire_year': data['payment_info']['expire_year'], 'cvv2': data['payment_info']['cvv2'] } Organization.objects.create( name=data['name'], notification_url=data['notification_url'], tax_address=tax_address, payment_info=payment_info, private=False ) except Exception as e: msg = e.message if not msg.startswith('Invalid'): msg = 'Invalid content' return build_response(request, 400, msg) return build_response(request, 201, 'Created')
def read(self, request, organization, name, version): user = request.user try: offering, org = _get_offering(organization, name, version) except ObjectDoesNotExist as e: return build_response(request, 404, unicode(e)) except Exception as e: return build_response(request, 400, unicode(e)) try: result = get_offering_info(offering, user) except Exception, e: return build_response(request, 400, unicode(e))
def read(self, request): profile = request.user.userprofile filter_ = request.GET.get('open', None) if filter_ and filter_ != 'true' and filter_ != 'false': return build_response(request, 400, 'Invalid open param') if 'provider' in profile.get_current_roles(): try: response = get_provider_resources(request.user, filter_=filter_) except Exception, e: return build_response(request, 400, e.message)
def create(self, request): """ Creates a new OAuth2 token :param request: refresh token and application id :return: JSON containing the new OAuth2 token """ response = {} #proxy_url = AUTHORIZE_SERVICE try: body = json.loads(request.body) refreshToken = body['refresh_token'] application_id = body['appId'] except Exception as e: return build_response(request, 400, 'Invalid request') #token_store = tokenStore() keystone_client = KeystoneClient(KEYSTONE_USER, KEYSTONE_PWD, ADMIN_DOMAIN, KEYSTONE_PROTOCOL, KEYSTONE_HOST, KEYSTONE_PORT) try: application_info = keystone_client.get_application_by_id( application_id) if 'application' in application_info: client_secret = application_info['application']['secret'] else: return build_response(request, 404, 'application does not exist') #authorization = "Basic " + str(base64.b64encode(APP_CLIENT_ID + ":" + APP_CLIENT_SECRET)) authorization = "Basic " + str( base64.b64encode(application_id + ":" + client_secret)) url = KEYSTONE_PROTOCOL + '://' + KEYSTONE_HOST + ":" + KEYROCK_PORT + "/oauth2/token" data = "grant_type=refresh_token&refresh_token=" + refreshToken headers = { 'Content-type': 'application/x-www-form-urlencoded', 'Authorization': authorization } r = requests.post(url, data=data, headers=headers) #Check if token has been correctly refreshed if r.status_code != 200: return build_response(request, 401, 'Invalid refresh token') response = r.json() except Exception as e: return build_response(request, 500, unicode(e)) return HttpResponse(json.dumps(response), status=200, mimetype='application/json; charset=utf-8')
def create(self, request): response = {} m_token = str(request.META.get('HTTP_AUTHORIZATION')) m_token = m_token.replace('Bearer ', '') body = json.loads(request.body) try: userId = body['userId'] appId = body['appId'] except Exception as e: return build_response(request, 400, 'Invalid request') token_store = tokenStore() keystone_client = KeystoneClient(KEYSTONE_USER, KEYSTONE_PWD, ADMIN_DOMAIN, KEYSTONE_PROTOCOL, KEYSTONE_HOST, KEYSTONE_PORT) try: token_info = keystone_client.get_token_info(m_token) user_id = keystone_client.get_user_by_email(userId) if not user_id: return build_response(request, 401, 'Invalid username') if token_info['id'] != user_id: return build_response( request, 401, 'username does not match authentication') try: r = token_store.get(body) if not len(r): response = {} # if r["appId"] == "test": # response = r else: response = { 'appId': r['appId'], 'userId': r['userId'], 'authToken': r['authToken'], 'refreshToken': r['refreshToken'], 'expire': r['expire'] } except Exception as e: return build_response(request, 500, unicode(e.message)) except Exception as e: return build_response(request, 500, unicode(e)) return HttpResponse(json.dumps(response), status=200, mimetype='application/json; charset=utf-8')
def delete(self, request, repository): if not request.user.is_staff: return build_response(request, 403, 'Forbidden') try: unregister_repository(repository) except Exception, e: if e.message == 'Not found': code = 404 else: code = 400 return build_response(request, code, e.message)
def create(self, request): try: task = json.loads(request.body) except: return build_response(request, 400, 'The provided data is not a valid JSON object') # Check the products to be renovated if 'name' not in task or 'id' not in task or 'priceType' not in task: return build_response(request, 400, 'Missing required field, must contain name, id and priceType fields') # Parse oid from product name parsed_name = task['name'].split('=') try: order = Order.objects.get(order_id=parsed_name[1]) except: return build_response(request, 404, 'The oid specified in the product name is not valid') # Get contract to renovate if isinstance(task['id'], int): task['id'] = unicode(task['id']) try: contract = order.get_product_contract(task['id']) except: return build_response(request, 404, 'The specified product id is not valid') # Refresh accounting information on_usage_refreshed(order, contract) # Build charging engine charging_engine = ChargingEngine(order) if task['priceType'].lower() not in ['recurring', 'usage']: return build_response(request, 400, 'Invalid priceType only recurring and usage types can be renovated') try: redirect_url = charging_engine.resolve_charging(type_=task['priceType'].lower(), related_contracts=[contract]) except ValueError as e: return build_response(request, 400, unicode(e)) except OrderingError as e: return build_response(request, 422, unicode(e)) except: return build_response(request, 500, 'An unexpected event prevented your payment to be created') response = build_response(request, 200, 'OK') # Include redirection header if needed if redirect_url is not None: response['X-Redirect-URL'] = redirect_url return response
class ServiceRecordCollection(Resource): def _get_datetime(self, time): try: time_stamp = datetime.strptime(time, '%Y-%m-%dT%H:%M:%S.%f') except: time_stamp = datetime.strptime(time, '%Y-%m-%d %H:%M:%S.%f') return time_stamp # This method is used to load SDR documents and # start the charging process @supported_request_mime_types(('application/json', )) @authentication_required def create(self, request, reference): try: # Extract SDR document from the HTTP request data = json.loads(request.raw_post_data) # Validate SDR structure if 'offering' not in data or 'customer' not in data or 'time_stamp' not in data \ or 'correlation_number' not in data or 'record_type' not in data or'unit' not in data \ or 'value' not in data or 'component_label' not in data: raise Exception('Invalid JSON content') # Get the purchase purchase = Purchase.objects.get(ref=reference) # Call the charging engine core with the SDR charging_engine = ChargingEngine(purchase) charging_engine.include_sdr(data) except Exception, e: return build_response(request, 400, e.message) # Return response return build_response(request, 200, 'OK')
def read(self, request): response = [] organizations = Organization.objects.all() if 'username' in request.GET: username = request.GET.get('username', '') try: user = User.objects.get(username=username) except User.DoesNotExist: return build_response(request, 404, 'The user is not registered in WStore.') organizations = Organization.objects.filter(managers=(user.pk,)) # Get organization info for org in organizations: try: org_element = get_organization_info(org) except: continue # Check if payment information is displayed if not request.user.is_staff and not request.user.pk in org.managers\ and 'payment_info' in org_element: del(org_element['payment_info']) elif request.user.pk in org.managers: org_element['is_manager'] = True # Include organizations response.append(org_element) return HttpResponse(json.dumps(response), status=200, mimetype='application/json')
def read(self, request, path, name): # Protect the resources from not authorized downloads if path.startswith('assets'): err_code, err_msg = self._validate_asset_permissions( request.user, path, name) elif path.startswith('bills'): err_code, err_msg = self._validate_invoice_permissions( request.user, name) else: err_code, err_msg = 404, 'Resource not found' local_path = os.path.join(path, name) if err_code is None and not os.path.isfile( os.path.join(settings.MEDIA_ROOT, local_path)): err_code, err_msg = 404, 'Resource not found' if err_code is not None: response = build_response(request, err_code, err_msg) elif not getattr(settings, 'USE_XSENDFILE', False): response = serve(request, local_path, document_root=settings.MEDIA_ROOT) else: response = HttpResponse() response['X-Sendfile'] = smart_str(local_path) return response
def create(self, request): task, order, contract, error_response = validate_product_job( self, request) if error_response is not None: return error_response # If the model is pay-per-use charge for pending payment redirect_url = None if task['priceType'].lower() == 'usage': # The update of the product status need to be postponed if there is a pending payment redirect_url, error_response = process_product_payment( self, request, task, order, contract) if error_response is not None: return error_response response = build_response(request, 200, 'OK') # Include redirection header if needed if redirect_url is not None: response['X-Redirect-URL'] = redirect_url else: # Suspend the product as no pending payment on_product_suspended(order, contract) contract.suspended = True order.save() client = InventoryClient() client.suspend_product(contract.product_id) return response
def read(self, request): try: response = json.dumps(get_marketplaces()) except: return build_response(request, 400, 'Invalid request') return HttpResponse(response, status=200, mimetype='application/JSON; charset=UTF-8')
def read(self, request): # Check user roles if not 'provider' in request.user.userprofile.get_current_roles(): return build_response(request, 403, 'Forbidden') # Make idm request from wstore.social_auth_backend import FIWARE_APPLICATIONS_URL url = FIWARE_APPLICATIONS_URL if request.user.userprofile.is_user_org(): actor_id = request.user.userprofile.actor_id else: actor_id = request.user.userprofile.current_organization.actor_id token = request.user.userprofile.access_token url += '?actor_id=' + str(actor_id) url += '&access_token=' + token req = MethodRequest('GET', url) # Call idm opener = urllib2.build_opener() resp = [] try: response = opener.open(req) # Make the response resp = response.read() except Exception, e: if e.code == 401: try: # Try to refresh the access token social = request.user.social_auth.filter(provider='fiware')[0] social.refresh_token() # Update credentials social = request.user.social_auth.filter(provider='fiware')[0] credentials = social.extra_data request.user.userprofile.access_token = credentials['access_token'] request.user.userprofile.refresh_token = credentials['refresh_token'] request.user.userprofile.save() # Try to connect again token = request.user.userprofile.access_token url += '?actor_id=' + str(actor_id) url += '&access_token=' + token req = MethodRequest('GET', url) response = opener.open(req) # Make the response resp = response.read() except: resp = json.dumps([]) else: resp = json.dumps([])
def create(self, request): # Check if the user is an admin if not request.user.is_staff: return build_response(request, 403, 'Forbidden') # Get data data = json.loads(request.raw_post_data) if not 'currency' in data: return build_response(request, 400, 'Invalid JSON content') # Check currency regex if not is_valid_id(data['currency']): return build_response(request, 400, 'Invalid currency format') # Get the context context = Context.objects.all()[0] # Check if the allowed_currencies list is empty first = False if not 'allowed' in context.allowed_currencies: first = True context.allowed_currencies['allowed'] = [] error = False # Check that the new currency is not already included for curr in context.allowed_currencies['allowed']: if curr['currency'].lower() == data['currency'].lower(): error = True break if error: return build_response(request, 400, 'The currency already exists') # Check if it is the default currency if ('default' in data and data['default']) or first: # Note the this will override previous default currency context.allowed_currencies['default'] = data['currency'] # Include new currency context.allowed_currencies['allowed'].append({ 'currency': data['currency'], 'in_use': False }) context.save() return build_response(request, 201, 'Created')
def read(self, request): try: response = json.dumps(get_repositories()) except: return build_response(request, 400, 'Invalid request') return HttpResponse(response, status=200, mimetype='application/JSON; charset=UTF-8')
def patch(self, request, username): if not request.user.is_staff and not request.user.username == username: return build_response( request, 403, 'You are not authorized to update user info') try: data = json.loads(request.body) except: return build_response(request, 400, 'Invalid JSON content') # Get user org for storing the billing address user_org = Organization.objects.get(name=username) if 'billingAddress' in data: # Check that the billing information is correct if 'street' in data['billingAddress']: user_org.tax_address['street'] = data['billingAddress'][ 'street'] if 'postal' in data['billingAddress']: user_org.tax_address['postal'] = data['billingAddress'][ 'postal'] if 'city' in data['billingAddress']: user_org.tax_address['city'] = data['billingAddress']['city'] if 'province' in data['billingAddress']: user_org.tax_address['province'] = data['billingAddress'][ 'province'] if 'country' in data['billingAddress']: user_org.tax_address['country'] = data['billingAddress'][ 'country'] if 'street' not in user_org.tax_address or 'postal' not in user_org.tax_address or\ 'city' not in user_org.tax_address or 'province' not in user_org.tax_address or\ 'country' not in user_org.tax_address: return build_response( request, 400, 'Incomplete billing address, there is a missing field') user_org.save() return build_response(request, 200, 'OK')
def read(self, request): # Check user roles if 'provider' not in request.user.userprofile.get_current_roles(): return build_response(request, 403, 'Forbidden') resp = get_applications(request.user) return HttpResponse(resp, status=200, mimetype='application/json;charset=UTF-8')
def create(self, request): """ Uploads a new downloadable digital asset :param request: :return: 201 Created, including the new URL of the asset in the location header """ user = request.user profile = user.userprofile content_type = get_content_type(request)[0] if 'provider' not in profile.get_current_roles() and not user.is_staff: return build_response(request, 403, "You don't have the seller role") asset_manager = AssetManager() try: if content_type == 'application/json': data = json.loads(request.body) resource = asset_manager.upload_asset(user, data) else: data = json.loads(request.POST['json']) f = request.FILES['file'] resource = asset_manager.upload_asset(user, data, file_=f) except ConflictError as e: return build_response(request, 409, unicode(e)) except Exception as e: return build_response(request, 400, unicode(e)) location = resource.get_url() # Fill location header with the URL of the uploaded digital asset response = HttpResponse(json.dumps({ 'content': location, 'contentType': data['contentType'], 'id': resource.pk, 'href': resource.get_uri() }), status=200, mimetype='application/json; charset=utf-8') response['Location'] = location return response
def read(self, request, product_id): """ Retrieves the assets from a product :param request: :param id: :return: """ try: asset_manager = AssetManager() response = asset_manager.get_product_assets(product_id) except PermissionDenied as e: return build_response(request, 403, unicode(e)) except: return build_response(request, 500, 'An unexpected error occurred') return HttpResponse(json.dumps(response), status=200, mimetype='application/json; charset=utf-8')