The event addUserSignedOut is triggered automaticity only when i use IE11 - javascript

I'm using oidc.js version:1.5.2 with aspnet webforms and for some reason when I navigate to my callback page, someone is triggering my addUserSignedOut event.
This strange behavior happens only in IE11 (in chrome,edge,firefox it works fine).
This is the Main page
var baseUrl = top.location.protocol + '//' + top.location.host;
var config = {
authority: "http://...",
client_id: 'xyz',
redirect_uri: baseUrl + '/myFolder/callback.html?',
post_logout_redirect_uri: baseUrl + '/myFolder/page.html?',
revokeAccessTokenOnSignout: true,
response_type: 'id_token token',
scope: 'abc',
prompt: 'true',
loadUserInfo: true,
automaticSilentRenew: true,
accessTokenExpiringNotificationTime: 1800,
};
var mgr = new Oidc.UserManager(config);
var isLoggedIn = function () {
return new Promise(function (resolve) {
mgr.getUser()
.then(function (token) {
console.log("getUser token=" + token);
resolve(token != null);
});
});
}
var doLogin = function () {
this.isLoggedIn().then(function (res) {
if (!res)
mgr.signinRedirect();
});
};
var doLogout = function () {
mgr.signoutRedirect();
};
var registerEvents = function () {
this.isLoggedIn().then(function (res) {
if (res) {
mgr.events.addUserSignedOut(function () {
Auth.userManager.removeUser();
return Auth.userManager.signoutRedirect();
});
}
});
};
registerEvents();
</script>
This is callback page
<script>
new Oidc.UserManager({ response_mode: "query" }).signinRedirectCallback().then(function (res) {
if (res) {
console.log("token = " + res.access_token);
window.location.href = "page.html";
}
})
.catch(function (e) {
console.error(e);
});
</script>

Perhaps the issue is related to IE security zones, you could try to go into Internet Options > Security and uncheck the "Enabled Protected Mode" for the "Internet" zone.

Related

Add video to Youtube playlist NodeJS

