How to convert this curl example to google apps script / javascript? [duplicate] - rest

I have experience making CURL calls in GAS using headers and payload, but I have never done a CURL command using the -u option before. According to the API spec, I must use the -u option. I just don't know how to convert that to GAS. Here is my code so far:
function updateStatus()
{
//Build header.
var header =
{
'Content-Type': 'application/json', //Set content type to JSON.
};
//Put it all together.
var options =
{
'method' : 'get',
'headers' : header
};
//Make Login call to When I work.
var responseGetPlan = UrlFetchApp.fetch('my url', options);
var strResponseGetPlan = responseGetPlan.getContentText();
Logger.log('Get Plan Response: ' + strResponseGetPlan); //Log response.
var parsedData = JSON.parse(strResponseGetPlan); //Parse into JSON format.
var strId = parsedData.id;
Logger.log(strId);
}

curl -u uses Basic authentication, which is a simple base64 encoding of a concatenated "username:password" string. You would send the following as headers.
Authorization: 'Basic ' + Utilities.base64Encode('username:password')
References:
RFC7617
curl Basic Authentication
Utilities

Related

Google Storage REST get with axios

I want to get a list of images in a bucket using REST and axios.
ref: https://cloud.google.com/storage/docs/listing-objects#list-objects-json
The documentation gives this curl request
curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o"
reqConfig: this is a token I use in my REST firestore queries to authenticate the user. I'm using that same token for here. I'm guessing it's the problem but not sure how to fix it.
My result is consistently 404 for a bucket path that I know exists, using the URL from their docs. I should be getting a json list of the files in the bucket.
Error: Request failed with status code 404
Where am I going wrong?
export async function getCompanyStorage(context, apikey, companyId) {
const url = `https://storage.googleapis.com/storage/v1/b/uploads/${companyId}/o?key=${apikey}`;
const cookies = nookies.get(context);
const reqConfig = {
headers: new Headers({
Authorization: "Bearer " + cookies.token,
"Content-Type": "application/json",
}),
};
const result = axios
.get(url, { headers: { Authorization: `Bearer ${reqConfig}` } })
.then((res) => {
return res.data;
})
.catch((error) => {
console.error("error using axios", error);
});
}
Edit: a path to a bucket in the firebase console looks like this
gs://projectname.appspot.com/uploads/WhmDZyQdLVk7n0qR7aTg
I suggest reviewing the documentation you linked to. In particular:
OAUTH2_TOKEN is the access token you generated in Step 1.
BUCKET_NAME is the name of the bucket whose objects you want to list. For example, my-bucket.
You can use a prefix=PREFIX query string parameter to limit results to
objects that have the specified prefix.
Your URL does not contain the name of the bucket as required by the URL pattern. Use the unique name of the bucket where you see "BUCKET_NAME". It looks like, given your example, that it would be "projectname.appspot.com". BUCKET_NAME is not the path of the object within that bucket. If you want to list files under the "uploads" prefix, then you would use the prefix query string parameter to specify that, as documented in the last line of the quoted text.
You can use this function to create Get request with axios for Google Cloud Storage
export const UploadVideo = async (form_data, file, signedurl, asset_uuid) => {
let resultState = { state: '', data: {} };
console.log(signedurl)
/*
const xhr = new XMLHttpRequest();
xhr.open("PUT", signedurl);
xhr.setRequestHeader('Content-Type', "application/octet-stream");
xhr.send(file);
*/
let config = {
headers: {
'Content-Type': 'application/octet-stream',
},
};
await axios.get(signedurl, file, config).then(function (response) {
resultState.state = 'success';
}).catch(function (error) {
resultState.state = 'error';
resultState.data.message = error.message;
window.toastr.error(error.message);
console.log(error)
})
return resultState;
}

loopback access_token not found

