Using YouTube data api within chrome extension embedded iframe - javascript

I am trying to create a chrome extension that adds an iframe to an existing website and populates it with data from the YouTube data api however I am having trouble with restrictions imposed by the chrome extension content policy.
My current issue comes from user login, I need to use the gapi to get the users OAuth2 key however it appears that gapi isn't supported within sandboxed environments. Is it possible to use the YouTube data api without gapi? Or more directly is it possible have the code below work inside an iframe placed there by a chrome extension? This example comes from the Google docs.
<html><head><title>Google APIs - Sample JS Page</title></head>
<body>
<script>
/***** START BOILERPLATE CODE: Load client library, authorize user. *****/
// Global variables for GoogleAuth object, auth status.
var GoogleAuth;
/**
* Load the API's client and auth2 modules.
* Call the initClient function after the modules load.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes
gapi.client.init({
'clientId': 'REPLACE_ME',
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest'],
'scope': 'https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtubepartner'
}).then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state. (Determine if user is already signed in.)
setSigninStatus();
// Call handleAuthClick function when user clicks on "Authorize" button.
$('#execute-request-button').click(function() {
handleAuthClick(event);
});
});
}
function handleAuthClick(event) {
// Sign user in after click on auth button.
GoogleAuth.signIn();
}
function setSigninStatus() {
var user = GoogleAuth.currentUser.get();
isAuthorized = user.hasGrantedScopes('https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtubepartner');
// Toggle button text and displayed statement based on current auth status.
if (isAuthorized) {
defineRequest();
}
}
function updateSigninStatus(isSignedIn) {
setSigninStatus();
}
function createResource(properties) {
var resource = {};
var normalizedProps = properties;
for (var p in properties) {
var value = properties[p];
if (p && p.substr(-2, 2) == '[]') {
var adjustedName = p.replace('[]', '');
if (value) {
normalizedProps[adjustedName] = value.split(',');
}
delete normalizedProps[p];
}
}
for (var p in normalizedProps) {
// Leave properties that don't have values out of inserted resource.
if (normalizedProps.hasOwnProperty(p) && normalizedProps[p]) {
var propArray = p.split('.');
var ref = resource;
for (var pa = 0; pa < propArray.length; pa++) {
var key = propArray[pa];
if (pa == propArray.length - 1) {
ref[key] = normalizedProps[p];
} else {
ref = ref[key] = ref[key] || {};
}
}
};
}
return resource;
}
function removeEmptyParams(params) {
for (var p in params) {
if (!params[p] || params[p] == 'undefined') {
delete params[p];
}
}
return params;
}
function executeRequest(request) {
request.execute(function(response) {
console.log(response);
});
}
function buildApiRequest(requestMethod, path, params, properties) {
params = removeEmptyParams(params);
var request;
if (properties) {
var resource = createResource(properties);
request = gapi.client.request({
'body': resource,
'method': requestMethod,
'path': path,
'params': params
});
} else {
request = gapi.client.request({
'method': requestMethod,
'path': path,
'params': params
});
}
executeRequest(request);
}
/***** END BOILERPLATE CODE *****/
function defineRequest() {
// See full sample for buildApiRequest() code, which is not
// specific to a particular API or API method.
buildApiRequest('GET',
'/youtube/v3/search',
{'maxResults': '25',
'part': 'snippet',
'q': 'surfing',
'type': ''});
}
</script>
<button id="execute-request-button">Authorize</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body></html>
I will refrain from posting any of my code as it's a total mess and will just confuse anybody who reads it. I also can't help but feel I am going in the wrong direction.
Any pointers as to how to achieve this would be greatly appreciated.

Related

Chrome extension: chrome local storage is not set instantly

