How to get a response key into the URL, Google Apps Script - url

I need to get the permission to access to specific URL, but before that I need to get the responseKey, and the way to get the responseKey is to access to this URL in the browser: https://api.getgo.com/oauth/v2/authorize?client_id={consumerKey}&response_type=code. After accessing
it contains the responseKey what I need. It will look something like: http://example.com/oauthreturn/?code={responseKey}. The question is how I can get the responseKey in code in google-apps-scrpits.
This what i wrote:
function myFunction() {
var client_id='xxxxxxxxxxxxxxxxx'
var url ="https://api.getgo.com/oauth/v2/authorize?client_id="+client_id+"&response_type=code";
var resp = UrlFetchApp.fetch(url)
}
but I get a HTML code response

In your code var resp = UrlFetchApp.fetch(url) will create a HTTPResponse object. First, you will want to know if the response code is 200 OK. To gather that information you should use getResponseCode() and check if it equals to 200. If that is the case, then you must parse the code. To do that you can first use getContentText() and after that parse(). One example implementation, that is compatible with your code, can be this one:
if (resp.getResponseCode() == 200) {
var results = JSON.parse(resp.getContentText());
}
You can then access to the data referring to that variable and the name of the parameter. For example, you could use results.code, results.token… If this explanation doesn't clarify your question, please ask me again for further help.

Related

Include multiple incoming SMS messages/responses with Twilio functions

