Double request permission when using Oauth2 Google - javascript

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)

Related

Is it possible to trigger a flow based on a condition within a function for SMS routing

I have a simple flow that posts incoming SMS messages to slack. I also have a function that allows me to send SMS messages and receive them. (I.E if the SMS is from MY_NUMBER and the message starts with +12121212: then it will send the message to +12121212.
If the message is not from MY_NUMBER it will forward the SMS to MY_NUMBER)
I would like the function to trigger a flow instead of forwarding a message to MY_NUMBER.
I would like to trigger my flow after the function has run:
e.g
exports.handler = function(context, event, callback) {
const MY_NUMBER = '+0000000000000';
let twiml = new Twilio.twiml.MessagingResponse();
if (event.From === MY_NUMBER) {
const separatorPosition = event.Body.indexOf(':');
if (separatorPosition < 1) {
twiml.message('You need to specify a recipient number and a ":" before the message.');
} else {
const recipientNumber = event.Body.substr(0, separatorPosition).trim();
const messageBody = event.Body.substr(separatorPosition + 1).trim();
twiml.message({ to: recipientNumber }, messageBody);
}
} else { ***MY FLOW SHOULD BE TRIGGERED HERE***
// the above line should replace `twiml.message({ to: MY_NUMBER }, `${event.From}: ${event.Body}`);`
}
callback(null, twiml);
};
You can trigger Studio flows from Twilio Functions via the following code snippet:
exports.handler = function (context, event, callback) {
const client = context.getTwilioClient();
client.studio.v2.flows('<Flow ID>')
.executions
.create({ to: recipientNumber, from: MY_NUMBER })
.then(execution => {
return callback(null, "hello"); // You could return something else as well
}
};
And you can find the ID of your flow in the console (or when you click on the root element and check the Flow Configuration):

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.

Using YouTube data api within chrome extension embedded iframe

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.

Can't send a GET-request with value from session-storage which is stored in a variable

I am working with angularjs and I am trying to access a value stored in vm.userid to the server side. I want to store a value from session-storage to vm.userid and then send it with the API request. I have checked my session-storage and the value I seek is indeed there. My value doesn't show up on the server-side, but a couple of minutes later it comes back empty (userid: " ").
This is the function in the StatisticsController:
(function () {
'use strict';
angular
.module('app')
.controller('StatistikController', StatistikController);
StatistikController.$inject = ['$location', 'AdminService','FlashService'];
function StatistikController($location, AdminService, FlashService) {
var vm = this;
vm.logout = logout;
initController();
function initController() {
loadStat();
}
function loadStat() {
vm.userid = angular.fromJson(sessionStorage.getItem('userid'));
AdminService.Stat(vm.userid)
.then(function (allStats) {
vm.allStats = allStats;
});
}
This is were the userid item is set to sessionStorage (which is in a different controller):
function loadUserid() {
UserService.GetUserid($rootScope.globals.currentUser.username)
.then(function (userid) {
vm.userid = userid;
sessionStorage.setItem('userid', angular.toJson(vm.userid));
});
}

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