Twitter OAuth callback URL for a Chrome extension - google-chrome

I'm trying to develop a Chrome extension on which people can sign in with their Twitter account (using OAuth 1.0A).
I have not provided the callback URL in the Twitter application settings so far, so the user is returned a PIN to enter on the extension to complete the authorization process. But I don't want to implement the final PIN verification step in the extension.
Instead, I'd like that once the user was redirected to Twitter and authorized the app to access his account, he is automatically logged into the extension and can use it in order to post tweets.
I know I should definee a callback URL but I have no idea on what to use. I've been struggling for several days, during which I tried multiple things (like chrome://extensions/extension_id/ but it's not accepted by Twitter). I didn't manage to find the solution.
Any idea on what should be the callback URL? And what should contain the file pointed by that URL?

I know this is incredibly old, but I had the same issue and finally figured out how to do it, so hopefully this helps other people who find this.
In your twitter apps configuration, you have to add a callback URL to a domain. Then, in your chrome extension, you have to have a content script that is injected on that same domain. The content script will have some logic that will parse the query string for the auth tokens and send that as a message to your background script. Then, in your background script, you can use those tokens to get the actual oauth tokens, which are then saved to local storage or chrome.storage.
Here is a brief example:
in your manifest.json, make sure your content script matches the same domain that you put in your twitter app settings callback URL:
"content_scripts": [{
"matches": ["https://andyjiang.com/*"],
"js": ["js/session.js"]
}]
Then, in your js/session.js file, have this sort of logic:
chrome.runtime.sendMessage({type: 'auth', session:
window.location.search.substr(1)}, function(response) {
window.open('', '_self', '');
window.close();
});
In your background script, have some logic that listens for the message, gets the token, and uses Twitter's API for the third leg of the oauth process to finally get the oauth token and oauth token secret, which you can then save in localStorage or chrome.storage.
Hope that helps. Here is sample code if you want to play around with it.
https://github.com/lambtron/chrome-extension-twitter-oauth-example

Related

Connecting a Hello sign API to apps script project

I want to Create a new API app usin Google Apps script and Hello sign API
I have specified the redirect URL as https://script.google.com/macros/s/AKfycbyKw3oLmpqINGsDml281iUbxBboKn950dqVFXNibMfLurxYcRPf/exec and the screenshot is shown below
Also, the code of the apps script file is
function doPost(e) {
return ContentService.createTextOutput("Hello API Event Received.");
}
The documentation says: https://app.hellosign.com/api/eventsAndCallbacksWalkthrough
I get error message as shown like here
Illustation image here
405(http-status-code-405) is "method not allowed", where a incorrect method is used. In this case, ContentService uses a specific pattern of redirection (post-redirect-getwiki), where the POST request to script.google.com is redirected(302) to a one time url at script.googleusercontent.com, to which a GET request should be made.
302 specification did not intend the method to change from POST to GET, but this pattern is very common in the web. But, hellosign-api seems to make another POST request to the one time redirected url at script.googleusercontent.com. There isn't much you could do from apps script to change this behavior. It is possible to change to HtmlService to avoid the redirection, but Hellosign specifically requires you to provide a specific text content as response: Hello API Event Received. This isn't possible with HtmlService.
You could make a feature request/bug fix request to Google to change redirect status to 303, where method change to GET is explicitly specified. Or Make a request to Hellosign to follow 302 redirects with GET request, as that is the most common way, things are done in the web.
References:
Curl redirect preferred method -L
ContentService Redirect
Post redirect get wiki
RFC7231 § 6.4.3
RFC7231 § 6.4.4
Looking at our backend logs, we see that your callback URL is not allowing our POST call to be granted to fetch "Hello API Event Received" response. This can be due to they way your [callback handler is set up][1].
Would you mind taking a look at this similar ask and they way they tackled the POST/Allow header field and let us know how it goes by emailing at apisupport#hellosign.com?
App Script sends 405 response when trying to send a POST request
[1]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405#:~:text=The%20HyperText%20Transfer%20Protocol%20(HTTP,supported%20by%20the%20target%20resource.