I am currently working through the code to programmatically create a youtube playlist using a nodejs server that I received from a previous question I had and am using the working code below to do so:
var google = require('googleapis');
var Lien = require("lien");
var OAuth2 = google.auth.OAuth2;
var server = new Lien({
host: "localhost"
, port: 5000
});
var oauth2Client = new OAuth2(
'YOUR_CLIENT_ID',
'YOUR_CLIENT_SECRET',
'http://localhost:5000/oauthcallback'
);
var scopes = [
'https://www.googleapis.com/auth/youtube'
];
var youtube = google.youtube({
version: 'v3',
auth: oauth2Client
});
server.addPage("/", lien => {
var url = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: scopes
});
lien.end("<a href='"+url+"'>Authenticate yourself</a>");
})
server.addPage("/oauthcallback", lien => {
console.log("Code obtained: " + lien.query.code);
oauth2Client.getToken(lien.query.code, (err, tokens) => {
if(err){
return console.log(err);
}
oauth2Client.setCredentials(tokens);
youtube.playlists.insert({
part: 'id,snippet',
resource: {
snippet: {
title:"Test",
description:"Description",
}
}
}, function (err, data, response) {
if (err) {
lien.end('Error: ' + err);
}
else if (data) {
lien.end(data);
}
if (response) {
console.log('Status code: ' + response.statusCode);
}
});
});
});
I am now moving on to the part of my project where I am in need of a way to add videos to this playlist once I have created it. The sample code that I am following along with is only written in JS and does not detail nodejs and I am therefore stuck on how to achieve this implementation with nodejs. How could I create a method like this (received from the JS implementation from the link above):
function addToPlaylist(id, startPos, endPos) {
var details = {
videoId: id,
kind: 'youtube#video'
}
if (startPos != undefined) {
details['startAt'] = startPos;
}
if (endPos != undefined) {
details['endAt'] = endPos;
}
var request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: playlistId,
resourceId: details
}
}
});
request.execute(function(response) {
$('#status').html('<pre>' + JSON.stringify(response.result) + '</pre>');
});
}
in the NodeJS language using the implementation I have already started?
I get what you mean now.If you want to add a video on your playlist then you can do that in Node using this.
youtube.playlistItems.insert({
part: 'id,snippet',
resource: {
snippet: {
playlistId:"YOUR_PLAYLIST_ID",
resourceId:{
videoId:"THE_VIDEO_ID_THAT_YOU_WANT_TO_ADD",
kind:"youtube#video"
}
}
}
}, function (err, data, response) {
if (err) {
lien.end('Error: ' + err);
}
else if (data) {
lien.end(data);
}
if (response) {
console.log('Status code: ' + response.statusCode);
}
});
If you want to render the result as HTML, First you need to use a view engine like (jade or pug) then create a template then lastly render it along with the response.
Base on your example you can do it this way:
First Create a template( Im using Pug) Save it as results.pug
html
head
title= title
body
h1= title
p=description
img(src=thumbnails.medium.url)
Then update your code below:
var google = require('googleapis');
var Lien = require("lien");
var OAuth2 = google.auth.OAuth2;
var pug = require('pug')
var server = new Lien({
host: "localhost"
, port: 5000,
views:{
path:__dirname,
name:'pug'
}
});
var oauth2Client = new OAuth2(
'YOUR_CLIENT_ID',
'YOUR_CLIENT_SECRET',
'http://localhost:5000/oauthcallback'
);
var scopes = [
'https://www.googleapis.com/auth/youtube'
];
var youtube = google.youtube({
version: 'v3',
auth: oauth2Client
});
server.addPage("/", lien => {
var url = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: scopes
});
lien.end("<a href='"+url+"'>Authenticate yourself</a>");
})
server.addPage("/oauthcallback", lien => {
console.log("Code obtained: " + lien.query.code);
oauth2Client.getToken(lien.query.code, (err, tokens) => {
if(err){
return console.log(err);
}
oauth2Client.setCredentials(tokens);
youtube.playlists.insert({
part: 'id,snippet',
resource: {
snippet: {
title:"Test",
description:"Description",
}
}
}, function (err, data, response) {
if (err) {
lien.end('Error: ' + err);
}
else if (data) {
//lien.end(data);
lien.render('results',data.snippet)
}
if (response) {
console.log('Status code: ' + response.statusCode);
}
});
});
});
The things that I update on your code are:
var server = new Lien({
host: "localhost"
, port: 5000,
views:{
path:__dirname,
name:'pug'
}
});
And
//lien.end(data);
lien.render('results',data.snippet)

conversationId - Value can't be NULL

In a Word-addin I'm am trying to fetch data from AAD with the help of ADAL and microsoft.graph. Here is the code:
from app.js
var app = (function () {
"use strict";
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: '<TENANT>',
clientId: '<CLIENTID>',
redirectUri: '<THE-APP-ADDRESS>',
postLogoutRedirectUri: window.location.origin,
endpoints: {
officeGraph: 'https://graph.microsoft.com',
},
callback: userSignedIn,
popUp: true,
cacheLocation: 'localStorage'
};
function signIn() {
authContext.login();
}
function userSignedIn(err, token) {
console.log('userSignedIn called');
// showWelcomeMessage();
if (!err) {
console.log("token: " + token);
showWelcomeMessage();
}
else {
console.error("error: " + err);
}
}
function showWelcomeMessage() {
var authContext = new AuthenticationContext(config);
var $userDisplay = $(".app-user");
var $signInButton = $(".app-login");
var $signOutButton = $(".app-logout");
// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
and main.js
function getDataFromSelection() {
var baseEndpoint = 'https://graph.microsoft.com';
var authContext = new AuthenticationContext(config);
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
authContext.acquireToken(baseEndpoint, function (error, token) {
if (error || !token) {
app.showNotification("Ingen token: ", "Du får logga in igen." + error); // + error
}
//var email = authContext._user.userName;
var url = "https://graph.microsoft.com/v1.0/" + config.tenant + "/me";
var html = "<ul>";
$.ajax({
beforeSend: function (request) {
request.setRequestHeader("Accept", "application/json");
},
type: "GET",
url: url,
dataType: "json",
headers: {
'Authorization': 'Bearer ' + token,
}
}).done(function (response) {
html += getPropertyHtml("Namn", response.displayName);
html += getPropertyHtml("Titel", response.jobTitle);
html += getPropertyHtml("Avdelning", response.officeLocation);
html += getPropertyHtml("Telefon jobb", response.businessPhones);
$("#results").html(html);
return postDataToContentControlers(response);
}).fail(function (response) {
// app.showNotification('Inloggningen slutade att fungera!', 'Du får logga ut och prova att logga in igen'); //response.responseText
}).always(function () {
console.log("AJAX is done!!")
})
});
} else {
app.showNotification('Error:', 'Något gick fel. Du får logga in igen.'); //result.error.message
}
}
);
}
On local wordklient it works but on Word online (Office 365 Pro Plus v.1609)
I get this when running the function getDataFromSelection();
Error from console
And right Before I login and i get confirmed and a token:
the parameter ConversationId is handled when you use microsoft-graph to GET mail-messages. Every mail has a conversationId... Why is it complaining about that regarding a GET against https://graph.microsoft.com/v1.0/me ?
Does anyone know how to get around this problem or Point me in the right direction? Thanks =)
EDIT: And I forgot to mention that this works online on Google Chrome but on Microsoft Edge The popup doesn't work at all regarding login Before even fetching any data. Only popup the addin again.

