Google Analytics Embed API: How to Auto-Authenticate? - google-analytics

I'm using the Google Analytics Embed API to embed some GA data on a custom dashboard. I'm using the method from the demo site:
https://ga-dev-tools.appspot.com/embed-api/
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container',
clientid: 'MY CLIENT ID',
});
This works fine. But it requires the user to authenticate before they can see the data. How do I get around this or auto-authenicate using this method (so anyone that can access the page doesn't have to login)?

I want to use Google Analytics Embed in my admin dashboard. After hours, searching similar posts on stackoverflow, and any other sites found by google search, i have solved my auth problem. Then i want to share.
Firstly, you know, you need some credentials. get your client_id and client_secret keys from https://console.developers.google.com. Add your site(example.com) to authenticated js source... and follow directions...
Secondly, go to https://developers.google.com/oauthplayground/ and select api (Google Analytics Reporting API v4) check https://www.googleapis.com/auth/analytics and https://www.googleapis.com/auth/analytics.readonly
And this is important: Before pressing Authorize Apis button, you should press settings button on top rigth side of page. then check "Use your own OAuth credentials" on settings popup and write your own client_id client_secret
Now you can press Authorize Apis button.
Then press "Exchange authorization code for tokens" button and copy refresh token code. Seems like 1/gwPrtXcdqpC_pDXXXXXXXXXXXXXXXXXzvVA.
So you have client_id, client_secret and refresh_token(taken by your own auth via settings popup)
Let see javascript code:
of course, add
<script>
(function (w, d, s, g, js, fs) {
g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } };
js = d.createElement(s); fs = d.getElementsByTagName(s)[0];
js.src = 'https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); };
}(window, document, 'script'));
</script>
Then you can use this script as example:
<script>
//CX Google Auth Process
var client_id = "111XXXXXXXXXXXXXXXXson.apps.googleusercontent.com";
var client_secret = "edXXXXXXXXXXXXXXXXabW";
function CXAuth(parameters) {
var credits= { client_secret: client_secret, grant_type: 'refresh_token', refresh_token: '1/AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXi7', client_id: client_id };
$.ajax({
type: "POST",
url: "https://www.googleapis.com/oauth2/v4/token",
contentType: "application/x-www-form-urlencoded",
data: credits,
dataType: "json",
success: function (credits) {
//console.log("CX Auth success");
gapi.analytics.auth.authorize({
serverAuth: {
"access_token": credits.access_token,
"expires_in": credits.expires_in,
"token_type": credits.token_type
},
container: 'embed-api-auth-container', //Your auth div id in html
clientid: client_id,
clientsecret: client_secret
});
}, error: function (xhr, textStatus, errorThrown) {
console.log("cx ajax post error:" + xhr.statusText);
}
});
}
gapi.analytics.ready(function () {
CXAuth();
//CX Get your ids no from https://ga-dev-tools.appspot.com/query-explorer/
var report = new gapi.analytics.report.Data({
query: {
ids: 'ga:18XXXXX', //Your ids no
//CX ga:visits,ga:sessions,ga:users for Tekil kullanıcı Sayısı-Unique user count
metrics: 'ga:pageviews', // Not unique user count
dimensions: 'ga:date',
'start-date': '2018-01-01',
'end-date': 'today'
}
});
var total = 0;
report.on('success', function handleCoreAPIResponse(resultsAsObject) {
if (resultsAsObject.rows.length > 0) {
resultsAsObject.rows.forEach(function pushNumericColumn(row) {
total = Number(total) + Number(row[1]);
});
document.getElementById("totalCounter").textContent = total;
}
});
report.execute();
var dataChart = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:18XXXXX', // <-- Replace with the ids value for your view.
'start-date': '30daysAgo',
'end-date': 'today',
'metrics': 'ga:sessions,ga:users',
'dimensions': 'ga:date'
},
chart: {
'container': 'site_statistics', //Your div id
'type': 'LINE',
'options': {
'width': '100%'
}
}
});
//CX Responsive Google Charts
window.addEventListener('resize', function () {
dataChart.execute();
});
$(document).ready(function () {
dataChart.execute();
});
});
</script>
and finally in your html like this:
<div id="embed-api-auth-container"></div>
<div id="site_statistics" class="chart"> </div>
<div id="totalCounter">0</div >
if all steps correct, you can get auto refresh token via js on your Admin Dashboard without pressing sign in button manually everytime.

Essentially, you're asking about authorizing server side on behalf of your visitors.
Various forms of this question have been asked before, so rather than re-answer I'll just send you some links:
Using Google Analytics to show subset of data for customers of web application using embed api
Google Analytics Embed API: How to retireve access token?
And here's the documentation for the auth method, which discusses the serverAuth option:
https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference#auth

I would suggest you follow this:
Go to this website: Google Analytics
SignUp for a Google Analytics Account
Go to the Admin Tab
Create a new Property (put your website URL)
Under new Property go to Tracking Info > Tracking Code, and there is a piece of code
Copy it and put in every JS file of each page you want to track in your site
Go to Reporting Tab on Google Analytics and on the left side click on Real-Time
Start seeing real-time data of visitors of your page