Vimeo api /me doesn´t return upload_quota value

I need to check my own upload quota.
As described in docs, I use GET https://api.vimeo.com/me
API response doesn´t return expected value:
In the response, find the upload_quota object, look for the space
object inside it, and check the value.
Has API changed? thanks
One of two things is happening:
Your API app has not yet been granted upload permission. To request upload access, visit your app's management page at https://developer.vimeo.com/apps, click on "Request Upload Access", and fill out the request form.
If your API app already has upload permission, the token used to authenticate the request may not have the upload scope. When a token lacks the upload scope, upload-related metadata like the upload_quota array will not return.
I hope this information helps!

Set up Google Calendar V3 API Push notification via my Google Apps script

I want to use Google CAL API v3 to watch multiple calendars and thus to update all those events from those calendars to a Master Calendar, so I need to use WATCH/PUSH notification in order that whenever there is a new event in those cal’s, those events shd be automatically be pushed/created in my master calendar.
But, I am facing the following issue :Under APIs Explorer. Most of the services return 200 OK, except the Watch request not working.
Services > Calendar API v3 > calendar.events.watch
i got the below request and response
Request
POST https://www.googleapis.com/calendar/v3/calendars/mailid%40domain.com/events/watch?key={YOUR_API_KEY}
{
}
Response
400 OK
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "entity.resource"
}
],
"code": 400,
"message": "entity.resource"
}
}
And then i followed as per the below google documentation
https://developers.google.com/google-apps/calendar/v3/push
Registering Your domain:
Step 1: Verify that you own the domain
Step 2: Register your domain
I verified my domain/notifications in google webmaster tools.
My verified domain look like this:
http://my-domain.com/notifications
And have added my domain name in the webhooks under the PUSH in Google Developer Console, as explained in the doc.
Is there anything i am missing here, plz is there an issue in SSL certificate fr my domain, how can i atleast test in the API explorer, so that i get a return code 200 OK. After that, I need to implement this push/WATCH via Google Apps Script.
Is there any documentation for apps script to use push notification.
Any hint, tip will help me, I am tired with this for the past 1 week in trial and error method.
In the request that you posted the body is empty. In the documentation there is an example where you need to provide the calendar ID, the web_hook and other information:
{
"id": "01234567-89ab-cdef-0123456789ab", // Your channel ID.
"type": "web_hook",
"address": "https://example.com/notifications", // Your receiving URL.
...
"token": "target=myApp-myCalendarChannelDest", // (Optional) Your channel token.
"expiration": 1426325213000 // (Optional) Your requested channel expiration time.
}
Add this information when creating the push notification.
For using apps script you can use URLfetch service with the method "fetch()" then you would need to provide the parameters mentions and make the call as a POST.
Hope this helps.
UPDATE: I will write here to have more space.
Push notifications work in this way.
-You create a push notification with the id, the resource you want to watch, the address where you want to receive the notification and the optional parameters.
-if successful, the server will watch that resource and will send a notification to the address mentioned in the request describing the changes when a change is made to the resource.
-The server needs to know that you received the notification, so from the address mentioned in #1, you need to tell the server that you received the notification returning a HTTP 200 response. (for this you need an app that is listening to the notifications and sending the responses)
for your questions
1.- As the server will make a HTTP request to a url (your web_hook address) Google requires it to be secure, that's why it is required to be HTTPS.
2.- Yes, without that url you won't be able to receive the notification.
3.- Google also needs to verify that the url you provided is actually yours, so you will need to provide the url, then Google will provide you a file, you have to make this file available in that url, then Google will call the url an will retrieve that file. Then you can prove that the URL is yours. I'm not sure if this step can be done with apps script. You can actually deploy a script as web app but i'm not sure if you can use it for this purpose.(here you can find more info and different ways to verify the url)
4.- That's created by yourself. In the documentation is pointed out the recommendations for it.
I hope this clarifies your questions.
You can check here how push notifications work, this example is for Drive but the concept is the same.