followed by the access documentation
both are not working by using
Authorization Header
Query Parameter
Using the latest version of loopback 2.1.X.
I turned off the email verification and successfully got the AccessToken object from the initial login. The header and the query request are not working now.
ACCESS_TOKEN=6Nb2ti5QEXIoDBS5FQGWIz4poRFiBCMMYJbYXSGHWuulOuy0GTEuGx2VCEVvbpBK
Authorization Header
curl -X GET -H "Authorization: $ACCESS_TOKEN" \
http://localhost:3000/api/widgets
Query Parameter
curl -X GET http://localhost:3000/api/widgets?access_token=$ACCESS_TOKEN
In header pass key as authorization not ACCESS_TOKEN
In query params pass key as accessToken not access_token
Here is what works for me in Angular 2 :
initRequestOptions(accessToken:any) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Authorization', accessToken);
return new RequestOptions({headers: headers});
}
makeRequest(accessToken:any){
let options = this.initRequestOptions(accessToken);
this.http.get('http://' + apiUrl + '/api/MyModel, options)
.subscribe(
//...
)
}
So basically you need to create a headers object , add an 'Authorization' item whoes value is the access token , and use the headers object to create a RequestOptions object to be inserted in the request.
Also loopback explorer passes the access token as a url encoded parameter so this should work too :
http://localhost:3000/api/MyModel?access_token=X3Ovz4G1PfmPiNGgU5YgORPwPGLaVt9r8kU7f4tu1bDMyA4zbqiUEgeDAC3qkZLR

Trying to use 'Postman' and having trouble setting Basic access authentication Headers

I have an API endpoint that I am trying to test with the google app: 'Postman'. I need to set the headers which use 'Basic authentication'. I am not sure what should go in 'Header: Value'
This is how the admin said the headers should be set:
"The head value is the word 'Basic' followed by your org name and your Api key separated by a colon and base64 encoded."
I have tried numerous things but I am not getting it quite right. The error I get is "Message: Token not set".
Your header field should look like this:
Header : Authorization
Value : Basic base64('YourOrgName:YourAPIKEY');
You can get the base64 value of your string here:
https://www.base64encode.org/
For example, for my-org-name:123key4api it should be bXktb3JnLW5hbWU6MTIza2V5NGFwaQ==.
The complete header would look like:
Authorization: Basic bXktb3JnLW5hbWU6MTIza2V5NGFwaQ==
Looks like you are facing trouble in getting the base64 value. Well you can make use of in-built function in Javscript as below.
Simply run below code in any JS runtime, (Simplest would be - open console tab in chrome developer tool)
"username:password!" // Here I used basic Auth string format
// Encode the plain string to base64
btoa("username:password!"); // output: "dXNlcm5hbWU6cGFzc3dvcmQh"
// Decode the base64 to plain string
atob("dXNlcm5hbWU6cGFzc3dvcmQh"); // output: "username:password!"
It's 2019 and with Version 6.5.3 we have a separate tab to use different kind of Authentication techniques.
For basic auth you just have to give username and password after selecting "Basic Auth" under Authentication tab
Putting it all together in a pre-request script
(and then use the access_token for oauth).
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}};
var userPass = pm.environment.get("oauth_key") + ':' + pm.environment.get("oauth_secret")
pm.sendRequest({
url: pm.environment.get("basepath")+"/oauthpreview/token",
method: 'POST',
header: {
'Accept': 'application/json',
'cache-control':"no-cache",
'Authorization' : 'Basic ' + Base64.encode(userPass),
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: "grant_type", value: "client_credentials", disabled: false}
]
}
}, function (err, res) {
pm.environment.set("access_token", res.json().access_token);
})

Google Apps Script - create draft Gmail email message WITH embedded graphics

I want to create a draft Gmail email message using Google Apps Script, like in the following example taken from Mogsdad's accepted answer to the Create draft mail using Google apps script question:
function createDraft() {
var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope
var raw =
'Subject: testing Draft\n' +
//'To: test#test.com\n' +
'Content-Type: multipart/alternative; boundary=1234567890123456789012345678\n' +
'testing Draft msg\n' +
'--1234567890123456789012345678--\n';
var draftBody = Utilities.base64Encode(raw);
var params = {method:"post",
contentType: "application/json",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
payload:JSON.stringify({
"message": {
"raw": draftBody
}
})
};
var resp = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/me/drafts", params);
Logger.log(resp.getContentText());
It works great, BUT I want to embedd some image in the message body, without linking to external URL, so it always shows up, it's not blocked by some email clients, including Gmail. How to do that?

UrlFetchApp Authentication failed Freshbooks

So I am trying to communicate with the freshbooks api by making the sample request detailed on the developers page of freshbooks (http://developers.freshbooks.com/). We are doing token-based authentication as opposed to using OAuth.
I have my code logging the responses to my requests in a spreadsheet. The responses it has been logging are as follows:
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="http://www.freshbooks.com/api/" status="fail">
<error>Authentication failed.</error>
<code>20010</code>
</response>
I have been able to authenticate when using a curl command in console, but not when running the script. Below is the code I used. Left out the logging to spreadsheet part and our specific url and authToken:
// Sample function to call into an API using basic HTTP auth
function freshbooksTest () {
var url = ;
var authToken = ;
var unamepass =authToken+":X";
var digestfull = "Basic "+unamepass;
var payload = '<request method="system.current"></request>';
var options =
{
"method" : "post",
"muteHttpExceptions": true,
"headers" : {"Authorization": digestfull},
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
var xml = response.getContentText();
}
I have checked out threads where people are having similar problems, but the solutions were either not applicable to my situation, or have already been tried. Any suggestions are welcome.
Not specifically familiar with UrlFetchApp, but if it doesn't do it for you, you'll need to Base64 encode digestfull before you send it in the header.
Looks like you need to base 64 encode your auth token. Code should look like this:
function freshbooksTest () {
var url = ;
var authToken = ;
var unamepass = authToken+":X";
var digestfull = "Basic "+ Utilities.base64Encode(unamepass);
var payload = '<request method="system.current"></request>';
var options =
{
"method" : "post",
"muteHttpExceptions": true,
"headers" : {"Authorization": digestfull},
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
var xml = response.getContentText();
}