def post(self): if request.json is None or not request.json: return error_response("Request must be application/json"), 400 schema = WebhookSchema() load = schema.load(request.json) if load.errors: return load.errors, 400 user = self.user_manager.get_user_from_request(request) if user is None: return error_response("Couldn't authenticate user from token"), 401 if load.data is None or "id" not in load.data: return error_response("Error grabbing repository for user"), 400 # TODO: Add webhook user validation back in, this will require allowing users to join organizations #if user.id != load.data.get("id"): # return error_response("Repository not owned by requester"), 403 dock_url = "".join( [settings.JOB_URL, "/repo", load.data.get("id"), "/job"]) response = self.manager.create_webhook(owner=user, repo=load.data.get("name"), url=dock_url) print(response) print(response.json()) return {}, 400
def get_order(order_id): data, error = models.Order(order_id).get() if not error: if data['orderStatus'] == "https://schema.org/OrderPaymentDue" and utils.is_date_in_past( utils.from_datestring(data['paymentDueDate'])): return utils.error_response('anonymous_lease_expired') else: return utils.json_response(data) else: return utils.error_response(error)
def login_account(request): account_json = json.loads(request.body) user = authenticate(username=account_json['email'], password=account_json['password']) if user is not None: if user.is_active: login(request, user) print user, "logged in." return utils.success_response() else: return utils.error_response("Your account has been disabled. Check your email for details") else: return utils.error_response("Your account does not exist!")
def get_prediction_after_date_and_actual_data(ticker, pred_date): global ticker_to_transaction_index global transaction_data global chengdu80_model if ticker not in ticker_to_transaction_index: return utils.error_response('no such ticker') idx = ticker_to_transaction_index[ticker] data = transaction_data.values[idx] dates = data[:, 0] # 计算出dataset from DATA import get_transaction_data X = get_transaction_data(data, look_back) # 找look_back个数据 i = 0 while i < len(dates) and dates[i] < pred_date.replace('-', '/'): i += 1 predX = X[i - min(i, look_back):i] predy = data[i - min(i, look_back):i, -3] y_scaler = MinMaxScaler(feature_range=(0, 1)) y_scaler.fit(np.array([predy]).reshape([7, 1])) y = chengdu80_model.predict(predX) # 反归一化之后的预测数据 y = y_scaler.inverse_transform(y)[0] y = ((int)(y * 1000)) / 1000 numpy_array = data[i - min(i, look_back):i] line = get_prediction(numpy_array, y, pred_date) return line.dump_options_with_quotes()
def post_survey(request): #TODO: Handle image upload of user profile picture post_obj = json.loads(request.body) class_year, major, min_price, max_price, gender, smoking, birthday, cleanliness, location = None, None, None, None, None, None, None, None, None user = request.user user_picture = None #TODO: change this if 'class_year' in post_obj: class_year = post_obj['class_year'] if 'major' in post_obj: major = post_obj['major'] if 'min_price' in post_obj: min_price = post_obj['min_price'] if 'max_price' in post_obj: max_price = post_obj['max_price'] if 'gender' in post_obj: gender = post_obj['gender'] if 'smoking' in post_obj: smoking = post_obj['smoking'] if 'birthday' in post_obj: birthday = post_obj['birthday'] if 'cleanliness' in post_obj: cleanliness = post_obj['cleanliness'] if 'location' in post_obj: location = post_obj['location'] errors = check_post_survey_errors(user, class_year, major, min_price, max_price, gender, smoking, birthday, cleanliness, location) if len(errors) != 0: return utils.error_response(errors) models.SurveyInfo.objects.filter(user=user).delete() survey_data = models.SurveyInfo(user=user, user_picture=user_picture, class_year=class_year, major=major, min_price=min_price, max_price=max_price, gender=gender, smoking=smoking, birthday=birthday, cleanliness=cleanliness, location=location) survey_data.save() return utils.success_response()
def test_no_user_raises_exception(self): with requests_mock.Mocker() as mock: mock.get('/api/users/1', status_code=404, json=utils.error_response('User', 1)) with pytest.raises(BenwaOnlineError): show_user(user_id=1)
def get_event(event_id): utils.clean_expired_leases(event_id) data, error = models.Event(event_id).get() if not error: return utils.json_response(data) else: return utils.error_response(error)
def test_no_user(self, client): with requests_mock.Mocker() as mock: mock.get('/api/users/1', status_code=404, json=utils.error_response('User', 1)) response = client.get(url_for('userinfo.show_user', user_id=1)) assert response.status_code == 200
def vote(): flask.request.environ['CONTENT_TYPE'] = 'application/json' try: if flask.request.method == 'POST': # Save vote in database # Parse request first requestStr = flask.request.data panchromious.app.logger.info('Received request: %s', requestStr) voteObj = flask.json.loads(requestStr) panchromious.app.logger.info('Decoded request: %s', voteObj) colorRed = voteObj['color']['red'] colorGreen = voteObj['color']['green'] colorBlue = voteObj['color']['blue'] name = voteObj['value'] # Verify that R,G,B components are in valid range if not utils.are_valid_rgb_values([colorRed, colorGreen, colorBlue]) or not name: panchromious.app.logger.error('Incorrect request: color: [%d, %d, %d], name: %s', colorRed, colorGreen, colorBlue, name) return utils.error_response('Incorrect request') else: model.save_vote(colorRed, colorGreen, colorBlue, name) return utils.generate_response(201, utils.generate_vote()) else: # GET # Generate new vote return utils.generate_response(200, utils.generate_vote()) except: panchromious.app.logger.info('Error: %s', sys.exc_info()[2]) return utils.generate_response(500, {'status': 'error'})
def remove_user(self, body, is_admin=False): """Remove a user or admin.""" fingerprint = None sig_path = write_sig_to_file(body["signature"]) try: fingerprint = self.cert_processor.admin_verify( body["fingerprint"].encode("UTF-8"), sig_path) logger.info("Admin {adminfp} adding user {userfp}".format( adminfp=fingerprint, userfp=body["fingerprint"])) except (CertProcessorInvalidSignatureError, CertProcessorUntrustedSignatureError): os.remove(sig_path) logger.error( "Invalid signature on adding fingerprint: {fp}".format( fp=body["fingerprint"])) return error_response("Unauthorized", 403) # Remove signature file os.remove(sig_path) if is_admin: # Add a user to the admin trust store self.cert_processor.admin_gpg.delete_keys(body["fingerprint"]) # Add the user to the user trust store self.cert_processor.user_gpg.delete_keys(body["fingerprint"]) return json.dumps({"msg": "success"}), 201
def get_transactions_of_ticker(ticker): """ 返回某个股票的全年数据,用于前端绘制图形 :param ticker: :return: """ global transaction_data global ticker_to_transaction_index if ticker not in ticker_to_transaction_index: return utils.error_response('no such ticker') idx = ticker_to_transaction_index[ticker] data = transaction_data.values[idx] date, list1, list2 = data[:, 0], data[:, 3:5], data[:, 5:7] list0 = np.concatenate([list2, list1], axis=1) kline = (Kline().add_xaxis(date.tolist()).add_yaxis( "k line chart", list0.tolist()).set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), datazoom_opts=[opts.DataZoomOpts()], title_opts=opts.TitleOpts(title=""), )) return kline.dump_options_with_quotes()
def revoke_cert(self, body): """ A user should be able to revoke their own certificate. An admin should be able to revoke the certificate of any user. Args: body: A dictionary from the JSON input. Returns: (json, int): a tuple of the json response and http status code. """ is_admin = False fingerprint = None sig_path = write_sig_to_file(body["signature"]) try: fingerprint = self.cert_processor.admin_verify( json.dumps(body["query"]).encode("UTF-8"), sig_path) is_admin = True logger.info( "Admin {adminfp} revoking certificate with query {query}". format(adminfp=fingerprint, query=json.dumps(body["query"]))) os.remove(sig_path) except (CertProcessorInvalidSignatureError, CertProcessorUntrustedSignatureError): try: fingerprint = self.cert_processor.verify( json.dumps(body["query"]).encode("UTF-8"), sig_path) logger.info( "User {userfp} revoking certificate with query {query}". format(userfp=fingerprint, query=json.dumps(body["query"]))) os.remove(sig_path) except ( CertProcessorInvalidSignatureError, CertProcessorUntrustedSignatureError, ): os.remove(sig_path) return error_response("Unauthorized", 403) certs = self.cert_processor.storage.get_cert(**body["query"]) if certs is None: return error_response("No Cert to revoke") for cert in certs: cert = x509.load_pem_x509_certificate(str(cert).encode("UTF-8"), backend=default_backend()) self.cert_processor.revoke_cert(cert.serial_number) return json.dumps({"msg": "success"}), 200
def very_important_page(ticker): global company_info # TODO 对接数据格式 if ticker not in company_info: return utils.error_response('no such company') return render_template('block_show.html', company=company_info[ticker], ticker=ticker)
def delete_testing_accounts(request): try: testing_users = User.objects.filter(email=TESTING_EMAIL) for u in testing_users: u.delete() return utils.success_response() except Exception, e: return utils.error_response(e)
def test_show_likes_no_user(client): # test no tags? with requests_mock.Mocker() as mock: mock.get('/api/users/1/likes', status_code=404, json=utils.error_response('User', 1)) response = client.get(url_for('userinfo.show_likes', user_id=1)) assert response.status_code == 200
def make_housing_post(request): # try: housing_json = json.loads(request.body) errors = check_errors_post_housing(request.user, housing_json) if len(errors) != 0: return utils.error_response(errors) #TODO: Handle image uploads in post #TODO: format address info with Google Maps API line1 = housing_json['line1'] line2 = housing_json['line2'] city = housing_json['city'] zip_code = housing_json['zip_code'] property_name = housing_json['property_name'] longitude = 0.0 latitude = 0.0 address_dict = googleParse(line1 + ' ' + line2 + ' ' + city + ' ' + zip_code) if address_dict['status'] == -1: return utils.error_response(["Address could not be parsed"]) line1, line2, city, zip_code = address_dict['line1'], address_dict['line2'], address_dict['city'], address_dict['zipcode'] longitude, latitude = address_dict['longitude'], address_dict['latitude'] if models.Address.objects.filter(line_address1=line1).filter(zip_code=zip_code).filter(is_building=True).count() == 0: building = create_building(line1, line2, city, zip_code, property_name, longitude, latitude) else: building = models.Address.objects.filter(zip_code=zip_code).filter(is_building=True).get(line_address1=line1).building address = models.Address(is_building=False, line_address1=line1, line_address2=line2, city=city, zip_code=zip_code) address.save() housing_post = models.HousingPost( user = request.user, #TODO Figure out how to test with cookies title=housing_json['title'], description=housing_json['description'], price = housing_json['price'], num_people=housing_json['num_people'], bedrooms=housing_json['bedrooms'], bathrooms=housing_json['bathrooms'], address=address, building=building, last_updated=datetime.datetime.now(), start_date=housing_json['start_date'], end_date=housing_json['end_date']) housing_post.save() return utils.success_response({'postId' : housing_post.id})
def make_account(request): account_json = json.loads(request.body) if is_account(account_json): try: user = User.objects.get(email=account_json['email']) return utils.error_response('Account with email: ' + account_json['email'] + ' already exists.') except User.DoesNotExist, e: errors = check_errors_account(account_json) if len(errors) == 0: user = create_user(account_json) user.save() logged_in_user = authenticate(username=account_json['email'], password=account_json['password']) print logged_in_user login(request, logged_in_user) return utils.success_response() else: return utils.error_response(errors) except Exception, e: return utils.error_response(e)
def get_color(red, green, blue): flask.request.environ['CONTENT_TYPE'] = 'application/json' try: if not utils.are_valid_rgb_values([red, green, blue]): panchromious.app.logger.error('Incorrect color values: [%d, %d, %d]', red, green, blue) return utils.error_response('Color values should be in <0;255>') else: # Response panchromious.app.logger.error((red, green, blue)) return utils.generate_response(200, model.get_color(red, green, blue)) except: panchromious.app.logger.info('Error: %s', sys.exc_info()[2]) return utils.generate_response(500, {'status': 'error'})
def handle_error(e): """ A catch-all error handler that catches any unhandled exception and returns an error message to the end user. """ if isinstance(e, AuthError) or isinstance(e, InvalidUsage): response = jsonify(e.to_dict()) response.status_code = e.code else: LOGGER.error('Internal Error: {}'.format(traceback.format_exc())) response = jsonify(error_response('Internal Error', 'internal_error', 500)) response.status_code = 500 return response
def add_user(self, body, is_admin=False): """Add a user or admin.""" fingerprint = None sig_path = write_sig_to_file(body["signature"]) try: fingerprint = self.cert_processor.admin_verify( body["fingerprint"].encode("UTF-8"), sig_path) except (CertProcessorInvalidSignatureError, CertProcessorUntrustedSignatureError): os.remove(sig_path) logger.error( "Invalid signature on adding fingerprint: {fp}".format( fp=body["fingerprint"])) return error_response("Unauthorized", 403) # Remove signature file os.remove(sig_path) fingerprint = body["fingerprint"] try: if is_admin: has_user = self.has_user(self.cert_processor.admin_gpg, fingerprint) if not has_user: logger.info( "Admin {adminfp} adding admin user {userfp}".format( adminfp=fingerprint, userfp=body["fingerprint"])) # Add a user to the admin trust store self.add_and_trust_user(self.cert_processor.admin_gpg, fingerprint) has_user = self.has_user(self.cert_processor.user_gpg, fingerprint) if not has_user: # Add the user to the user trust store logger.info( "Admin {adminfp} adding admin user {userfp}".format( adminfp=fingerprint, userfp=body["fingerprint"])) self.add_and_trust_user(self.cert_processor.user_gpg, fingerprint) return json.dumps({"msg": "success"}), 201 except GPGKeyNotFoundException: return ( json.dumps( {"msg": "Key not found on keyserver. Could not import"}), 422, )
def fetch_bill(): try: if not request.json or not 'mobileNumber' in request.json: error_response("invalid-api-parameters", 402) mobile_number = request.json['mobileNumber'] row = Customer.query.filter_by(mobile_number=mobile_number).first() if row: return jsonify({"status": "SUCCESS", "data": row.serialize()}), 201 else: error_response("customer-not-found", 406) except Exception as err: error_response("unhandled-error", 408)
def update_order(order_id): order_data, error = models.Order(order_id).get() if error: return utils.error_response(error) else: event_id = utils.get_identifier( order_data['orderedItem'][0]['orderedItem']['id']) params = ['payments', 'orderedItem'] variables, erroring_params, error = utils.request_variables(params) if params == erroring_params: return utils.error_response('insufficient_information') if [param for param in variables] == params: return utils.error_response('too_much_information') if 'payments' in variables and variables['payments'] is not None: # PAYMENT FLOW if utils.is_date_in_past( utils.from_datestring(order_data['paymentDueDate'])): # LEASE HAS EXPIRED # TODO delete the expired lease and release the places #utils.clean_expired_leases(event_id) return utils.error_response("anonymous_lease_expired") if variables['payments'][0]['totalPaidToProvider'][ 'value'] != order_data['partOfInvoice']['totalPaymentDue'][ 'value']: return utils.error_response("payment_amount_incorrect") if variables['payments'][0]['totalPaidToProvider'][ 'currency'] != order_data['partOfInvoice'][ 'totalPaymentDue']['currency']: return utils.error_response("currency_incorrect") if order_data[ 'orderStatus'] != "https://schema.org/OrderPaymentDue": return utils.error_response("order_cannot_be_completed") order_data['payments'] = variables['payments'] order_data['orderStatus'] = 'https://schema.org/OrderDelivered' order_data['potentialAction'] = [{ "type": "CancelAction", "name": "Cancel", "target": { "type": "EntryPoint", "urlTemplate": "https://example.com/orders/{order_id}", "encodingType": "application/vnd.openactive.v1.0+json", "httpMethod": "PATCH" } }] order_data['orderedItem'][0][ 'orderItemStatus'] = 'https://schema.org/OrderDelivered' order_data['partOfInvoice'][ 'paymentStatus'] = 'https://schema.org/PaymentComplete' order_data['payments'][0]['confirmationNumber'] = 'C' + str( random.randint(0, 100000)) order = models.Order(order_id) order.update(order_data) event_data, error = models.Event(event_id).get() # Remove used lease from Event order_summary = event_data['orderLeases'][str(order_id)] del event_data['orderLeases'][str(order_id)] del order_summary['leaseExpiresAt'] # Add completed order to event order_summary['orderCompletedAt'] = datetime.now().strftime( "%Y-%m-%dT%H:%M:%SZ") event_data['completedOrders'][str(order_id)] = order_summary event = models.Event(event_id) event.update(event_data) return utils.json_response(order.as_json_ld()) else: # CANCELLATION FLOW offer_id = utils.get_identifier( order_data['acceptedOffer'][0]['id']) offer_data, error = models.Offer(offer_id).get() if order_data['orderStatus'] != "https://schema.org/OrderDelivered": return utils.error_response("order_cannot_be_cancelled") if offer_data['isCancellable'] == False: return utils.error_response("order_is_uncancellable") if offer_data['isCancellable'] == True and utils.is_date_in_past( utils.from_datestring( offer_data['cancellationValidUntil'])): return utils.error_response( "order_cancellation_window_expired") order_data['orderedItem'][0][ 'orderItemStatus'] = 'https://schema.org/OrderCancelled' order_data['orderStatus'] = 'https://schema.org/OrderCancelled' order = models.Order(order_id) order.update(order_data) quantity_of_order = int( order_data['orderedItem'][0]['orderQuantity']) event_data, error = models.Event(event_id).get() event_data['remainingAttendeeCapacity'] = event_data[ 'remainingAttendeeCapacity'] + quantity_of_order del event_data['completedOrders'][str(order_id)] event = models.Event(event_id) event.update(event_data) return utils.json_response(order.as_json_ld())
def logout_api(request): try: logout(request) return views.home(request) except Exception, e: return utils.error_response(e)
def feed_error(): return utils.error_response("method_not_allowed")
def create_order_error(): return utils.error_response("method_not_allowed")
def order_error(order_id): return utils.error_response("method_not_allowed")
except User.DoesNotExist, e: errors = check_errors_account(account_json) if len(errors) == 0: user = create_user(account_json) user.save() logged_in_user = authenticate(username=account_json['email'], password=account_json['password']) print logged_in_user login(request, logged_in_user) return utils.success_response() else: return utils.error_response(errors) except Exception, e: return utils.error_response(e) else: return utils.error_response('Ill Formed JSON: Missing one or more keys') def create_user(account_json): user = User.objects.create_user( account_json['email'], account_json['email'], account_json['password']) user.first_name = account_json['first_name'] user.last_name = account_json['last_name'] return user def is_account(account_json): return ( ('email' in account_json) and ('password' in account_json) and ('first_name' in account_json) and ('last_name' in account_json) ) def check_errors_account(account_json): errors = [] if len(account_json['email']) > 256:
def fallback(u_path): error_response("path-not-found", 404)
def create_cert(self, body): """Create a certificate.""" lifetime = int(body["lifetime"]) min_lifetime = int(self.config.get("mtls", "min_lifetime", fallback=60)) max_lifetime = int(self.config.get("mtls", "max_lifetime", fallback=0)) if lifetime < min_lifetime: logger.info( "User requested lifetime less than minimum. {} < {}".format( lifetime, min_lifetime)) error_response("lifetime must be greater than {} seconds".format( min_lifetime)) if max_lifetime != 0: if lifetime > max_lifetime: logger.info( "User requested lifetime greater than maximum. {} < {}". format(lifetime, max_lifetime)) error_response("lifetime must be less than {} seconds".format( max_lifetime)) csr_str = body["csr"] csr = self.cert_processor.get_csr(csr_str) if csr is None: return error_response("Could not load CSR") try: csr_public_bytes = csr.public_bytes(serialization.Encoding.PEM) sig_path = write_sig_to_file(body["signature"]) fingerprint = self.cert_processor.verify(csr_public_bytes, sig_path) os.remove(sig_path) except CertProcessorUntrustedSignatureError as e: logger.info("Unauthorized: {}".format(e)) return error_response("Unauthorized", 403) except CertProcessorInvalidSignatureError: logger.info("Invalid signature in CSR.") return error_response("Invalid signature", 401) if csr is None: logger.info("Invalid CSR.") return error_response("Invalid CSR") cert = None try: cert = self.cert_processor.generate_cert(csr, lifetime, fingerprint) return json.dumps({"cert": cert.decode("UTF-8")}), 200 except CertProcessorKeyNotFoundError: logger.critical("Key missing. Service not properly initialized") return error_response("Internal Error") except CertProcessorMismatchedPublicKeyError: logger.error("CSR Public Key does not match found certificate.") return error_response("Internal Error") except CertProcessorNotAdminUserError: logger.error( "User {} is not an admin and attempted ".format(fingerprint) + "to generate a certificate they are not allowed to generate.") return error_response("Invalid Request", 403) except CertProcessorNoPGPKeyFoundError: logger.info("PGP Key not found.") return error_response("Unauthorized", 401)
def default(path): return utils.error_response("not_found")
def get_offer(offer_id): data, error = models.Offer(offer_id).get() if not error: return utils.json_response(data) else: return utils.error_response(error)
def index(): return utils.error_response('nothing_to_see_here')
def create_order(): params = ['orderedItem', 'acceptedOffer', 'customer', 'broker'] variables, erroring_params, error = utils.request_variables(params) if error: if not variables['orderedItem']: return utils.error_response("incomplete_event_details") if not variables['acceptedOffer']: return utils.error_response("incomplete_offer_details") if not variables['customer']: return utils.error_response("incomplete_customer_details") if not variables['acceptedOffer']: return utils.error_response("incomplete_broker_details") else: event_id = utils.get_identifier( variables['orderedItem'][0]['orderedItem']['id']) offer_id = utils.get_identifier(variables['acceptedOffer'][0]['id']) utils.clean_expired_leases(event_id) event_data, event_error = models.Event(event_id).get() offer_data, offer_error = models.Offer(offer_id).get() if not event_error and not offer_error: quantity_of_order = int( variables['orderedItem'][0]['orderQuantity']) if utils.get_identifier( offer_data['itemOffered']['id']) != utils.get_identifier( event_data['id']): #EVENT DOES NOT MATCH OFFER return utils.error_response("offer_not_valid") if event_data['remainingAttendeeCapacity'] == 0: #EVENT IS FULL return utils.error_response("event_is_full") if event_data['remainingAttendeeCapacity'] < quantity_of_order: #EVENT HAS INSUFFICIENT SPACES return utils.error_response("event_has_insufficient_spaces") if utils.is_date_in_past( utils.from_datestring(event_data['startDate'])): # EVENT IS IN THE PAST return utils.error_response("unavailable_event") if utils.is_date_in_past( utils.from_datestring(offer_data['validThrough'])): # OFFER VALID THROUGH IS IN THE PAST return utils.error_response("offer_expired") if not utils.is_date_in_past( utils.from_datestring(offer_data['validFrom'])): # OFFER VALID FROM IS NOT YET IN THE PAST return utils.error_response("offer_not_yet_valid") order = models.Order() variables['orderDate'] = datetime.now() variables['paymentDueDate'] = utils.add_time( datetime.now(), 15, 'M') value_of_order = offer_data['price'] * quantity_of_order currency_of_offer = offer_data['priceCurrency'] variables['partOfInvoice'] = { "type": "Invoice", "paymentStatus": "https://schema.org/PaymentDue", "totalPaymentDue": { "type": "MonetaryAmount", "value": value_of_order, "currency": currency_of_offer } } order.create(variables) order_data, errors = order.get() order_id = order_data['identifier'] order_summary = { 'leaseExpiresAt': order_data['paymentDueDate'], 'places': quantity_of_order } event_data['remainingAttendeeCapacity'] = event_data[ 'remainingAttendeeCapacity'] - quantity_of_order event_data['orderLeases'][str(order_id)] = order_summary event = models.Event(event_id) event.update(event_data) return utils.json_response( order.as_json_ld(), created=True, created_key=order.as_json_ld()['id'].replace('$HOST$', '')) else: if event_error == 'resource_not_found': # EVENT NOT FOUND return utils.error_response("unavailable_event") if offer_error == 'resource_not_found': # OFFER NOT FOUND return utils.error_response("unavailable_offer")
def get_company_info(ticker): global company_info #TODO 对接数据格式 if ticker not in company_info: return utils.error_response('no such company') return company_info[ticker]