How to connect to the Facebook Graph API from Google Apps Script?

I'm trying to connect to the Facebook Graph API via a Google Apps Script but I'm getting an error
I've tried:
function myFunction (name) {
FB.init({
appId : '{your-app-id}',
status : true,
xfbml : true,
version : 'v2.0'
});
var jsonData = UrlFetchApp.fetch("graph.facebook.com/"; + name);
}
I've also tried:
function myFuntion(name) {
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
version : 'v2.0'
});
};
var jsonData = UrlFetchApp.fetch("graph.facebook.com/"; + name);
}
but neither have worked, I always get a:
"ReferenceError: "FB" is not defined." and a "ReferenceError: "window" is not
defined"
and
"(#4) Application request limit reached","type":"OAuthException","code":4}}
despite putting in my facebook app ID into the variable. I know that "window" is part of an external javascript library so that's why I'm unable to use it in a Google Apps Script, but even after looking at other posts I'm still confused on why I get a "FB" is not defined error.
Any ideas on how to solve this?
There are error codes at the bottom of this page:
Facebook Graph API - Error codes
The "OAuthException" has to do with the Login Status. If you get that error, then you aren't logged in, and to get what you want, you need to be logged in.
You can get an App Access Token using a Server to Server request. There are four types of
Access Tokens:
User - to read, modify or write a specific person's Facebook data on their behalf.
App - modify and read the app settings, and publish Open Graph actions.
Page - read, write or modify the data belonging to a Facebook Page.
Client - the client token is used rarely. Very limited Access to Facebook.
Forms of Access Tokens
User access tokens come in two forms: short-lived tokens and long-lived tokens
short-lived - lifetime of about an hour or two - generated via web login
long-lived - lifetime of about 60 days
You probably don't have an App Access Token. You have an App ID, but that's different than an App Token.
You only get your App Token once. You need to run some code to get it.
Note, that you also must know your App Secret in order to run this code. If you don't know, or have your App Secret, then you need to get that.
See if you can run this code:
//A Facebook App Token never changes unless you go to the Facebook Developers Console,
//and you
//change the App Secret. So, do NOT keep requesting a new App Token. Just get it once,
//then
//hard code it into a backend secret function.
// The App Token can be used to modify your App, but you can just do that 'Manually'
function getOneTimeFB_AppToken() {
Logger.log("getOneTimeFB_AppToken ran");
//keep this info secret
//Generate an App Access Token
var myApp_ID = 'Your App ID';
var myAppSecret = 'Your App Secret';
var optnAppTkn = {"method" : "get"};
var getAppTknURL = "https://graph.facebook.com/oauth/access_token?client_id=" + myApp_ID + "&client_secret=" + myAppSecret + "&grant_type=client_credentials"
var getAppTkn = UrlFetchApp.fetch(getAppTknURL, optnAppTkn);
Logger.log("Object returned from GET: " + getAppTkn)
var myAppTkn = getAppTkn.getContentText();
Logger.log("myAppTkn: " + myAppTkn);
};
Run that code, then in the script editor, choose the VIEW menu, and the LOGS menu item. Read what is in the LOGS. Don't keep running this code over and over again. Just run it once if it's successful.
If that code works, then you just successfully communicated with Facebook.
You need to understand what the Tokens can do, and what your options are. If you are not going to get a token from a user through client side authorization, then you need to understand the App Token.
App Tokens allow you to interact with Facebook on behalf of an app rather than a user. This can be used to read YOUR app insights and modify the parameters of YOUR app.
You never want to use an App Token in client side (browser) code. That would be a major security problem.
However, if a user has granted your application publishing permissions, then you can use the App Token to publish content to Facebook on behalf of that person. So, app access token can be used in place of a user access token to make API calls IF your app has been granted publishing permissions.
But how do you get publishing permissions? Well, there is no way to get the initial short term access token through the server. That just makes sense if you think about it in terms of security. You can't get the initial, short term access token any other way than through a client login. So, if you want to do something that isn't within the bounds of the App Access Token, you can't do it without having the user login through client side.
You can achieve a client side login, without using the JavaScript SDK. So, in the case of an Apps Script Stand Alone HTML web app, you can still use Facebook login without needing to link to the Facebook JavaScript SDK. If you need to do that, let me know.
In that code, FB is an object. The object needs to be assigned "key/value" pairs. Every "key/value" pair is an element (property) in the object. The error is directly related to how objects work. That FB object gets assigned values from a link (inside HTML) to the Facebook API. If you are trying to use an HTML link to the Facebook API from server side (.gs) code, it won't work. There are lots of things that could be going wrong. In order to know exactly what is going wrong, we need to know whether that code is in a gs file, or an HTML file inside a <script> tag.
There are a couple of ways to connect to Facebook:
From HTML (Client Side)
From the server with HTTP Requests
It looks like the code you are using is from an example of how to use the Facebook JavaScript SDK that is meant to run from inside HTML. The problem with that, is that Apps Script sanitizes HTML sent to the browser. So, if you try to link to the Facebook JavaScript SDK through the HTML, you may not get access. I know that, in the past, I have not been able to use a link to the Facebook API in HTML with the NATIVE sandboxed mode. I haven't tried the new IFRAME sandbox mode.