Google drive pdf not uploaded properly to s3 server

I am trying to upload the pdf file from google drive to s3 server, but its not uploaded properly.
I use google drive picker for get the file
Here is my
Here is my google drive picker code:- (Client side code)
<script type="text/javascript" src="https://apis.google.com/js/api.js"></script>
// The Browser API key obtained from the Google Developers Console.
// Replace with your own Browser API key, or your own key.
var developerKey = 'XXXXXXXXXX_ff_NX66eb-XXXXXXXXXXX';
// The Client ID obtained from the Google Developers Console. Replace with your own Client ID.
var clientId = "XXXXXXXXXX-hs4ujaro5sc3d0g8qndtcq2tl279cfm1.apps.googleusercontent.com"
// Replace with your own App ID. (Its the first number in your Client ID)
var appId = "XXXXXXXXXX";
// Scope to use to access user's Drive items.
var scope = ['https://www.googleapis.com/auth/drive'];
var pickerApiLoaded = false;
var oauthToken;
$scope.addGoogleDriveFile = function() {
if (!isValidSelectedCategories(getSelectedCategories())) {
return;
}
if (!isValidSelectedCategoriesNoapost(getSelectedCategories())) {
return;
}
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for searching images.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.View(google.picker.ViewId.DOCS);
var picker = new google.picker.PickerBuilder()
.enableFeature(google.picker.Feature.NAV_HIDDEN)
.setAppId(appId)
.setOAuthToken(oauthToken)
.addView(view)
.addView(new google.picker.DocsUploadView())
.setDeveloperKey(developerKey)
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
console.log(data);
addGoogleDrivePDF (data.docs);
}
}
var addGoogleDrivePDF = function (file) {
var pdfData = {
url: file[0].url
};
$http.post('/uploadto/s3/drtivepdf', pdfData )
.success((function (article) {
console.log(article);
}).error(function (error) {
console.log(article);
});
}
Here i am able to get the file url
Like :
https://drive.google.com/file/d/0B39VaBFZeygDNEVuWDYtYlgxNGhTeVdKNWtSX0tpT0FzeDRB/view?usp=drive_web
Here is my server side code
s3upload_rou.js file (router file)
app.post('/uploadto/s3/drtivepdf', function (req, res, next) {
next();
}, bookmark.addGoogleDrivePDF );
s3upload_ctrl.js file (controller file)
var async = require('async');
var config = require('../config');
var file = require('../libs/file');
exports.addDropboxBookmark = function (req, res, next) {
saveGoogleDrivePdf(req.body.url, function (err, pdfDetail) {
if (err) {
cb(err);
} else {
res.send(pdfDetail);
}
});
}
var saveGoogleDrivePdf= function (url, callback) {
async.waterfall([
function (cb) {
var fileDetails = {
url: url,
name: 'drive/' + url.toString().replace(/^(http|https):\/\//i, ""),
contentType: 'application/pdf'
};
file.uploadPdf(fileDetails);
cb(null, fileDetails);
},function (fileDetails, cb) {
console.log(fileDetails);
//create object for saving the pdf
var pdfDetail = {
pdf_url: fileDetails.url,
pdf_title: 'PDF FILE',
pdf_preview_image: config.defaultPreviewImageUrl,
pdf_file: fileDetails.name,
pdf_website: url.parse(url, false, true).host,
mode: 'pdf'
};
cb(null, pdfDetail );
}
], function (err, pdfDetail ) {
if (err) {
callback(err);
} else {
callback(null, pdfDetail );
}
});
}
Here is my file.js code:-'
var request = require('request');
var config = require('../config');
var url = require('url');
var http = require('http');
var pool = new http.Agent();
var streamingS3 = require('streaming-s3');
exports.uploadPdf = function (details, cb) {
var options = {
url: config.s3.url + 'upload/drive',
method: 'POST',
json: true,
body: details,
headers : { "x-api-key": config.s3.apiKey, "x-aws-bucket": config.aws.bucket, "Content-Type": 'application/json' },
agent: pool
};
request(options, function (err, res) {
if (err) {
console.log(err);
logger.log('error', "PDF Error: ", { error : err , details: details });
} else {
console.log(res.body);
logger.log('info', "UPLOAD PDF", { response : res.body });
}
});
};
Uploading is working fine, but when i am trying to view that file on S3, i am not able to open it.
Any reason ?
Thanks
To download the selected file with JS, use this
function downloadFile(file, callback) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
} else {
callback(null);
}
}