I am having strange issues with Chrome Local storage setting and retrieval.
In background.js I am setting it when a certain URL's HTML is fetched once the page loading is completed and then in content.js I am fetching values from local storage. At times it is stored and fetched instantly while other times results.html is undefined. And if I use chrome.storage.local.clear() it makes it more worst, make you to refresh the page 2-3 times at least. Below is my code:
background.js
chrome.runtime.onMessage.addListener(
async function(request, sender, sendResponse) {
// Reset storage
// chrome.storage.local.clear() // it is lagging refreshing values
sendResponse("bar")
// Check whether it is correct URL
var url = 'http://localhost:8000/get.php?url='+request
console.log('URL for AJAX =',url)
var result = await sendReq(url)
var json_result = JSON.parse(result)
var status = json_result['status']
var rules = []
console.log('Status = '+status)
if(status == 'ok') {
rules = json_result['msg']['rules']
chrome.storage.local.set({'rules': rules}, function() {});
url = 'http://localhost:8000/read.php?url='+request
result = await sendReq(url)
// console.log(result)
chrome.storage.local.set({'html': result}, function() {}); // this goes undefined if the URL of visiting page is changed.
} else {
// To check on content script
chrome.storage.local.set({'html': '__FAIL__'}, function() {});
}
}
);
content.js (Using JQuery)
$(function() {
// console.clear()
console.log('The Agile Super Cluster extension cleared all previous output')
chrome.storage.local.get(['html','rules'], function(result) {
// Do not perform things below if it is not a relevant Super Cluster URL
if(result.html == '__FAIL__' || typeof (result.html) == 'undefined') {
return
}
.....
// Out of onReady() block
chrome.runtime.sendMessage(
url,
function (response) {
console.log('Sending Response')
console.log(response);
}
);
The solution is to use messaging correctly so you can wait on the result reliably.
remove chrome.storage, it's not necessary for this task;
remove async from onMessage listener (why?) and use a separate async function to get info;
return the result via sendResponse + return true.
content.js:
chrome.runtime.sendMessage(url, res => {
console.log(res);
if (res.html) {
// use `res.html` here
}
});
background.js:
const API_GET = 'http://localhost:8000/get.php?url=';
const API_READ = 'http://localhost:8000/read.php?url=';
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
getInfo(request).then(sendResponse);
return true; // keep the channel open for asynchronous sendResponse
});
async function getInfo(url) {
const res = JSON.parse(await sendReq(`${API_GET}${url}`));
return res.status === 'ok' ? {
rules: res.msg.rules,
html: await sendReq(`${API_READ}${url}`),
} : {};
}

Simple MSAL Login/Authentication in JavaScript

I'm trying to do a simple login to Azure AD using the MSAL for JavaScript v2.0 library. We want users to be able to authenticate into our site with their work Microsoft accounts. All I need to do is be able to authenticate/login the user via Microsoft, and if they can login via their work Microsoft account, then they're granted access to our site.
I'm using the Javascript library and have followed the code from the Github page and while the login prompt is coming up, afterwards I have no idea how to check if the user is signed in.
Here's the code I'm using, which is basically what's in the sample code from Github:
<script type="text/javascript" src="https://alcdn.msauth.net/browser/2.15.0/js/msal-browser.min.js"></script>
<script type="text/javascript">
const msalConfig = {
auth: {
clientId: "[ClientID goes here]",
authority: "https://login.microsoftonline.com/[tenant ID]",
knownAuthorities: ["login.microsoftonline.com"],
protocolMode: "OIDC",
redirectUri: "[page on our site that doesn't have MSAL auth, listed in Azure Reply URLs]"
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: true, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case msal.LogLevel.Error:
console.error(message);
return;
case msal.LogLevel.Info:
console.info(message);
return;
case msal.LogLevel.Verbose:
console.debug(message);
return;
case msal.LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["User.Read"]
};
const silentRequest = {
scopes: ["openid", "profile", "User.Read"]
};
const ua = window.navigator.userAgent;
const msie = ua.indexOf("MSIE ");
const msie11 = ua.indexOf("Trident/");
const msedge = ua.indexOf("Edge/");
const isIE = msie > 0 || msie11 > 0;
const isEdge = msedge > 0;
let signInType;
let accountId = "";
let credType = "";
// Create the main myMSALObj instance
const myMSALObj = new msal.PublicClientApplication(msalConfig);
// Register Callbacks for Redirect flow
myMSALObj.handleRedirectPromise().then(handleResponse).catch((error) => {
console.log(error);
});
function handleResponse(resp) {
alert("beginning handleResponse");
if (resp !== null) {
accountId = resp.account.homeAccountId;
credType = resp.account.credentialType;
myMSALObj.setActiveAccount(resp.account);
alert("response not null (already auth), accountId: " + accountId + ", credType: " + credType);
}
else {
const currentAccounts = myMSALObj.getAllAccounts();
if (!currentAccounts || currentAccounts.length < 1) {
alert("currentAccounts null/empty, going to signIn");
signIn("loginRedirect");
//return;
}
else if (currentAccounts.length > 1) {
// add choose account code here
alert("currentAccounts has multiple");
}
else if (currentAccounts.length === 1) {
const activeAccount = currentAccounts[0];
myMSALObj.setActiveAccount(activeAccount);
accountId = activeAccount.homeAccountId;
credType = activeAccount.credentialType;
alert("currentAccounts == 1; accountId: " + accountId + ", credType: " + credType);
}
}
}
async function signIn(method) {
signInType = isIE ? "loginRedirect" : method;
if (signInType === "loginPopup") {
return myMSALObj.loginPopup(loginRequest).then(handleResponse).catch(function (error) {
console.log(error);
});
}
else if (signInType === "loginRedirect") {
return myMSALObj.loginRedirect(loginRequest);
}
}
function signOut() {
const logoutRequest = {
account: myMSALObj.getAccountByHomeId(accountId)
};
myMSALObj.logoutRedirect(logoutRequest);
}
async function getTokenPopup(request, account) {
request.account = account;
return await myMSALObj.acquireTokenSilent(request).catch(async (error) => {
console.log("silent token acquisition fails.");
if (error instanceof msal.InteractionRequiredAuthError) {
console.log("acquiring token using popup");
return myMSALObj.acquireTokenPopup(request).catch(error => {
console.error(error);
});
}
else {
console.error(error);
}
});
}
// This function can be removed if you do not need to support IE
async function getTokenRedirect(request, account) {
request.account = account;
return await myMSALObj.acquireTokenSilent(request).catch(async (error) => {
console.log("silent token acquisition fails.");
if (error instanceof msal.InteractionRequiredAuthError) {
// fallback to interaction when silent call fails
console.log("acquiring token using redirect");
myMSALObj.acquireTokenRedirect(request);
}
else {
console.error(error);
}
});
}
So what happens upon going to this page is I get the two alerts saying "beginning handleResponse" and then "currentAccounts null/empty, going to signIn."
Then I'm redirected to MS sign-in page which I do with my work MS account. This succeeds.
I'm then redirected to the site I have listed in Azure Reply URLs, another page on our site that isn't secure and has no Azure login code.
The problem is I have no idea where to check that the user is signed in. If I try and check immediately after the signIn("loginRedirect") call in the handleResponse() function on the first page, the code never gets hit apparently. If I try and check on the page I'm redirected to, by instantiating the MSAL object and calling getAllAccounts(), this returns null.
It seems maybe on the page I'm redirected to I could call the ssoSilent() function (seems like this can check if user is authenicated?), but this requires a username/AccountId parameter. Well I don't frickin know this if a user hasn't (possibly) been authenticated yet! I don't really understand that.
So I don't know. It's probably something stupid I'm doing but I'm a pretty basic JavaScript person and am pretty much a total noob with authenication stuff. Any help would be epic.

Double request permission when using Oauth2 Google

I have issue when using "client:auth2:analytics" (Google Authenticate & Analytics). After i choose a account to verify, a dialog other will appear over authenticate dialog to request user allow some permission of app (look at the picture below), how way can auto allow all permisison ?
Request user confirm permissions.
Then, still request user confirm permissions.
https://www.googleapis.com/auth/analytics https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/analytics.manage.users
this.onLoad = function () {
const thiss = this;
window.onload = function () {
gapi.load('client:auth2:analytics', function () {
gapi.client.init({
'apiKey': thiss.config.apiKey,
'clientId': thiss.config.clientId,
'scope': thiss.config.scope,
}).then(function () {
thiss.handleBtnAuthClickStateful('reset');
thiss.GoogleAuth = gapi.auth2.getAuthInstance();
thiss.onAuthClick();
});
});
}
}
this.onAuthClick = function () {
const thiss = this;
$(document).on('click', `#${thiss.html.btnAuthAnalytics}`, function () {
thiss.handleOnAuthClick();
});
};
this.handleOnAuthClick = function () {
const thiss = this;
if (!thiss.handleValidate()) {
thiss.handleResetAuth();
thiss.GoogleAuth.signIn().then(function () {
if (thiss.GoogleAuth.isSignedIn.get()) {
thiss.handleAfterSignIn();
}
});
}
};
this.handleResetAuth = function () {
const thiss = this;
thiss.GoogleAuth.signOut();
thiss.GoogleAuth.disconnect();
};
This happens due to the un-verified domain name.
All you need to Verify your Domain name and Provide the App name and website address in Oauth console
Goto https://console.developers.google.com/
Domain Verification
Add Domain
Follow the steps (use one of the multiple methods provided by google)

Chrome Extension Storing Custom Object Type Strips Prototype Methods

I have created a custom object that I am using in my extension. When I save objects of the type Group (my object type) and then later pull those objects out of storage, it appears that the prototype methods are no longer present. Now I read in the documentation that objects serialize down to object literals {} and I can't seem to figure out how to keep the methods with the objects. I have provided the code of the group class below. When I try and use one of the methods from the file below on an object that was retrieved from storage, I get an error that the function does not exist. I used a for in loop to loop through all of the properties and the object has the name and urls property. Any help would be greatly appreciated!
Group.js:
// Create the Group class
var Group = function (name, urls) {
this.name = name;
this.urls = urls;
};
// Clears all urls from the group
Group.prototype.clearUrls = function () {
this.urls = [];
};
// Adds the specified url to the group
Group.prototype.addUrl = function (url) {
this.urls.append(url);
};
// Removes the specified url from the group
Group.prototype.removeUrl = function (url) {
this.urls = this.urls.filter(function(_url){
return url !== _url;
});
};
// Renames the group
Group.prototype.rename = function (name) {
this.name = name;
};
// Checks whether or not the group contains the specified url
// Returns either true or false
Group.prototype.containsUrl = function (url) {
var contains = false;
for (var i = 0; i < this.urls.length; i++) {
if (this.urls[i] === url) {
contains = true;
break;
}
}
return contains;
};
EDIT:
Here is the background.js script, it shows how the object is retrieved and then how it is called later in the script. It fails when it receives the addUrl message and attempts to call containsUrl() on currentGroup.
// Global Variables
var currentGroup;
var groups = [];
var options = [];
// Short hand function to save the current data to storage
var saveData = function () {
// Save default options, currrentGroup, and groups
chrome.storage.sync.set({'options': options, 'currentGroup': currentGroup, 'groups': groups}, function() {
if (chrome.runtime.lastError) {
console.error("Could not save because: " + chrome.runtime.lastError);
}
});
}
// On start query for saved data to make sure data is current
chrome.storage.sync.get(function(items) {
// Check if there are groups
if (items['groups']) { // Set the groups
groups = items['groups'];
} else { // Create default group and add to list of groups
currentGroup = new Group('default', []);
groups = [currentGroup];
}
// Check for current group, if none set to first available group
if (items['currentGroup']) {
currentGroup = items['currentGroup'];
console.log(Object.getOwnPropertyNames(currentGroup));
} else {
currentGroup = groups[0];
}
// Check for the options
if (items['options']) {
options = items['options'];
} else {
// No options, set the default options and save them
options['overrideHomepages'] = true;
}
saveData();
// After data has been fetched bring up the tabs
chrome.tabs.query({'currentWindow': true}, function(tabs) {
for (var i = 0; i < currentGroup.urls.length; i++) {
if (options['overrideHomepages']) {
if (tabs[i].url.length > 0) {
chrome.tabs.update(tabs[0].id, {'url': currentGroup.urls[i]});
} else {
chrome.tabs.create({'url': currentGroup.urls[i]});
}
} else { // Don't override homepages or open tabs
chrome.tabs.create({'url': currentGroup.urls[i]});
}
currentGroup.urls[i]
}
}); // End tabs.query
}); // End storage.sync.get
// Add message listener
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// If add url was sent
if (request.message === 'addUrl') {
console.log('Recieved message: ' + request.message);
// Check if the group contains the url already
if (currentGroup.containsUrl(sender.url) === false) {
currentGroup.addUrl(sender.url);
saveData();
sendResponse({'message': 'Saved ' + sender.url});
}
}
// If remove url was sent
if (request.message === 'removeUrl') {
// Check if the group contains the url
if (currentGroup.containsUrl(sender.url)) {
currentGroup.removeUrl(sender.url);
saveData();
sendResponse({'message': 'Removed ' + sender.url})
}
}
});
I believe currently chrome.storage is only used to save key-value items, not including prototype/functions. However, I didn't find any official docs about this.
One workaround would be using Group.prototype.containsUrl.call(currentGroup, sender.url), it allows you to invoke containsUrl with specifying the context for "this".

Exception in async function: Only on server, not on localhost

I am trying to get a route working that will function as a "Thank You" page for people who buy our products on an external store. On localhost everything works fine but on our staging server I get the following exception:
Exception in callback of async function: action#http://taskwunderstaging-45398.onmodulus.net/12289f8cf999b67e6c6c6dcad1a5a5eded53f4e2.js:517:468
Does anyone have an idea what might be causing this?
The code in question is as follows:
The Iron Router Endpoint
Router.route('/signup-partner', {
name: 'signupPartner',
where: 'client',
waitOn: function(){
return Meteor.subscribe("packages");
},
action: function() {
Meteor.logout(function() {});
var query = this.params.query;
//#TODO verify the query with the sha key!
var userInfo = {
email:query.email,
firstname:query.firstname,
lastname:query.lastname,
};
var companyInfo = {
companyName:query.company,
street:query.street,
city:query.city,
zipcode:query.zipcode,
country:query.country,
taxId:query.taxid
};
var orderInfo = {
product:query.product,
order:query.order,
};
// get the package from the database
orderInfo.package = Packages.findOne({digistoreId:orderInfo.product}).name;
orderInfo.tw_id = Packages.findOne({digistoreId:orderInfo.product})._id;
var data = {
userInfo:userInfo,
companyInfo:companyInfo,
orderInfo:orderInfo,
};
var that = this;
// check if the user account already exists and if so add the package and login the user
Meteor.call("partnerUserExists", data.userInfo.email,{orderId:data.orderInfo.order,tw_id:data.orderInfo.tw_id}, function(error, result){
if(result === "not-found"){
that.render('signup_partner',{
data: function(){
return data;
}
});
}
else {
Session.set('boughtPackage',result);
that.redirect('login');
}
});
}
});
the method that this route calls is as follows:
partnerUserExists: function(email,orderIds){
var user = Meteor.users.findOne({"emails.address":email}) || false;
console.log(user);
if(!user){
return "not-found";
}
if(_.indexOf(user.data.digistoreOrders,orderIds.orderId) > -1){
return orderIds.tw_id;
}
(function(callback){
// add the paidTask array if it doesnt exist
if (!user.data.paidTasks){
Meteor.users.update({_id:user._id},{$set:{"data.paidTasks":[]}});
}
// add the digistore array if it doesnt exist
if (!user.data.digistoreOrders){
Meteor.users.update({_id:user._id},{$set:{"data.digistoreOrders":[]}});
}
callback();
})(function(){
Meteor.users.update({_id:user._id},{$push:{"data.digistoreOrders":orderIds.orderId}});
Meteor.users.update({_id:user._id},{$push:{"data.paidTasks":orderIds.tw_id}});
return orderIds.tw_id;
});
}
check for error in your meteor.call. It should tell you if there is an error and why. If not, then try putting a console.log before each return. Overall, I see a lot of user.xx fields being accessed without checking whether that field is set. It could be one of those.

Categories