Connecting Chrome Extension to StackExchange oAuth API - javascript

TL;DR -- I am trying to build a Chrome extension that displays the number of current notifications for a user from StackOverflow.
I am following the Chrome Extension tutorial on creating an extension that utilizes oAuth. Swapping out the Google oAuth bits for (what I think are) the StackExchange API bits, I end up with the following in my background.js file:
var oauth = ChromeExOAuth.initBackgroundPage({
//ES6 template strings!
'request_url' : `https://stackexchange.com/oauth?client_id=${STACK_APP.id}&scope=read_inbox,no_expiry`,
'authorize_url' : 'https://stackexchange.com/oauth/login_success',
'access_url' : 'https://stackexchange.com/oauth/access_token',
'consumer_key' : STACK_APP.key,
'consumer_secret' : STACK_APP.secret,
//'scope' : '', //not sure I need this...
'app_name' : 'StackOverflow Notifications (Chrome Extension)'
});
oauth.authorize(function () {
console.log('authorize...');
});
When I run the extension locally, it attempts to open a new browser tab to complete the oAuth handshake -- which is great, except that I end up at the following URL:
https://stackexchange.com/oauth/login_success?oauth_token=undefined
The browser tab gets stuck here.
I'm not really sure what the problem is - I don't know if I have the wrong URLs listed in my initBackgroundPage() call, or if my StackApp has the wrong oAuth domain (since it's a Chrome extension... this question didn't really answer things for me).
Any ideas would be most appreciated!

From what I can tell, the oAuth tutorial I mentioned in my OP is outdated -- you no longer need any of that, you can use chrome.identity instead.
To be clear, there are a few things I had to do:
STACK_APP = {
id : 1234,
scope : 'read_inbox,no_expiry',
request_uri : 'https://stackexchange.com/oauth/dialog',
redirect_uri : chrome.identity.getRedirectURL("oauth2")
};
//ES6 template string!
var requestUrl = `${STACK_APP.request_uri}?client_id=${STACK_APP.id}&scope=${STACK_APP.scope}&redirect_uri=${STACK_APP.redirect_uri}`;
//https://developer.chrome.com/extensions/identity
//https://developer.chrome.com/extensions/app_identity#update_manifest
chrome.identity.launchWebAuthFlow({
url : requestUrl,
interactive : true
}, function (url) {
console.log('redirected to: ' + url);
});
Note the redirect_uri -- this ends up being a subdomain of chromiumapp.org, so you need to list that in StackApps as the domain for your app (allowing oAuth to continue).

Related

WebRTC video streaming in PubNub