How to authorize with oauth 2.0 from appscript to Google APIs?

I'm playing around with AppScript and try to get an oAuth 2.0 access token.
Any sample out there how to get this working in AppScript?
I am working on a cleaner tutorialized version of this, but here is a simple Gist that should give you some sample code on how things would work -
https://gist.github.com/4079885
It still lacks logout, error handling and the refresh_token capability, but at least you should be able to log in and call a oAuth 2 protected Google API (in this case its a profile API).
You can see it in action here -
https://script.google.com/macros/s/AKfycby3gHf7vlIsfOOa9C27z9kVE79DybcuJHtEnNZqT5G8LumszQG3/exec
The key is to use oAuth 2 Web Server flow. Take a look at getAndStoreAccessToken function in the gist to get the key details.
I hope to have this published in the next few weeks but hopefully this will help in the mean time.
UPDATE - adding in info on redirect_uri
The client secret is tied to specific redirect URIs that the authorization code is returned to.
You need to set that at - https://code.google.com/apis/console/
The highlighted URI needs to match the published URI (ends in /exec). You get the published URI from the script editor under Publish -> Deploy as web app. Make sure you are saving new versions and publishing the new versions when you make changes (the published URI stays the same).
I've modified the example above to use the newish state token API and the CacheService instead of UserProperties, which is now deprecated. Using the state token API seems to make things a little more secure, as the callback url will stop accepting a state token after a timeout.
The same caveats apply. Your redirect URIs have to be added to your (script) project in the developer's console, meanwhile you have to yank the CLIENT_SECRET and CLIENT_ID from the console and paste them in. If you're working within a domain, there don't seem to be any guarantees on what URL will be returned by ScriptApp.getService().getUrl(), so I wound up basically having it get the address dynamically, then waiting for to fail on the the (second) redirect, and then hard-coded the resulting URI.
https://gist.github.com/mclaughta/2f4af6f14d6aeadb7611
Note that you can build an OAuth2 flow using this new API, but it's not a complete sample yet:
https://developers.google.com/apps-script/reference/script/script-app#newStateToken()
In particular, you should not pass 'state' directly to the /usercallback URL yourself, because the OAuth2 service provider is responsible for round-tripping the 'state' parameter. (Instead, you pass 'state' to the auth URL, and the service provider automatically attaches it to the callback URL.)