Google Apps Script - Failed to send a request - post

I need a help.
I have a Flask API running like this:
from flask import Flask
from flask import jsonify
app = Flask(__name__)
#app.route('/rules/<payload>', methods=['GET', 'POST'])
def add_none(payload):
return jsonify({'result': payload})
if __name__ == '__main__':
app.run(debug=False)
My Google code is trying to send a post request, but always I got an invalid request.
I ran the same request using Postman and I didn't get the error. I don't understand what's happening.
rulesArray = [{'column_a': 35.0, 'column_b': 100.0, 'column_c': 105.0}, {'column_a': 38.0, 'column_b': 50.0, 'column_c': 80.0}];
var payload = {'content': rulesArray};
var params = { method: "POST", payload: payload, muteHttpExceptions: true, contentType: "application/json" };
var URL = 'http://127.0.0.1:5000/rules';
var response = UrlFetchApp.fetch(URL, params);
Any ideas what I can do to fix this? Thanks.

Related

Getting Error: XMLHttpRequest error when using dart

I have tried POST request from dart code to django rest api on local machine.
the API works when I do POST from Postman but fails when using dart.
Can someone please explain why !
my dart code :
void post_call() async {
var headers = {
'Content-Type': 'application/json',
};
var data = {"_selectedValue":"yes","_DescriptionValue":"yes","_namefieldValue":"yes","_contactValue":"yes","_emailValue" : "yes"};
var url = Uri.parse('http://127.0.0.1:8000/first_app/forms/');
var res = await http.post(url, headers: headers, body: json.encode(data));
if (res.statusCode != 200) throw Exception('http.post error: statusCode= ${res.statusCode}');
print(res);
}
the API works when I do POST from Postman but fails when using dart.

Hubspot client library file upload returning 400 Bad Request

I'm using hubspot client library in nodejs. https://github.com/HubSpot/hubspot-api-nodejs
Below is my code
import FormData from "form-data";
import fs from "fs";
import os from "os";
import uniqueFilename from "unique-filename";
const requestBody = req.body; //Binary data from postman post request
const path = uniqueFilename(os.tmpdir(), 'test.png');
fs.writeFileSync(path, requestBody);
const formData = new FormData();
const options = {
access: "PUBLIC_NOT_INDEXABLE",
overwrite: false,
duplicateValidationStrategy: "NONE",
duplicateValidationScope: "EXACT_FOLDER"
};
formData.append("folderId", 'folder id');
formData.append("options", JSON.stringify(options));
formData.append("file", fs.createReadStream(path));
const fileUploadReq = await hubspotClient.client.apiRequest({
method: 'POST',
path: '/filemanager/api/v3/files/upload',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
});
Seems all api working file except file upload. it is returning 400 Bad request error.
same formData i've tried with axios post request it is working.
Am i missing something or it something wrong with hubspot client library?

How to send recaptcha token in POST request (python)

I'm trying to login to my leetcode account via a POST request (for a project). This is what I have so far:
import requests
import os
login\_url = "https://leetcode.com/accounts/login/"
s = requests.Session()
res = s.get('https://leetcode.com/accounts/login/')
cookies = dict(res.cookies)
csrftoken = cookies\['csrftoken'\]
headers = {'Referer': url}
data = {
'csrfmiddlewaretoken': csrftoken,
'login': os.environ\['LEETCODE\_USERNAME'\],
'password': os.environ\['LEETCODE\_PASSWORD'\],
'next': '/problems/two-sum/',
'recaptcha\_token': (token from screenshot)
}
x = requests.post(login\_url, data=data, headers=headers, cookies=cookies)
print(x.text)
This screenshot shows the payload:
link
I tried to copy+paste that recaptcha_token in my data dictionary but I'm still getting this error:
{"recaptcha": {"error_type": "recaptcha_token_invalid", "error": "Something went wrong with reCAPTCHA."}}

Apache Superset and Auth0 returns "The browser (or proxy) sent a request that this server could not understand."

