Google sign-in sends multiple requests on redirect - servlets

I'm trying to implement Google sign-in on my web application, as an add-on to normal server-side authentication. The problem is,I'm not able to redirect the page to a Servlet to go to the user homepage. Instead, whenever I try to redirect ONCE,I get continuous requests to the next Servlet(I used print statements on the Servlet to check this).It seems as if the page reloads after every request sent to the Servlet. I also tried using form data to fix this, but that doesn't work either.
How do I stop this from happening? I'm a newbie, so any dumbing down will be much appreciated. In case this is a duplicate, please do send the link. I have tried to find a similar question, but have had no luck so far.
Note: I have removed all irrelevant lines of code.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id"
content="CLIENT_ID_HERE">
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
//document.cookie = "emailId=" + profile.getEmail();
redirectPost(profile.getEmail());
//window.location = "http://localhost:8080/auth/gmailhome";
}
function redirectPost(data) {
var inputElement = document.getElementById('emailId');
var form = document.getElementById("gmailLoginForm");
inputElement.value = data;
form.submit();
}
</script>
</head>
<body>
<form method="post" action="gmaillogin" id="gmailLoginForm">
<input type="hidden" id="emailId" name="emailId">
</form>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
</body>
</html>

I figured out how to solve this issue, and it just occurred to me that I can leave this here in case someone needs it in the future.
The problem we have is that onSignin() gets called as long as the user is signed in, and the status of the user doesn't reflect that they are signed in. I'm not sure why the state isn't changed automatically-perhaps there is some other purpose to this, or this is just low-priority right now.
So, what we do is add a listener that monitors whether or not the user is signed-in.
Something like this
function onLoad() {
gapi.load('auth2', function () {
gapi.auth2.init();
gapi.auth2.isSignedIn.listen(function (isSignedIn) {
this.setState({ status: isSignedIn })
})
})
}

Related

Reload the "Sign In With Google" button if user changes locale

I can't find any documented way to reload the new "Sign in With Google" button in JavaScript.
I have to remove the script tag and the "button" div then re-add them both.
Does anyone know of a better way to do this?
Have you looked at the JS renderButton method ?
Assuming you have something like this to initialize the library and display the button in JS, you might be able to update locale in the second parameter to renderButton and call the method again to switch languages.
<html>
<body>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<script>
function handleCredentialResponse(response) {
console.log("Encoded JWT ID token: " + response.credential);
}
window.onload = function () {
google.accounts.id.initialize({
client_id: "YOUR_GOOGLE_CLIENT_ID",
callback: handleCredentialResponse
});
google.accounts.id.renderButton(
document.getElementById("buttonDiv"),
{ theme: "outline", size: "large", locale: "the new locale" }
);
google.accounts.id.prompt(); // also display the One Tap dialog
}
</script>
<div id="buttonDiv"></div>
</div>
</body>
</html>
Obviously, you'd call renderButton a second time from outside of the window.onload example above, I didn't go as far as showing that in the code sample though.

Google Analytics API OAuth after clicking "Allow" cannot connect to local host