I've recently gotten my hands on the WebRTC sdk by PubNub. Everything's been going great but I've been having trouble displaying video from a client to my screen.
As mentioned in their documentations and tutorial I've written the following code:
function login(form) {
var pub = <publish_key>;
var sub = <subscribe_key>;
var phone = window.phone = PHONE({
number : form.username.value,
publish_key : pub,
origin :'pubsub.pubnub.com',
subscribe_key : sub,
//media : { audio : true, video : true }
ssl :true
});
var ctrl = window.ctrl = CONTROLLER(phone);
ctrl.ready(function(){
form.username.style.background="#55ff5b";
form.login_submit.hidden="true"; // Hide login button
ctrl.addLocalStream(vid_thumb);
});
ctrl.receive(function(session){
session.connected(function(session){
video_out.appendChild(session.video);
});
session.ended(function(session) { ctrl.getVideoElement(session.number).remove(); });
});
}
function makeCall(){
if (!window.phone) alert("Login First!");
var num = form.number.value;
if (phone.number()==num) return false; // No calling yourself!
ctrl.dial(num);
return false;
}
Evrything seems to be working, but the actual video is not being shown on my screen.
(I'm using chrome browsers on both machines)
Can anybody please help out?
Thanks
i got the solution..
Its a very weird solution though and i cant really say how it solved my problem..
I was previously putting my javascript codes in another script file and then linking that file to my HTML page. But as soon i transferred those code to my HTML page everything seemed to work just fine.
Thanks everyone.
WebRTC Video Streaming in PubNub P2P
Answer: WebRTC running on localhost with HTTPS
We answered a similar question yesterday. You can find the answer here in the following Stackoverflow answer link. Essentially you need to make sure you are running HTTPS locally and also using the correct variable scoping as mentioned by Craig Conover.
And you can find the source code on github gist.

chrome.identity.launchWebAuthFlow, how to clear user cache?

I'm developing an extension that works with Gmail and I'd like to be able to allow users to switch between Gmail accounts and still make use of the Google REST APIs.
I'm using chrome.identity.launchWebAuthFlow to acquire OAuth2 access tokens to the Google APIs.
This workflow opens a modal sort of chrome webview. With no url bar at the top. Upon entering a username and password the first time, then allowing for the requested scopes, the webview closes. My app then receives the redirect URI with the access token included. Great.
The problem comes when switching users. One would think it would be as simple as checking that a new email is logged in, then doing the chrome.identity.launchWebAuthFlow again to grab a new token.
Unfortunately the first logged in user seems to remain cached in the system.
function webAuthFlow(userEmail, forceApprovalPrompt, xhrCallback) {
var baseUrl = 'https://accounts.google.com/o/oauth2/auth';
var forceApprovalPrompt = forceApprovalPrompt || 'auto';
var urlParams = {
'redirect_uri' : 'https://inobjcmbajbmllkgkigemcfnikdmlidn.chromiumapp.org/callback',
'response_type' : 'token',
'client_id' : 'not shown here',
'scope' : 'https://mail.google.com/ https://www.google.com/m8/feeds/',
'approval_prompt' : 'force',
'include_granted_scopes' : 'true'
};
var providerDetails = {
url : baseUrl + '?' + stringify(urlParams),
interactive : true
}
var xhrCallback = xhrCallback || false;
console.log(xhrCallback);
var callback = function(responseUrl) {
var params = {},
queryString = responseUrl.split('#')[1],
regex = /([^&=]+)=([^&]*)/g,
m,
validateUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo'
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
validateToken(params.access_token, function() { storeToken(params.access_token, userEmail) }, xhrCallback);
};
chrome.identity.launchWebAuthFlow(providerDetails, callback);
};
I've tried to inspect the chrome webview that pops up by setting approval_prompt to 'force'. It appears there are some cookies associated with it. I'd like to know how to clear persistent data from the webview.
The only thing that seems to work is completely closing out chrome. Not an acceptable UX for my extension.
Thanks in advance if anyone has any pointers on this.
Use chrome.identity.removeCachedAuthToken(object details, function callback) method.
Removes an OAuth2 access token from the Identity API's token cache.
If an access token is discovered to be invalid, it should be passed to removeCachedAuthToken to remove it from the cache. The app may then retrieve a fresh token with getAuthToken.

casperjs testing an internal site

I am trying to run a casper test for an internal site. Its running on pre-production environment, the code so far is
var casper = require('casper').create({
verbose: true,
loglevel:"debug"
});
// listening to a custom event
casper.on('page.loaded', function() {
this.echo('The page title is ' + this.getTitle());
this.echo('value is: '+ this.getElementAttribute
('input[id="edit-capture-amount"]',
'value'));
});
casper.start('https://preprod.uk.systemtest.com', function() {
this.echo(this.getTitle());
this.capture('frontpage.png');
// emitting a custom event
this.emit('age.loaded.loaded');
});
casper.run();
as you can see its not much but my problem is the address is not reachable. The capture also shows a blank page. Not sure what i am doing wrong. I have checked the code with cnn and google urls, the title and screen capture works fine. Not sure how to make it work for an internal site.
I had the exact same problem. In my browser I could resolve the url, but capserjs could not. All I got was about::blank for a web page.
Adding the --ignore-ssl-errors=yes worked like a charm!
casperjs mytestjs //didn't work
capserjs --ignore-ssl-errors=yes mytestjs //worked perfect!
Just to be sure.
Can you reach preprod.uk.systemtest.com from the computer on which casper runs ? For example with a ping or wget.
Is there any proxy between your computer and the preprod server ? Or is your system configured to pass through a proxy that should not be used for the preprod server ?
The casper code seems to be ok.
I know this should be a comment but I don't have enough reputation to post a comment.
As far as CasperJs tests are run in localhost, for testing a custom domain/subdomain/host, some headers need to be defined.
I experienced some problems when passing only the HOST header, for instance, snapshots were not taken properly.
I added 2 more headers and now my tests run properly:
casper.on('started', function () {
var testHost = 'preprod.uk.systemtest.com';
this.page.customHeaders = {
'HOST': testHost,
'HTTP_HOST': testHost,
'SERVER_NAME': testHost
};
});
var testing_url: 'http://localhost:8000/app_test.php';
casper.start(_testing_url, function() {
this.echo('I am using symfony, so this should have to show the homepage for the domain: preprod.uk.systemtest.com');
this.echo('An the snapshot is also working');
this.capture('casper_capture.png');
}

Identify tab that made request in Firefox Addon SDK

I'm using the Firefox Addon SDK to build something that monitors and displays the HTTP traffic in the browser. Similar to HTTPFox or Live HTTP Headers. I am interested in identifying which tab in the browser (if any) generated the request
Using the observer-service I am monitoring for "http-on-examine-response" events. I have code like the following to identify the nsIDomWindow that generated the request:
const observer = require("observer-service"),
{Ci} = require("chrome");
function getTabFromChannel(channel) {
try {
var noteCB= channel.notificationCallbacks ? channel.notificationCallbacks : channel.loadGroup.notificationCallbacks;
if (!noteCB) { return null; }
var domWin = noteCB.getInterface(Ci.nsIDOMWindow);
return domWin.top;
} catch (e) {
dump(e + "\n");
return null;
}
}
function logHTTPTraffic(sub, data) {
sub.QueryInterface(Ci.nsIHttpChannel);
var ab = getTabFromChannel(sub);
console.log(tab);
}
observer.add("http-on-examine-response", logHTTPTraffic);
Mostly cribbed from the documentation for how to identify the browser that generated the request. Some is also taken from the Google PageSpeed Firefox addon.
Is there a recommended or preferred way to go from the nsIDOMWindow object domWin to a tab element in the SDK tabs module?
I've considered something hacky like scanning the tabs list for one with a URL that matches the URL for domWin, but then I have to worry about multiple tabs having the same URL.
You have to keep using the internal packages. From what I can tell, getTabForWindow() function in api-utils/lib/tabs/tab.js package does exactly what you want. Untested code:
var tabsLib = require("sdk/tabs/tab.js");
return tabsLib.getTabForWindow(domWin.top);
The API has changed since this was originally asked/answered...
It should now (as of 1.15) be:
return require("sdk/tabs/utils").getTabForWindow(domWin.top);
As of Addon SDK version 1.13 change:
var tabsLib = require("tabs/tab.js");
to
var tabsLib = require("sdk/tabs/helpers.js");
If anyone still cares about this:
Although the Addon SDK is being deprecated in support of the newer WebExtensions API, I want to point out that
var a_tab = require("sdk/tabs/utils").getTabForContentWindow(window)
returns a different 'tab' object than the one you would typically get by using
worker.tab in a PageMod.
For example, a_tab will not have the 'id' attribute, but would have linkedPanel property that's similar to the 'id' attribute.

Twitter #anywhere using chrome Unsafe JavaScript attempt to access frame

im trying to iplement twitter #anywhere ,
to detect current twitter user info ,
twttr.anywhere(function(T){
if (T.isConnected()) {
currentUser = T.currentUser;
screenName = currentUser.data('screen_name');
alert(screenName);
return true;
}
else {
return false;
};
});
when loading page i get in console :
"Unsafe JavaScript attempt to access frame with URL https://api.twitter.com/xd_receiver.html from frame with URL about:blank. Domains, protocols and ports must match."
i've checked the Registered Callback URL and it's ok ,
everything should work ok ,
any idea what's wrong ?
tnx
I know it's been a long time, but I'm having this problem now.
In this blog, Shannon Whitley said what appears to be the problem.
If you are on “www…” in your browser then try removing it (or vice-versa).

Categories