I'm trying to set up Superset with Auth0. I've found somewhat similar issues here and here.
I've set up the following configuration based on the first link above and trying to follow the Superset and Flask-AppBuilder docs:
from flask_appbuilder.security.manager import (
AUTH_OAUTH,
)
from superset.security import SupersetSecurityManager
import json
import logging
import string
import random
nonce = ''.join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase, k = 30))
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
AUTH_TYPE = AUTH_OAUTH
AUTH_USER_REGISTRATION = True
AUTH_USER_REGISTRATION_ROLE = "Admin"
AUTH0_URL = os.getenv('AUTH0_URL')
AUTH0_CLIENT_KEY = os.getenv('AUTH0_CLIENT_KEY')
AUTH0_CLIENT_SECRET = os.getenv('AUTH0_CLIENT_SECRET')
OAUTH_PROVIDERS = [
{ 'name':'auth0',
'token_key':'access_token',
'icon':'fa-at',
'remote_app': {
'api_base_url': AUTH0_URL,
'client_id': AUTH0_CLIENT_KEY,
'client_secret': AUTH0_CLIENT_SECRET,
'server_metadata_url': AUTH0_URL + '/.well-known/openid-configuration',
'client_kwargs': {
'scope': 'openid profile email'
},
'response_type': 'code token',
'nonce': nonce,
}
}
]
class CustomSsoSecurityManager(SupersetSecurityManager):
def oauth_user_info(self, provider, response=None):
logger.debug('oauth2 provider: {0}'.format(provider))
if provider == 'auth0':
res = self.appbuilder.sm.oauth_remotes[provider].get(AUTH0_URL + '/userinfo')
logger.debug('response: {0}'.format(res))
if res.raw.status != 200:
logger.error('Failed to obtain user info: %s', res.json())
return
# user_info = self.appbuilder.sm.oauth_remotes[provider].parse_id_token(res)
# logger.debug('user_info: {0}'.format(user_info))
me = res.json()
return {
'username' : me['email'],
'name' : me['name'],
'email' : me['email'],
}
CUSTOM_SECURITY_MANAGER = CustomSsoSecurityManager
The full error log message is:
2022-03-18 18:53:56,854:ERROR:flask_appbuilder.security.views:Error authorizing OAuth access token: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
NOTES:
I can see an access_token parameter in the redirect url, so it seems to be working with Auth0 correctly.
I don't see any of the debug lines in the CustomSsoSecurityManager being written, so my guess is that I have not correctly set that up (or my logging is not correctly configured).
I've tried using both Regular Web Application and Single Page Application application types in Auth0, and both fail in the same way.
I would appreciate any help in understanding what I might be missing or what else I need to do to configure Auth0 to work with Superset.
I was able to make it work using the JSON Web Key Set endpoint provided by Auth0, look at this example and adapt it accordingly:
from jose import jwt
from requests import request
from superset.security import SupersetSecurityManager
class CustomSecurityManager(SupersetSecurityManager):
def request(self, url, method="GET", *args, **kwargs):
kwargs.setdefault("headers", {})
response = request(method, url, *args, **kwargs)
response.raise_for_status()
return response
def get_jwks(self, url, *args, **kwargs):
return self.request(url, *args, **kwargs).json()
def get_oauth_user_info(self, provider, response=None):
if provider == "auth0":
id_token = response["id_token"]
metadata = self.appbuilder.sm.oauth_remotes[provider].server_metadata
jwks = self.get_jwks(metadata["jwks_uri"])
audience = self.appbuilder.sm.oauth_remotes[provider].client_id
payload = jwt.decode(
id_token,
jwks,
algorithms=["RS256"],
audience=audience,
issuer=metadata["issuer"],
)
first_name, last_name = payload["name"].split(" ", 1)
return {
"email": payload["email"],
"username": payload["email"],
"first_name": first_name,
"last_name": last_name,
}
return super().get_oauth_user_info(provider, response)

Send post request in aqueduct dart

I have created a post request in aqueduct dart and it takes json as body parameter, and I need to send that request body to thirdparty api , upon getting response from third party api I need to return that response to user. I have updated the code and printed the response header and it says http 400 (bad request)
here is the code :
#override
Controller get entryPoint {
String dataRecieved;
var completer = new Completer();
var contents = new StringBuffer();
final router = Router();
// Prefer to use `link` instead of `linkFunction`.
// See: https://aqueduct.io/docs/http/request_controller/
router.route("/uploadurl").linkFunction((request) async {
final req = await request.body.decode();
// print( await request.body.decode());
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
var auth = 'Bearer ' +
'eyJ...';
await client
.postUrl(Uri.parse(
'https://<removed>/api/datalake/v3/generateDownloadObjectUrls'))
.then((HttpClientRequest requestSend) {
requestSend.headers
.add("Content-Type", "application/json; charset=UTF-8");
requestSend.headers.add("Authorization", auth);
// requestSend.headers.contentLength = request.body.length;
print(req);
requestSend.write(req);
return requestSend.close();
}).then((HttpClientResponse response) async {
print(await response.contentLength);
var resStream = response.transform(Utf8Decoder());
await for (var data in resStream) {
print('Received data: $data');
}
print(await response.statusCode);
}).catchError((e) {
print("Request error: $e"); // The only case
});
print(contents);
return Response.ok({"key": dataRecieved});
});
return router;
}
when I make a request from the postman , I get
{
"key": null
}
I think I am not able to send the correct request to third party API , because when I tested third party API from the postman, it was sending correct response
My pubspec.yaml file is :
name: proxydl
description: An empty Aqueduct application.
version: 0.0.1
author: stable|kernel <jobs#stablekernel.com>
environment:
sdk: ">=2.0.0 <3.0.0"
dependencies:
aqueduct: ^3.0.0
http: ^0.12.0+2
dev_dependencies:
test: ^1.0.0
aqueduct_test: ^1.0.0
This is what I am sending from postman as post request:
{
"paths": [
{
"path": "/f1/f2.log"
}
]
}
This is my first POC with Dart on the server side.
Upon further investigation I found the answer:
final req = await request.body.decode();
var envalue = json.encode(req);
For now, this worked, but I feel there might be a better answer for this

Resources