I'm trying to obtain an access token for Google Analytics API.
After creating a project in the developers console and granting acess to the Analytics API I reached the "create credentials" step and created new credentials for a web application.
On these credentials I set the Javascript origins to http://localhost:8080 and also http://localhost:5000. Then I set authorized redirect URIs to http://localhost:8080/oauth2callback as well as http://localhost:5000/oauth2callback.
Then, when I attempt to authorize I'm asked to enter my clientId and secret, which I do, then new browser tab opens and I'm asked to choose an account and then after that select "Allow".
Then, when I click "Allow" I'm taken to this page:
I also tried creating credentials for an application type of "other" but the exact same thing happened.
I've found numerous posts on stack overflow about this but none of the answers were able to solve my problem. Not sure which other info to provide. I even tried clearing history and using different browsers but with no success.
How can I give my application authorization to Google Analytics using OAuth?
This issue has nothing to do with localhost or your redirect uris or JavaScript origins. The issue is that your code is not set up to handle the call back from the authentication server. It would have helped if you had posted your code so it will be hard to know what the problem might be.
You should check the official example here Hello analytics js tutorial
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Analytics Reporting API V4</title>
<meta name="google-signin-client_id" content="<REPLACE_WITH_CLIENT_ID>">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>
<h1>Hello Analytics Reporting API V4</h1>
<!-- The Sign-in button. This will run `queryReports()` on success. -->
<p class="g-signin2" data-onsuccess="queryReports"></p>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
// Replace with your view ID.
var VIEW_ID = '<REPLACE_WITH_VIEW_ID>';
// Query the API and print the results to the page.
function queryReports() {
gapi.client.request({
path: '/v4/reports:batchGet',
root: 'https://analyticsreporting.googleapis.com/',
method: 'POST',
body: {
reportRequests: [
{
viewId: VIEW_ID,
dateRanges: [
{
startDate: '7daysAgo',
endDate: 'today'
}
],
metrics: [
{
expression: 'ga:sessions'
}
]
}
]
}
}).then(displayResults, console.error.bind(console));
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>
</body>
</html>

How do I make my firebase database public

I have a database in firebase and I want to make it public like https://publicdata-transit.firebaseio.com/sf-muni
What I see here they have a prefix "pulicdata", How do I get it?
A publicly accessible read-only dashboard, like the one you're referring to, is only available for apps managed by Firebase themselves. You cannot enable it on your own applications.
This won't do any formatting (you can make it pretty if you want), but this will take your snapshot and just put it up on the screen for anyone to see as long as you have your settings for read as true.
<html>
<head>
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
</head>
<body>
<div id='displaySnapshotDiv'></div>
<script>
var myDataRef = new Firebase('https://MY-FIREBASE-NAME-GOES-HERE.firebaseio.com/');
myDataRef.on('value', function(snapshot) {
displaySnapshot(snapshot.val());
});
function displaySnapshot(snapshot) {
$('<div/>').text(JSON.stringify(snapshot)).appendTo($('#displaySnapshotDiv'));
$('#displaySnapshotDiv')[0].scrollTop = $('#displaySnapshotDiv')[0].scrollHeight;
};
</script>
</body>
</html>
If you want it to be a little more readable, you could do something like:
<!-- language: lang-html -->
<html>
<head>
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
</head>
<body>
<div id='displaySnapshotDiv'></div>
<script>
var myDataRef = new Firebase('https://MY-FIREBASE-NAME-GOES-HERE.firebaseio.com/');
myDataRef.on('child_added', function(snapshot) {
displaySnapshotNeatly(snapshot.val());
});
function displaySnapshotNeatly(snapshot) {
$('<div/>').text(JSON.stringify(snapshot)).appendTo($('#displaySnapshotDiv'));
};
</script>
</body>
</html>
Here is the second one working in JSFiddle: https://jsfiddle.net/lukeschlangen/rzfn45pz/
And here is the second one with your firebase data (please tell me the security settings for writing are set to something other than true?): https://jsfiddle.net/lukeschlangen/rzfn45pz/2/
It seems like you might want to do some formatting, but this is displaying all of the data.
The data can be available public if you change your database rules to true or use the auth token for authentication. But since you do not want to authenticate access, all you simply need to do is Make you access rules public
for more information check out: https://firebase.google.com/docs/reference/rest/database/
enter image description here

Send notification to user on facebook for app request?

I have encountered a lot of questions for the same but no where have been given any concrete answer
I am sending invites to Facebook friends say a , b ,c and what should happen is a notification should be displayed for the app request
I have seen this in case of PININTEREST which does the same however I am trying to achieve this in asp.net. I found this demo which is very close to what I want to achieve
The code I have so far is :
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>Request Example</title>
</head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<p>
<input type="button"
onclick="sendRequestToRecipients(); return false;"
value="Send Request to Users Directly"
/>
<input type="text" value="User ID" name="user_ids" />
</p>
<p>
<input type="button"
onclick="sendRequestViaMultiFriendSelector(); return false;"
value="Send Request to Many Users with MFS"
/>
</p>
<script>
FB.init({
appId : 'XXXXX',
});
function sendRequestToRecipients() {
var user_ids = document.getElementsByName("user_ids")[0].value;
FB.ui({method: 'apprequests',
message: 'XXXXXXX',
to: user_ids,
}, requestCallback);
}
function sendRequestViaMultiFriendSelector() {
FB.ui({method: 'apprequests',
message: 'My Great Request'
}, requestCallback);
}
function requestCallback(response) {
// Handle callback here
}
</script>
</body>
</html>
EDIT:
When i send the request the user does not get it ... No error is displayed either
Here are two things that might be causing your requests not to go through -
Missing or incorrect canvas URL
Application is in sandbox mode
An application that sends requests to users must have a canvas URL specified in the application's settings. When a user acts on a request (accepts it) he/she is redirected to the application and specifically to the canvas URL. By not specifying a canvas URL your request is deemed invalid by Facebook as there is no where to redirect the user to. The canvas URL can not be apps.facebook.com/namespace because your application does not sit on Facebook's domain. You have to set the URL to your domain. The page that you redirect to should again redirect the user back to your application :
if(!strpos($_SERVER['HTTP_REFERER'],"apps.facebook.com")) {
header("location: "._fb_app_path);
exit();
}
An application in sandbox mode when the user being invited is not listed in the appropriate "roles" group in the application settings. Applications in sandbox mode are only accessable to users who are developers, administrators or testers of that application.
I believe the correct method (at least what we use) is:
function invoke_app_request(){
var receiverUserIds = FB.ui({
method: 'apprequests',
message: 'MESSAGE',
data: '',
max_recipients: AN_INT //this is optional
},
function(response) {
//whatever you do here
}
);
}
I read somewhere (don't take it 100%), that displaying notifications on invites is based on Facebook algorithms and it's not displayed on all apps. It has to do something with app activity and history.

Using the Facebook API after JavaScript Login

This is something I have been trying to figure out, but I am not sure exactly how to do it. I have a flex application that logs into facebook, but after that I can't access any of the facebook api. Right now I am using this HTML to log in:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<!-- Include support librarys first -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
//This example uses the javascript sdk to login before embedding the swf
var APP_ID = "[My App ID Here]";
var REDIRECT_URI = "http://apps.facebook.com/isotesthoskins/";
var PERMS = "publish_stream,offline_access"; //comma separated list of extended permissions
function init() {
FB.init({appId:APP_ID, status: true, cookie: true});
FB.getLoginStatus(handleLoginStatus);
}
function handleLoginStatus(response) {
if (response.session) { //Show the SWF
//A 'name' attribute with the same value as the 'id' is REQUIRED for Chrome/Mozilla browsers
swfobject.embedSWF("isotest.swf", "flashContent", "760", "500", "9.0", null, null, null, {name:"flashContent"});
} else { //ask the user to login
var params = window.location.toString().slice(window.location.toString().indexOf('?'));
top.location = 'https://graph.facebook.com/oauth/authorize?client_id='+APP_ID+'&scope='+PERMS+'&redirect_uri='+REDIRECT_URI+params;
}
}
$(init);
</script>
And everything logs in fine, but when I try this in the application after I am logged in, nothing happens.
Facebook.api("/me", function(response){
changeText.text = response.name;
});
I don't need to init because it was done by the javascript login, right? I might be wrong about that though.
Looks like you are calling the API using the Flex SDK.
That is not going to work, as the token is not shared between JS and Flex.
You should login on the Flex side or thunk into the JS to make the call.

Resources