How to make wordpress.com login connect work with meteor

I'm following these tutorial:
https://developer.wordpress.com/docs/oauth2/
https://developer.wordpress.com/docs/wpcc/
https://github.com/Automattic/wpcom-connect-examples/blob/master/express.js/app.js
So I setup Meteor.loginWithWordpresscom with the following code:
Accounts.oauth.registerService('wordpresscom');
if (Meteor.isClient) {
Meteor.loginWithWordpresscom = function(options, callback) {
// support a callback without options
if (! callback && typeof options === "function") {
callback = options;
options = null;
}
var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback);
Wordpresscom.requestCredential(options, credentialRequestCompleteCallback);
};
} else {
Accounts.addAutopublishFields({
forLoggedInUser: ['services.wordpresscom'],
forOtherUsers: ['services.wordpresscom.username']
});
}
And then I request credential with the following code:
Wordpresscom = {};
Wordpresscom.requestCredential = function (options, credentialRequestCompleteCallback) {
if (!credentialRequestCompleteCallback && typeof options === 'function') {
credentialRequestCompleteCallback = options;
options = {};
}
var config = ServiceConfiguration.configurations.findOne({service: 'wordpresscom'});
if (!config) {
credentialRequestCompleteCallback && credentialRequestCompleteCallback(
new ServiceConfiguration.ConfigError());
return;
}
var credentialToken = Random.secret();
var loginStyle = OAuth._loginStyle('wordpresscom', config, options);
var loginUrl =
'https://public-api.wordpress.com/oauth2/authorize' +
'?client_id=' + config.clientId +
'&redirect_uri=http://localhost:3000/connected' +
'&response_type=token' +
'&grant_type=authorization_code' +
'&scope=global'
OAuth.launchLogin({
loginService: "wordpresscom",
loginStyle: loginStyle,
loginUrl: loginUrl,
credentialRequestCompleteCallback: credentialRequestCompleteCallback,
credentialToken: credentialToken,
popupOptions: {width: 900, height: 450}
});
};
At the server, I request accessToken and identity with following code:
Wordpresscom = {};
OAuth.registerService('wordpresscom', 2, null, function(query) {
var accessToken = getAccessToken(query);
var identity = getIdentity(accessToken);
return {
serviceData: {
id: identity.ID,
accessToken: OAuth.sealSecret(accessToken),
email: identity.email,
username: identity.username,
displayName: identity.display_name,
avatar: identity.avatar_URL
},
options: {profile: {
name: identity.display_name,
displayName: identity.display_name,
avatar: identity.avatar_URL
}}
};
});
var getAccessToken = function (query) {
var config = ServiceConfiguration.configurations.findOne({service: 'wordpresscom'});
if (!config)
throw new ServiceConfiguration.ConfigError();
var response;
try {
response = HTTP.post(
"https://public-api.wordpress.com/oauth2/token", {
params: {
code: query.code,
client_id: config.clientId,
client_secret: OAuth.openSecret(config.secret),
redirect_uri: 'http://localhost:3000/connected',
grant_type: 'authorization_code'
}
});
} catch (err) {
throw _.extend(new Error("Failed to complete OAuth handshake with WordPress.com. " + err.message),
{response: err.response});
}
if (response.data.error) { // if the http response was a json object with an error attribute
throw new Error("Failed to complete OAuth handshake with WordPress.com. " + response.data.error);
} else {
console.log('getAccessToken');
return response.data.access_token;
}
};
var getIdentity = function (accessToken) {
console.log('getIdentity');
try {
return HTTP.get(
"https://public-api.wordpress.com/rest/v1/me", {
headers: {
/*"User-Agent": userAgent,*/
"Authorization": 'Bearer ' + accessToken
},
params: {access_token: accessToken}
}).data;
} catch (err) {
throw _.extend(new Error("Failed to fetch identity from WordPress.com. " + err.message),
{response: err.response});
}
};
Wordpresscom.retrieveCredential = function(credentialToken, credentialSecret) {
return OAuth.retrieveCredential(credentialToken, credentialSecret);
};
When I fire Meteor.loginWithWordpresscom popup window show up to ask user whether to approve or deny my app with this link http://localhost:3000/connected?code=a8kiRGwRPC
I get code a8kiRGwRPC to request access_token
After I approve, it redirect to http://localhost:3000/connected#access_token=w%5EQ7CFcvZQx3t%28OjspIs84v13BsbyUGROzrYh3%23aiLJQ%25NB%2AZ7jMjNX2%29m7%23t5J4&expires_in=1209600&token_type=bearer&site_id=0
Just like that. No new user stored in Meteor.users database
Any help would be appreciated
Thanks

