Make google auth request gapi.auth without a popup - javascript

Need to make auth request in js but the browser does not support popups. Is there any way to redirect to a new url or show the request in the in html5 page of the application

By using this code check if user authorized your app
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, callbackAuthResult);
Note: immediate:true
if you set immediate true then it wont show popup.
You see? You don't open the popup, and manage the stuff in the callback. This callback is usually used for post-processes. Here we use it for authenticating.
in callbackAuthResult:
callbackAuthResult = function (authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.display = 'none';
// do your processing here
} else {
authorizeButton.style.display = 'block';
authorizeButton.onclick = callbackAuthClick;
}
}
callbackAuthClick = function (event) {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: false
}, handleAuthResult);
return false;
}

Related

how to link a new user to google analytics property/view using javascript

My requirement is, I need to add a new email id to an existing google analytics account's property.
function insertPropertyUserLink() {
var request = gapi.client.analytics.management.webpropertyUserLinks.insert(
{
'accountId': '123456',
'webPropertyId': 'UA-123456-1',
'resource': {
'permissions': {
'local': [
'EDIT',
'MANAGE_USERS'
]
},
'userRef': {
'email': 'liz#gmail.com'
}
}
});
request.execute(function (response) { // Handle the response. });
}
Above code i got from google documentation and i am using the following code for authorization:
<script>
var GoogleAuth;
var SCOPE = 'https://www.googleapis.com/auth/analytics.manage.users';
function handleClientLoad() {
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Retrieve the discovery document for version 3 of Google Drive API.
// In practice, your app can retrieve one or more discovery documents.
var discoveryUrl = 'https://www.googleapis.com/analytics/v3/management/accounts/';
// 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({
'apiKey': 'mykey',
'discoveryDocs': [discoveryUrl],
'clientId': 'myclientId',
'scope': SCOPE
}).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.)
var user = GoogleAuth.currentUser.get();
setSigninStatus();
// Call handleAuthClick function when user clicks on
// "Sign In/Authorize" button.
$('#sign-in-or-out-button').click(function () {
handleAuthClick();
});
$('#revoke-access-button').click(function () {
revokeAccess();
});
});
}
function handleAuthClick() {
if (GoogleAuth.isSignedIn.get()) {
// User is authorized and has clicked 'Sign out' button.
GoogleAuth.signOut();
} else {
// User is not signed in. Start Google auth flow.
GoogleAuth.signIn();
}
}
function revokeAccess() {
GoogleAuth.disconnect();
}
function setSigninStatus(isSignedIn) {
var user = GoogleAuth.currentUser.get();
var isAuthorized = user.hasGrantedScopes(SCOPE);
if (isAuthorized) {
$('#sign-in-or-out-button').html('Sign out');
$('#revoke-access-button').css('display', 'inline-block');
$('#auth-status').html('You are currently signed in and have granted ' +
'access to this app.');
} else {
$('#sign-in-or-out-button').html('Sign In/Authorize');
$('#revoke-access-button').css('display', 'none');
$('#auth-status').html('You have not authorized this app or you are ' +
'signed out.');
}
}
function updateSigninStatus(isSignedIn) {
setSigninStatus();
}
</script>
<button id="sign-in-or-out-button"
style="margin-left: 25px">
Sign In/Authorize
</button>
<button id="revoke-access-button"
style="display: none; margin-left: 25px">
Revoke access
</button>
<div id="auth-status" style="display: inline; padding-left: 25px"></div><hr>
<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>
I have changed the API key and client id with mine and enabled the Analytics API for the app in console. Can anyone help me to integrate the above two code snippets to a single one and can be able to add a new user to analytics property.
To solve this: **gapi.client.analytics is undefined**
Change:
`gapi.load(**'client:auth2'**, initClient);`
to
gapi.load(**'client:analytics'**, initClient);
It worked for me.

Insert Event in Google Calendar With Javascript