I'm working on a project now within Twilio, using Twilio Functions, where I'm trying to set up SMS messaging so that if we receive an incoming keyword, we respond with a specific message, including a URL. The plan is to have multiple incoming keywords, with different responses so if someone sends an SMS to one of our numbers, depending on that key word, we respond with a basic message and a URL. I'm trying to figure out the best way to handle this within Twilio Functions.
I have this working for a single incoming keyword/response, as seen below.
if (incomingMessage.includes('testpark')) {
twiml.message('StartMyParking:\n\nTo start your parking, please click this link: https://blahblah.com');
} else if (incomingMessage.includes('bye')) {
twiml.message('Goodbye!');
} else {
twiml.message('Please check your zone/code and try again.');
}
While that works, I want to add in more incoming words, along with responses, such as an incoming message of 'testpark2' and a response of 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah2.com'.
Then I would want to include another one with 'testpark3' and a response of 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah3.com' and so on, all within the same script.
Can someone help me understand how to achieve this?
There are a lot of ways to achieve your desired outcome, but here's the most straightforward to begin with.
Instead of creating an else if statement for every possible keyword, you could define the keyword/response pairs up front using a JavaScript Map.
The keys of the Map will be your keywords, the values of the Map will be your responses:
const keywordResponseMap = new Map([
['testpark2', 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah2.com'],
['testpark3', 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah3.com'],
['testpark', 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah.com'],
]);
const keywords = Array.from(keywordResponseMap.keys());
let keyword;
if (incomingMessage.includes('bye')) {
twiml.message('Goodbye!');
}
else if (keyword = keywords.find(k => incomingMessage.includes(k))) {
const response = keywordResponseMap.get(keyword);
twiml.message(response);
} else {
twiml.message('Please check your zone/code and try again.');
}
Also note that I'm putting the bye case up front because it is more performant than looking for the keywords in the incomingMessage, thus you avoid unnecessarily doing that processing when a user says bye.
You can use find to search for any keyword that is in the incomingMessage, then you can use the keyword that you found to retrieve the response from the map.
If your response will always be the same except for the URL, you could further optimize this by only storing the URL in the map and using string interpolation like this:
const keywordUrlMap = new Map([
['testpark2', 'https://blahblah2.com'],
['testpark3', 'https://blahblah3.com'],
['testpark', 'https://blahblah.com'],
]);
const keywords = Array.from(keywordUrlMap.keys());
let keyword;
if (incomingMessage.includes('bye')) {
twiml.message('Goodbye!');
}
else if (keyword = keywords.find(k => incomingMessage.includes(k))) {
const url = keywordUrlMap.get(keyword);
twiml.message(`StartMyParking:\n\nTo start your parking, please click this link: ${url}`);
} else {
twiml.message('Please check your zone/code and try again.');
}
It is also important to note that I'm putting testpark last in the map because testpark matches to testpark2 and testpark3. If you'd put it first, it would always resolve to testpark even with a user submits testpark2 or similar values.
Also, I'm using the Map type because it guarantees the order in which the keys are returned, which is again important for the previous point.
When you have a lot more keywords and responses, you may have to start looking at a solution to store them externally like a database, and query the database by keyword to resolve the response.
Good luck, we can't wait to see what you build!

Correct way to send auth headers via ajax request to an API

I have a form where I've stored the auth key in a hidden field.
hidden_field_tag 'auth_key', Settings.biometric.auth_key
I am sending an ajax request to an API where I'm setting the auth key in the header which requires the key:
var authKey = $("input[id='auth_key']").val();
beforeSend: function (xhr) {
xhr.setRequestHeader ("auth", authKey);
}
All is working fine, just that the auth key resides in the form and is easily inspectable by any malicious user.
I think this might not be the right way to do this
What is the best approach to perform this?
TL;DR:
Anyone who has access to the client-side (a.k.a your User using a browser), can ultimately find a way to get this auth_key, because a client-user has and will always have power/access on what "data" gets sent/received/stored, especially easier here in webapps because of built-in browser developer tools.
Some Explanations:
Disclaimer: I am not well versed in this field, so if anyone, please let me know.
Yes, it can be encrypted in the client-side, but a user/hacker can decrypt them because the "encryption" trace can be found somewhere in your JS script file:
// application.js example
...beforeSend: function (xhr) {
var encryptedAuthKey = localstorage.get('encrypted-auth-key');
var decryptionPassword = 'abcd';
var authKey = doSomeFancyDecryption(encryptedAuthKey, decryptionPassword);
xhr.setRequestHeader ("auth", authKey);
}
However, a secure way would be to encrypt them using a password stored in the server-side, so that the client cannot debug/inspect/find this password in the JS code... except that this is not possible, see below:
// application.js example
...beforeSend: function (xhr) {
var encryptedAuthKey = localstorage.get('encrypted-auth-key');
var decryptionPassword = someFunctionThatPerformsAjaxRequestToServerAndReturnsTheDecryptionPassword();
var authKey = doSomeFancyDecryption(encryptedAuthKey, decryptionPassword);
function someFunctionThatPerformsAjaxRequestToServerAndReturnsTheDecryptionPassword() {
// do some ajax request with Auth header equals Something...
// ummm... what's the value of this something?
// ummm... I cannot pass in my Username and Password, of course!
// ummm... I cannot pass in another-kind of "auth_key", which just basically loops this process itself.
}
xhr.setRequestHeader ("auth", authKey);
}
You can "sign" your request so that you won't need to directly supply anymore the auth_key as part of your request (but the client-user can still hack this and get the auth-key and create their own request themselves, precisely because they can see and have access to your underlying code like below):
// application.js example
...beforeSend: function (xhr) {
var authKey = localstorage.get('auth-key');
var params = // assign all input fields as key-values object here
var url = this.url;
var signature = generateSignatureUsingHMAC(authKey, url, params)
xhr.setRequestHeader ("Signature", signature);
}
I would personally do something like the signature-based authorization above

UrlFetchApp.fetch with very long URLs

New to Google Apps Script, trying to retrieve data from a URL with UrlFetchApp.fetch but the URL length is limited to 2kB per call (https://developers.google.com/apps-script/guides/services/quotas).
Thus, with a long URL I get the error Limit Exceeded: URLFetch URL Length..
Example:
var url = 'http://www.longurlmaker.com/go?id=EXLVPCEEVMCJMZAHPCWLLUKQSDBNNSRSQDOGFTLAFNJRMJZCMVNYQXOIAQWOJOHZRVFXOQYTEHLRRKTEFGDVDSEEIBTRPARGVWDJNBDSJOJBYDGEJKANCFSKGLCVMTCHQFREHUWRIFTHIAMSKNGMSYXZKZUWTWEKCVOKPKCYPVGYWTRGHXTZWRYGRTCKPHUSCICSSFRIAYHXRYEYVXYROXYGQBQGILYKUBDMGUVHSCEKAJIWGHOVENBUOSBXDAHXBLKIFGQYIVIJERFLYUGCHIXVBZSFZACBMNJRTZPBUYLYPQKNLQQSZOOANHFMIINUWXLPWBRRACQPTADFRUXRIMSVTYIBHWWDTISQKKIKNZAHZDMRYJJGWBCPZKRHHNKAVDRFOZPBYQIYTUQREZYABAQBLHISVSTRWLWKKMLJCUIWOYOTYMUZNKAZSISOBMFXXCHIOTRRNANCYCVWPQWCBWCUFUIGHODEQLMFEEWSEKUDMQABGWEITHCYBLEIZINQTZVYERQJCLNPBNRIKVQDCTCEEGNEPAUIAPHFHXOJIBZKPQSAMJDOCGTHMGLCHGKIVRNDPCNYDMITCBTOKXDNDWVQDGSLMDTIVHLKJYJNLRGNSZBDWFRACMQFTIRFLKOHSARBZAOKSUXLUZOQEFQGRHMKPEQBOFIHFAIEBWOURMFLLUBQASXRZKCPOTRDZAKEBSJDPXXGKCRVXTMXMKPLUSBJLSNLSXPUQZXFXUMHXDDUXPRJAGVVYWEKORVHPLBFKYLHTXPQBSLZICIIJDDIZISOZOWOAYULXFSQDIHFASEIVMQEQUMQCFFCTBRTZLEXRXNVGVAGOFOJSFOIABYCGEFAFWUFHZCZXQUDMVJAAYJSEYBFZAIFENGJJAPRASQXILBVHKVIJFAODBTCCBI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GLMEXBSSKWWBIGJFVNUHSQVRZLQYTYVZJHDHIWZSSWUACEGXSBEKRZCRKSPEQKDASG'
var response = UrlFetchApp.fetch(url);
Is there any way I can get around this limit, maybe by using another library to make the GET request?
EDIT
Jack Brown's solution works well if I run the function from the script editor. In order to make the functionality accessible as a google-spreadsheets function, I used the following:
Using the UrlShortener API in a custom Spreadsheet function
You can use Url Shortener API to create a short URL and pass it to URLFetchApp like so:
function shortenUrl() {
var Lurl = 'http://www.longurlmaker.com/go?id=EXLVPCEEVMCJMZAHPCWLLUKQSDBNNSRSQDOGFTLAFNJRMJZCMVNYQXOIAQWOJOHZRVFXOQYTEHLRRKTEFGDVDSEEIBTRPARGVWDJNBDSJOJBYDGEJKANCFSKGLCVMTCHQFREHUWRIFTHIAMSKNGMSYXZKZUWTWEKCVOKPKCYPVGYWTRGHXTZWRYGRTCKPHUSCICSSFRIAYHXRYEYVXYROXYGQBQGILYKUBDMGUVHSCEKAJIWGHOVENBUOSBXDAHXBLKIFGQYIVIJERFLYUGCHIXVBZSFZACBMNJRTZPBUYLYPQKNLQQSZOOANHFMIINUWXLPWBRRACQPTADFRUXRIMSVTYIBHWWDTISQKKIKNZAHZDMRYJJGWBCPZKRHHNKAVDRFOZPBYQIYTUQREZYABAQBLHISVSTRWLWKKMLJCUIWOYOTYMUZNKAZSISOBMFXXCHIOTRRNANCYCVWPQWCBWCUFUIGHODEQLMFEEWSEKUDMQABGWEITHCYBLEIZINQTZVYERQJCLNPBNRIKVQDCTCEEGNEPAUIAPHFHXOJIBZKPQSAMJDOCGTHMGLCHGKIVRNDPCNYDMITCBTOKXDNDWVQDGSLMDTIVHLKJYJNLRGNSZBDWFRACMQFTIRFLKOHSARBZAOKSUXLUZOQEFQGRHMKPEQBOFIHFAIEBWOURMFLLUBQASXRZKCPOTRDZAKEBSJDPXXGKCRVXTMXMKPLUSBJLSNLSXPUQZXFXUMHXDDUXPRJAGVVYWEKORVHPLBFKYLHTXPQBSLZICIIJDDIZISOZOWOA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MJBTSURJCAETWHMQSVKVPFGRJISOIQZUZBOSWGCYHGSDOEUGZECPKJGURZIZPIUPJIIGPLEWSXAGCUNCZPRJYYDPYMOOUIDDRMKHXOEPMEVOZJQYYHHWGLMEXBSSKWWBIGJFVNUHSQVRZLQYTYVZJHDHIWZSSWUACEGXSBEKRZCRKSPEQKDASG'
var url = UrlShortener.Url.insert({
longUrl: Lurl
});
Logger.log('Shortened URL is "%s".', url.id);
var response = UrlFetchApp.fetch(url.id);
Logger.log(response)
}
Make sure you have selected URL shortener API under Resources>Advanced Google Services> URL shortener API v1 (set to on) and also enabled the same in developers console. For more details refer here
EDIT
Google shortener seems to have some issues with a certain type of URL. This is a more generalized solution. You can select different providers by modifying provider key in the payload below. More details can be found here
function shortenUrl(Lurl) {
if(Lurl == undefined){
var Lurl = 'http://www.longurlmaker.com/go?id=EXLVPCEEVMCJMZAHPCWLLUKQSDBNNSRSQDOGFTLAFNJRMJZCMVNYQXOIAQWOJOHZRVFXOQYTEHLRRKTEFGDVDSEEIBTRPARGVWDJNBDSJOJBYDGEJKANCFSKGLCVMTCHQFREHUWRIFTHIAMSKNGMSYXZKZUWTWEKCVOKPKCYPVGYWTRGHXTZWRYGRTCKPHUSCICSSFRIAYHXRYEYVXYROXYGQBQGILYKUBDMGUVHSCEKAJIWGHOVENBUOSBXDAHXBLKIFGQYIVIJERFLYUGCHIXVBZSFZACBMNJRTZPBUYLYPQKNLQQSZOOANHFMIINUWXLPWBRRACQPTADFRUXRIMSVTYIBHWWDTISQKKIKNZAHZDMRYJJGWBCPZKRHHNKAVDRFOZPBYQIYTUQREZYABAQBLHISVSTRWLWKKMLJCUIWOYOTYMUZNKAZSISOBMFXXCHIOTRRNANCYCVWPQWCBWCUFUIGHODEQLMFEEWSEKUDMQABGWEITHCYBLEIZINQTZVYERQJCLNPBNRIKVQDCTCEEGNEPAUIAPHFHXOJIBZKPQSAMJDOCGTHMGLCHGKIVRNDPCNYDMITCBTOKXDNDWVQDGSLMDTIVHLKJ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BQLYNWWQPQIOTMQQGAJELFUFHWKHEKKFBVEORBFHRNWLZNBGOKLZQGFYCPGGAQMCMQQESWLKJIVIVXPJHAIYGOXIDDPEUCGGTXKLTWVCERLZOAJWBRVIFSRJWGNQJUWCRHOKDKNIBYIPZRMBJHJPZAYVHMMQGJTYQHIURVCSULITCUVLBEBBEAXLMJBTSURJCAETWHMQSVKVPFGRJISOIQZUZBOSWGCYHGSDOEUGZECPKJGURZIZPIUPJIIGPLEWSXAGCUNCZPRJYYDPYMOOUIDDRMKHXOEPMEVOZJQYYHHWGLMEXBSSKWWBIGJFVNUHSQVRZLQYTYVZJHDHIWZSSWUACEGXSBEKRZCRKSPEQKDASG'
}
var payload = {
'apikey': 'your API Key', //Create a new Key here http://www.tiny-url.info/request_api_key.html
'provider' : 'tinyurl_com',
'format' : "text",
'url' : Lurl}
var options = {
'method':'POST',
'payload':payload
}
var url = "http://tiny-url.info/api/v1/create"
var response =UrlFetchApp.fetch(url, options)
var turl = response.getContentText()
Logger.log(turl)
response = UrlFetchApp.fetch(turl)
Logger.log(response)
}
Hope that helps!
On March 30, 2018, Google deprecated the URL Shortener service that was used in the accepted answer.
I wrote a script to use the Firebase Dynamic Links Short Links API service.
The docs are here if you want to cook your own.

AuthFlow.CreateCredentialsFromVerifierCode throws error only on load balancer

I am using Tweetinvi for posting images to Twitter.
From our App servers its working fine to post to Twitter.
But, When tried from our load balancer getting this error -
Error:The credentials are required as the URL does not contain the
credentials identifier.
Stack Trace: at Tweetinvi.AuthFlow.CreateCredentialsFromVerifierCode(String
verifierCode, String authorizationId, IAuthenticationContext
authContext)
My code snippet is like this -
var verifierCode = Request.Params.Get("oauth_verifier");
var authorizationId = Request.Params.Get("authorization_id");
var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(verifierCode, authorizationId);
I see these parameters(oauth_verifier, authorization_id,..) being passed to the callback page. But still seeing the above error in the call back page.
Note: this issue is only when I try posting to Twitter on our loadbalancer (using the individual servers working fine).
Should I use a different overloaded function?
So the problem comes from the fact that you are actually using a load balancer. But let me explain how the authentication works and how you can solve your problem.
var appCredentials = new ConsumerCredentials("", "");
var authContext = AuthFlow.InitAuthentication(appCredentials, "");
When you call AuthFlow.InitAuthentication, it returns an IAuthenticationContext. This context contains all the information required to process the callback from Twitter.
But in addition to this, Tweetinvi adds a parameter authorization_id to the callback so that it can map the callback request to an actual IAuthenticationContext.
var authorizationId = Request.Params.Get("authorization_id");
var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(verifierCode, authorizationId);
When you call AuthFlow.CreateCredentialsFromVerifierCode with an authorization_id as a parameter it will look into the local dictionary and try to get the IAuthenticationContext.
Because you are using a load balancer, the server executing the AuthFlow.InitAuthentication can be different from the server your receiving the callback request.
Because your callback arrives at a different server, it actually result in the AuthenticationContext being null.
This is what I tried to explain in the documentation.
How to solve this?
What you need to do is to store the IAuthenticationContext information required for the CreateCredentialsFromVerifierCode to continue its work when it receives the callback. I would suggest you store this in your database.
When you receive your callback you will have to get back these information from your db. To do that I would suggest that when you initally call the `` you add to the callback url a parameter with the value storing the authentication id in your database (e.g. my_auth_db_id=42).
var authContext = AuthFlow.InitAuthentication(appCredentials, "http://mywebsite.com?my_auth_db_id=42");
When your callback arrives you will be able to do :
var myDBAuthId = Request.Params.Get("my_auth_db_id");
With this value you can now create a new token with the required information (stored in the db).
var token = new AuthenticationToken()
{
AuthorizationKey = "<from_db>",
AuthorizationSecret = "<from_db>",
ConsumerCredentials = creds
};
Now you are ready to complete the operation:
var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(verifierCode, token );
I realize this is a big post, but I wanted to explain how it works.
Please let me know if anything does not makes sense.

Calling webservice from UIAutomation

Is it possible to call a webservice from UIAutomation?
on this webpage http://www.geonames.org/export/ajax-postalcode-autocomplete.html
it is possible to type in country and postal code, and get following reponse
http://api.geonames.org/postalCodeLookupJSON?postalcode=2830&country=DK&username=demo
{"postalcodes":[{"postalcode":"2830","countryCode":"DK","lng":12.4666667,"placeName":"Virum","lat":55.8}]}
Im fairly new to this, is there a way i can call the service with arguments or build the url myself and call that and get a response as JSON into UIAutomation?
You can do it like this:
var result = target.host().performTaskWithPathArgumentsTimeout("/usr/bin/curl", ["http://yoururl"], 30);
var json = JSON.parse(result.stdout)

Resources