how to write blocking function in nodejs

hi i am trying to short my urls
function shorutrl(link)
{
var linkpost = JSON.stringify({longUrl:link});.
var optionslink = {
host: "www.googleapis.com",
port: 443,
method: 'POST',
path: "/urlshortener/v1/url",
headers: {
'Content-Type' : 'application/json'
}
};
optionslink.headers['Content-Length']=linkpost.length;
var linkreq = https.request(optionsimg, function(res) {
res.on('data', function (d) {
linkdata+=d;
});
res.on('end', function (x) {
try { return JSON.parse(linkdata).id; } catch(e){ return link; }
});
}).on('error', function (e) {
//console.log(e.message);
});
linkreq.write(optionslink);
linkreq.end();
}
function nonworking_givelink()
{
return shorutrl(txtlinks[Math.floor(Math.random() * txtlinks.length)]);
}
function working_givelink()
{
return txtlinks[Math.floor(Math.random() * txtlinks.length)];
}
nonworking_givelink returns undefined working_givelink returns link as normal
should i write a new function and pass paramters to that and generate new link and pass the paramters to another function is there no any easier way?
You shouldn't write blocking code in node.js, it goes against the very design of the system.
You need to pass a callback function which will be called with the new URL within your .on('end', ...) block.
Alternatively, wrap this up into a new object which itself emits events, e.g.:
var https = require('https');
var events = require('events');
function GoogleShortener() {
events.EventEmitter.call(this);
};
GoogleShortener.super_ = events.EventEmitter;
GoogleShortener.prototype = Object.create(events.EventEmitter.prototype, {
constructor: {
value: GoogleShortener,
enumerable: false
}
});
GoogleShortener.prototype.shorten = function(link) {
var self = this;
var data = JSON.stringify({longUrl: link});
var options = {
hostname: 'www.googleapis.com',
port: 443,
path: '/urlshortener/v1/url',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
var resp = '';
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function(d) {
resp += d;
}).on('end', function() {
try {
var id = JSON.parse(resp).id;
self.emit('success', id);
} catch (e) {
self.emit('error', e);
}
});
}).on('error', function(e) {
self.emit('error', e);
});
req.write(data);
req.end();
return self;
};
exports.shorten = function(link) {
return new GoogleShortener().shorten(link);
};
usage:
var g = require('gshort');
g.shorten('http://www.google.com/').on('success', function(link) {
console.log(link)
});
return doesn't return from the function you want it to return from. It returns from the function immediately around it. Consider:
function foo() {
var bar = function() {
return "baz"; // This does _not_ return from `foo`! It returns from `bar`
}
bar();
}
console.log(foo()) // undefined

Categories

Resources