My client ID is correct but hidden in this example.
I need help posting an event to my calendar. I believe I have the code correct but I need someone else's eyes.
I just need to post a event to the calendar.
SCOPES = ["https://www.googleapis.com/auth/calendar"]
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* #param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadCalendarApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* #param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
/**
* Load Google Calendar client library. List upcoming events
* once client library is loaded.
*/
function loadCalendarApi() {
gapi.client.load('calendar', 'v3', listUpcomingEvents);
}
/**
* Print the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
var event = {
"summary":"Here"
"description":"Now"
"start":
{
"dateTime":"2016-04-21T12:00:00.000-07:00"
"timeZone":"America/Los_Angeles"
}
"end":
{
"dateTime":"2016-04-21T12:30:00.000-07:00"
"timeZone":"America/Los_Angeles"
}
};
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': event
});
request.execute(function(event) {
appendPre('Event created: ' + event.htmlLink);
});
}

Google Sign-in: how to avoid popup dialog if user is already signed in by using listeners?

Right now I'm using auth2.attachClickHandler(element, {}, onSuccess, onError);. It works, but if I've already signed in, the dialog box opens and closes right away which is rather ugly. Is there a way around this using listeners?
I played around the example but I'm not sure if listening for changes to current user is all I need, and my check of googleUser seems risky.
auth2 = gapi.auth2.init({client_id: 'xxxxx'});
auth2.currentUser.listen(function (user) {
googleUser = user;
if (typeof(googleUser.getBasicProfile()) !== 'undefined')
document.getElementById('signupAsGoogle').addEventHandler('click', popuplateForm);
else
auth2.attachClickHandler(document.getElementById('signupAsGoogle'), {}, onSuccess, onError);
Is there a better way? Thanks
Here is what I did to solve the same problem!
auth2 = gapi.auth2.init({
clientid: '${clientId}',
cookiepolicy: '${cookie_policy}',
});
auth2.currentUser.listen(function (googleUser) {
if (googleUser.isSignedIn()) {
// do your login(googleUser) function
} else {
auth2.attachClickHandler("your button", {},
function (googleUser) {
// do your login(googleUser) function
}, function (error) {
});
}
});

Google Calendar Api Intermittent 401

I have a simple code that Logs into to Google to use the Google Calendar API and creates and event for the user. The code works fine but every so often I get a 401 - Login Required error from Google. If I open the developer console in the browser and try again it works... which is very odd
var scopes = 'https://www.googleapis.com/auth/calendar';
var clientId = 'CLIENT_ID';
var apiKey = 'API_KEY';
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 = $('#calendarAuth');
var calendarFrame = $('#calendarFrame');
if (authResult && !authResult.error) {
authorizeButton.remove();
calendarFrame.show();
calendarFrame.attr('src', calendarFrame.attr('src')); //Hack to reload the iframe
} else {
authorizeButton.show();
calendarFrame.hide();
}
}
function Authorize() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function GoogleScheduleFollowup(followup) {
gapi.client.load('calendar', 'v3', function () {
var request = gapi.client.calendar.events.insert({
"calendarId": "primary",
resource: {
"summary": followup.title,
"start": {
"dateTime": window.GetFullDateString(followup.date, followup.time)
},
"end": {
"dateTime": window.GetFullDateString(followup.date, followup.time)
}
}
});
request.execute(function (resp) {
console.log(resp);
});
}
Everything seems to be well configured in the API Console, and I'm sure we haven't reached the quota (either total or requests per second). As an example today I have made 133 requests of which 36 failed with this error.
I have tried to call gapi.auth.authorize every 10 minutes to see if the problem was a session timeout, and as I read in another question I tried removing this line gapi.client.setApiKey(apiKey);, both without success

Google Analytics API Javascript: 403 Forbidden Error

For the love of Bob, someone please help me out...
I'm trying to use the Google Analytics API (Javascript Library) to get some Analytics info. I've registered the my app and set up the oauth2 stuff. I can return the access token jsut fine, but when i try to send a request to actually grab Analytics info, it returns a 403 forbidden error. Here's my code:
function auth() {
var config = {
'client_id': '[my_client_id]',
'scope': 'https://www.googleapis.com/auth/analytics.readonly'
};
gapi.auth.authorize(config, function() {
var retObj = gapi.auth.getToken();
makeRequest(retObj.access_token);
});
}
function makeRequest(accessToken) {
var restRequest = gapi.client.request({
'path': '/analytics/v3/data/ga',
'params': {
'access_token': accessToken,
'ids': 'ga:[table_number]',
'metrics': 'ga:pageviews,ga:uniquePageviews',
'start-date': '2011-11-01',
'end-date' : '2011-12-01'
}
});
restRequest.execute(function(resp) { console.log(resp); });
}
The auth() function is executed via a button click and like I said, getting the access token is not the issue. It's when I execute the makeRequest function that I get the 403 error. Anyone have any clue as to what the deal is here?
Thanks to anyone who answers in advance!!
In my case I was getting 403 Forbidden because in my browser I was logged into Google with an account that didn't have permission to the GA profile I was trying to access. Before discovering that issue, I was having trouble with the tableID for which Aksival posted the solution above.
Here's my working code for your reference:
<script type="text/javascript">
//GET THESE HERE https://code.google.com/apis/console/
var clientId = 'YOURCLIENTIDHERE';
var apiKey = 'YOURAPIKEYHERE';
//GET THIS HERE http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';
//INITIALIZE
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) {
if (authResult) {
makeApiCall();
} else {
requestAuth();
}
}
function requestAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
}
function makeApiCall() {
gapi.client.load('analytics', 'v3', function() {
var request = gapi.client.analytics.data.ga.get({
'ids':'ga:YOURTABLEIDHERE', 'start-date':'2012-01-01', 'end-date':'2012-02-01', 'metrics':'ga:visits', 'metrics':'ga:visits', 'start-index':1, 'max-results':1000
});
request.execute(function(resp) { console.log(resp.totalsForAllResults); });
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
I had the same issue. Turns out I was passing in the wrong [table_number].
You need to query
accounts/[account-id]/webproperties/[webproperties-id]/profiles
and use the 'id' field of the appropriate property. (I was using the internalWebPropertyId from the webproperties query at first, which is why it was failing.)
Works like a charm now.

Categories