Related

Scraping an ASP.NET website with NodeJS

i am trying to login to my supplier website programatically and get the resseller price by code. i have my username and password provided by the supplier to use in the website which is powred by ASP.NET. i tried to use the request module but got no luck with it.
this the code i used so far :
var request = require('request');
var j = request.jar();
var request = request.defaults({ jar : j }) //it will make the session default for every request
//...
request({
url:"https://www.XXXXX.com/login.aspx",
method:"POST",
form:{
ctl00$cpholder$txtUserName:"YYYYYYYY",
ctl00$cpholder$txtPassword:"ZZZZZZZZ"
}
},
function(err,response,body){
console.log(err);
// here i try to access the product page like a reseller
request({
url:"https://www.XXXXXX.com/productdetails.aspx?id=20000028&itemno=90NB0CL1-M08420",
method:"GET",
}, function(err, response, body){
console.log(err);
//Some logic
});
});
}
this is the login form code ( in pastebin because it is very long )
https://pastebin.com/kwuRdLX4
please help

Fullcalendar + Private google calendar

I m using full calendar for a web app project and I sync it with google calendar of my client, but for the moment only public calendar.
Is there any way to sync with a private calendar ?
Note : We use 0auth to identify and sync with Google account.
Thanks
I think it would work with private calendar using the correct authorization.
Authorizing requests with OAuth 2.0
All requests to the Google Calendar API must be authorized by an authenticated user.
Here is a sample create by Alexandre:
<script type="text/javascript">
var clientId = '<your-client-id>';
var apiKey = '<your-api-key>';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
GeneratePublicCalendar();
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
// Step 4: Load the Google+ API
gapi.client.load('calendar', 'v3').then(function() {
// Step 5: Assemble the API request
var request = gapi.client.calendar.events.list({
'calendarId': '<your-calendar-id(The #gmail.com>'
});
// Step 6: Execute the API request
request.then(function(resp) {
var eventsList = [];
var successArgs;
var successRes;
if (resp.result.error) {
reportError('Google Calendar API: ' + data.error.message, data.error.errors);
}
else if (resp.result.items) {
$.each(resp.result.items, function(i, entry) {
var url = entry.htmlLink;
// make the URLs for each event show times in the correct timezone
//if (timezoneArg) {
// url = injectQsComponent(url, 'ctz=' + timezoneArg);
//}
eventsList.push({
id: entry.id,
title: entry.summary,
start: entry.start.dateTime || entry.start.date, // try timed. will fall back to all-day
end: entry.end.dateTime || entry.end.date, // same
url: url,
location: entry.location,
description: entry.description
});
});
// call the success handler(s) and allow it to return a new events array
successArgs = [ eventsList ].concat(Array.prototype.slice.call(arguments, 1)); // forward other jq args
successRes = $.fullCalendar.applyAll(true, this, successArgs);
if ($.isArray(successRes)) {
return successRes;
}
}
if(eventsList.length > 0)
{
// Here create your calendar but the events options is :
//fullcalendar.events: eventsList (Still looking for a methode that remove current event and fill with those news event without recreating the calendar.
}
return eventsList;
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
});
}
function GeneratePublicCalendar(){
// You need a normal fullcalendar with googleApi when user isn't logged
$('#calendar').fullCalendar({
googleCalendarApiKey: '<your-key>',
...
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
Or
Perform Google Apps Domain-Wide Delegation of Authority
In enterprise applications you may want to programmatically access users data without any manual authorization on their part. In Google Apps domains, the domain administrator can grant to third party applications domain-wide access to its users' data — this is referred as domain-wide delegation of authority. To delegate authority this way, domain administrators can use service accounts with OAuth 2.0.
For additional detailed information, see Using OAuth 2.0 for Server to Server Applications
Hope this helps!
I have tried in the backend with php, use the google php client library to get the events and then put it into fullcalendar. This way, it works.

FullCalendar with private google calendar event

I currently using google calendar on my website with the iframe you can insert. I tested Fullcalendar and I like what you can do with it.
But I would like to do same as the embed calendar, I would like to be able to create private event (not calendar, events). The sharing settings of the calendar is on public, but when using chrome, you can log with your google account and with the embed calendar you can see private event (if you have access to the calendar).
Is that possible with Fullcalendar ?
I figure out how to connect via OAUTH and get the private event when you are authentified.
By clicking on a button, you can connect to a google account (If already connected in browser, no button will appear and you will be log automaticly).
I follow this google example
<script type="text/javascript">
var clientId = '<your-client-id>';
var apiKey = '<your-api-key>';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
GeneratePublicCalendar();
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
// Step 4: Load the Google+ API
gapi.client.load('calendar', 'v3').then(function() {
// Step 5: Assemble the API request
var request = gapi.client.calendar.events.list({
'calendarId': '<your-calendar-id(The #gmail.com>'
});
// Step 6: Execute the API request
request.then(function(resp) {
var eventsList = [];
var successArgs;
var successRes;
if (resp.result.error) {
reportError('Google Calendar API: ' + data.error.message, data.error.errors);
}
else if (resp.result.items) {
$.each(resp.result.items, function(i, entry) {
var url = entry.htmlLink;
// make the URLs for each event show times in the correct timezone
//if (timezoneArg) {
// url = injectQsComponent(url, 'ctz=' + timezoneArg);
//}
eventsList.push({
id: entry.id,
title: entry.summary,
start: entry.start.dateTime || entry.start.date, // try timed. will fall back to all-day
end: entry.end.dateTime || entry.end.date, // same
url: url,
location: entry.location,
description: entry.description
});
});
// call the success handler(s) and allow it to return a new events array
successArgs = [ eventsList ].concat(Array.prototype.slice.call(arguments, 1)); // forward other jq args
successRes = $.fullCalendar.applyAll(true, this, successArgs);
if ($.isArray(successRes)) {
return successRes;
}
}
if(eventsList.length > 0)
{
// Here create your calendar but the events options is :
//fullcalendar.events: eventsList (Still looking for a methode that remove current event and fill with those news event without recreating the calendar.
}
return eventsList;
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
});
}
function GeneratePublicCalendar(){
// You need a normal fullcalendar with googleApi when user isn't logged
$('#calendar').fullCalendar({
googleCalendarApiKey: '<your-key>',
...
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
And in your google api console, make sure in API & Auth -> ID
OAuth Javascript origin is set properly (Like http://localhost
https://localhost if you are working on a local website)
Leave Redirection and API referent empty.
Fullcalendar is a front-end solution only. Logging into a google account and any other authentication isn't part of it.
That said, it can be connected to a google calendar, but only if it's a public google calendar. If you want to interface it to a private google calendar, you would have to build in that functionality.
If you can get the gcal events with JS and handle authentication, getting them into FullCalendar is easy. But that first part takes a few steps. Take a look at the google calendar api docs for instruction.

How to correctly login user in mobile app built with PhoneGap

Im building a mobile app on a PhoneGap. I've created several static HTML pages (stored on the phone locally) and trying to load some data from server using AJAX.
$( document ).bind( "mobileinit", function() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
$(document).ready(function () {
ajaxDeferred = $.ajax({
url: 'http://example.com/api/isAuthorized'
type: method,
data: parameters,
timeout: 40000
});
ajaxDeferred
.done(function(data) {
alert(data.result);
})
.fail(onFailHandler);
});
On a server side I have this code
public ActionResult IsAuthorized()
{
FormsAuthentication.SetAuthCookie("shade", true);
return this.Json(
new
{
result = this.HttpContext.User.Identity.IsAuthenticated
},
JsonRequestBehavior.AllowGet
);
}
I expect:
On the first run recieve "False" result since user is not authorized
On the second run recieve "True", because of SetAuthCookie
When I try it in a browser, it works as expected.
But whatever I run mobile app i alwayes recieve False, like cookies are not being tranfered.
So the question is how to correctly login user with AJAX, is it possible?
What are best practises? For unknown reason this simple scenario is not covered by PhoneGap manuals.
Ok, I found an answer:
$(document).ready(function () {
...
});
is not suitable. Instead one have to use
document.addEventListener(
"deviceready",
function() {
... at this point cookies are working fine!
},
false);
Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers are not required as well as other cross-domain techniques

How to connect with new Facebook C# SDK v5.0?

I've been using the old v3.0 C# SDK for some time and Facebook have decided to deprecate that API and also block it so I can no longer use it. I'm trying to upgrading to v5.0 but it seems a lot more different and I can't get it to authenticate.
All I need is a Facebook login button which people click, login and allow permissions to my app (which works) but then I want to be able to call Get() on the C# SDK in the code behind to get their friends. This is what I have in my aspx page which works fine to allow them to login:
<input type="button" id="fblogin" value="Login to Facebook" disabled="disabled"/>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: 'myappid',
cookie: true,
xfbml: true,
oauth: true
});
function facebooklogin() {
FB.login(function(response) {
if (response.authResponse) {
// user authorized
// make sure to set the top.location instead of using
var accessToken = response.authResponse.accessToken;
window.location.reload();
} else {
// user cancelled
}
},
{
scope: 'publish_stream'
});
};
$(function() {
// make the button is only enabled after the facebook js sdk has been loaded.
$('#fblogin').attr('disabled', false).click(facebooklogin);
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
However when I'm trying to connect to the Facebook client as below it throws an error which says
(OAuthException) An active access token must be used to query
information about the current user."} System.Exception
{Facebook.FacebookOAuthException}
FacebookClient client = new FacebookClient(myappid, mysecretkey)
SomeDictionary object = client.Get("/me/friends");
What am I missing to get this active authtoken? How can I access it in the code behind? Also what's the difference between using FacebookClient and FacebookWebClient?
In your web.config file you also have to set:
<facebookSettings appSecret="your app secret" appId="your app id" />
and to get the current user:
var facebookApp = new FacebookApp();
facebookApp.Api("/4");

Resources