Cancel button for google plus sign-in - javascript

In twitter when the user pressed the cancel button it is redirected to this URL:
URL/verify?denied=TOKEN
therefore you can determine it by the denied in the URL.
In google+ sign-in, is there a way to detect the cancel button in the sign-in page or detect the close button for the javascript or jquery?

In the callback function, an error code is returned if the user rejects the consent dialog.
An example callback that checks for access_denied, indicating the user rejected the consent dialog:
function onSignInCallback(authResult) {
if (authResult['access_token']) {
// success
} else if (authResult['error']) {
if (authResult['error'] == 'immediate_failed'){
// This is perfectly normal, the user reached the site and was not logged in
// However, if the user should be signed in on this page, it would be
// appropriate to have an error here
}
if (authResult['error'] == 'access_denied'){
// The user cancelled out of the dialog.
}
// There was an error, which means the user is not signed in.
// As an example, you can handle by writing to the console:
console.log('There was an error: ' + authResult['error']);
}
console.log('authResult', authResult);
};

Related

Google OAuth disconnect, signOut but GoogleAuth.isSignedIn.get() = true?

Here is my code:
function googleLogOut() {
debugAlert("googleLogOut:Begin");
GoogleAuth.disconnect();
GoogleAuth.signOut().then(function () {
debugAlert("googleLogOut:Logout Completed, current login status = " + GoogleAuth.isSignedIn.get());
userNotLoggedIn();
debugAlert("googleLogOut:Exit");
});
}
According to my understanding, the disconnect revokes the authorization which the currently signed-in user has granted to my application and the signOut should log the user out of his Google account, basically backing out the OAuth signin which the user went through originally in order to gain access to my application.
However, immediately after GoogleAuth.signOut(), GoogleAuth.isSignedIn.get() evaluates to true - see alert dialog image:
Alert Dialog
Actually, as it turns out, the user is still logged in to his Google account so technically isSignedIn.get() is returning the correct value. I confirmed this by opening a new browser tab and going to gmail - clearly I was still logged in. More to the point though, what this code does is revoke all of the permissions which the user has granted to my application - that is the essence of this logout function. To test this -
GoogleAuth.currentUser.get().hasGrantedScopes(SCOPE) == false
So the compound test for whether a Google account is logged in to my application is:
GoogleAuth.isSignedIn.get() == true && GoogleAuth.currentUser.get().hasGrantedScopes(SCOPE) == true
Here's the modified logout function. (Same functionality, just modified the debug statements to show the revocation of the scopes privileges.)
function googleLogOut() {
debugAlert("googleLogOut:Begin");
GoogleAuth.disconnect();
GoogleAuth.signOut().then(function () {
debugAlert("googleLogOut:Logout Completed, current login status = " + GoogleAuth.isSignedIn.get());
if (GoogleAuth.isSignedIn.get()) {
debugAlert("googleLogOut:Logout Completed, current SCOPE status = " + GoogleAuth.currentUser.get().hasGrantedScopes(SCOPE));
}
userNotLoggedIn();
debugAlert("googleLogOut:Exit");
});
}
Here's a completely different way to do this. I found this to be much more reliable.
logoutWindow = window.open("https://accounts.google.com/SignOutOptions", "_blank", "toolbar=no,width=600,height=400");
I just open a window to Google's account management page. When the user signs out, they are signed out from my application as well.
As the icing on the cake, when I trap the user logged out event in my application I close the window - if the user is logging out through a window which my application has invoked:
try {
logoutWindow.close();
}
catch (err) {
// nothing...
}
Use GoogleAuth.isSignedIn.listen(listener) - when your listener is called the state of GoogleAuth objects has already been updated.

How to determine if google auth2.signIn() window was closed by the user?

Im implementing auth using this and am currently showing a loading icon in React when a user clicks the button to sign in and the auth2 account selection/login window shows.
However if a user closes the window, there doesnt seem to be any event fired i.e the signIn() function which returns a promise never resolves, I would have thought google would return an error for this promise if the window is closed. As a result there is no way for me to stop showing the loader icon and reshow the login menu.
I was wondering if anyone had a solution for this?
I try to modifiy my code that call Google OAuth 2.0 window.
You only have to add extra AJAX method that cover what is Google OAuth error result.
gapi.auth2.getAuthInstance().signIn()
Change it to this one,
gapi.auth2.getAuthInstance().signIn().then(function(response){
//If Google OAuth 2 works fine
console.log(response);
}, function(error){
//If Google OAuth 2 occured error
console.log(error);
if(error.error === 'popup_closed_by_user'){
alert('Oh Dude, Why you close authentication user window...!');
}
});
That's it...
For more detail about Google OAuth 2.0 information, you can visit this link.
https://developers.google.com/api-client-library/javascript/samples/samples#authorizing-and-making-authorized-requests
Sample code on JavaScript:
https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html
Although the API provides a mechanism for detecting when the user clicks the Deny button, there is not a built-in way for detecting that the user abruptly closed the popup window (or exited their web browser, shut down their computer, and so on). The Deny condition is provided in case you want to re-prompt the user with reduced scopes (e.g. you requested "email" but only need profile and will let the user proceed without giving you their email).
If the response from the sign-in callback contains the error, access_denied, it indicates the user clicked the deny button:
function onSignInCallback(authResult) {
if (authResult['error'] && authResult['error'] == 'access_denied') {
// User explicitly denied this application's requested scopes
}
}
You should be able to implement sign-in without detecting whether the window was closed; this is demonstrated in virtually all of the Google+ sample apps. In short, you should avoid using a spinner as you're doing and instead should hide authenticated UI until the user has successfully signed in.
It's not recommended you do this, but to implement detection of the pop-up closing, you could do something like override the global window.open call, then detect in window.unload or poll whether the window was closed without the user authenticating:
var lastOpenedWindow = undefined;
window.open = function (open) {
return function (url, name, features) {
// set name if missing here
name = name || "default_window_name";
lastOpenedWindow = open.call(window, url, name, features);
return lastOpenedWindow;
};
}(window.open);
var intervalHandle = undefined;
function detectClose() {
intervalHandle = setInterval(function(){
if (lastOpenedWindow && lastOpenedWindow.closed) {
// TODO: check user was !authenticated
console.log("Why did the window close without auth?");
window.clearInterval(intervalHandle);
}
}, 500);
}
Note that as I've implemented it, this mechanism is unreliable and subject to race conditions.

I want to call Google Plus callback function when clicking on the Google Plus button

I have used a Google Plus button in my project [built in CodeIgniter]. Here I have added the following code.
<span id="signinButton">
<span
class="g-signin gooConnect"
data-callback="signinCallback"
data-clientid="my_project_client_id"
data-cookiepolicy="single_host_origin"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-scope="https://www.googleapis.com/auth/userinfo.email">
</span>
</span>
Then I added the Javascript code provided by Google.
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function signinCallback(authResult) {
if (authResult['access_token']) {
$.ajax({
url:base_url+'index.php/user/getUserProfile',
type:'POST',
data:{'access':authResult['access_token']},
beforeSend : function(){
$("#loadingImageBeforeResult").show('slow');
},
success : function(resp){
$("#loadingImageBeforeResult").hide('slow');
if( resp == 'exist' ){
window.location.href=base_url+'index.php/user/my_deals';
} else {
$('#link_for_geniepage').trigger('click');
}
},
error : function(resp){}
});
} else if (authResult['error']) {
// There was an error.
// Possible error codes:
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatially log in the user
// console.log('There was an error: ' + authResult['error']);
}
}
</script>
It's working fine for me, but if I log in my Gmail account in a separate tab and then I go to my login page, the callback function just auto logins with my Gmail credentials and redirects me to my dashboard.
I want that unless I click on that Google Plus button, the callback function should not work. How can I do this? Please help me.
In the signinCallback(authResult) function, you should at first check if the user is signed in and then you should check, if the method value is AUTO or PROMPT. PROMPT is exactly what you want because it is returned when user clicks on the sign in button. Here's the code:
function signinCallback(authResult) {
if (authResult['status']['signed_in'] && authResult['status']['method'] == 'PROMPT') {
// User clicked on the sign in button. Do your staff here.
} else if (authResult['status']['signed_in']) {
// This is called when user is signed in to Google but hasn't clicked on the button.
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
From the docs, it looks like the signin button, when used this way, will always attempt an immediate validation. Since you're already signed in to google and have authorized the app, google automatically signs you in and sends you to your dashboard.
I'd suggest not using that sample code. You could, instead, use other parts of the Google Javascript API (https://developers.google.com/+/web/api/javascript) Make a Google sign in button that's a normal button. When that's clicked, call gapi.auth.authorize() to log the user in. Then nothing happens until they click the button, and when they do, it either asks for approval/login or just signs the user in automatically.

fb login popup block

I am making using fb login feature but problem comming to me is that whenever I click on the fb login button before page media loading is completed, it blocks the popup for fb login but if I click on fblogin after a second passed to loading event it works
Here is the function I am using:
function fb_login() {
var email='';
console.log(loginClassbackQueue);
// console.log('user wants to login with fb');
FB.getLoginStatus(function(response) {
if(response.status!='connected'){
FB.login(function(response) {
// console.log(response);
if (response.authResponse) {
// console.log('user logged in successfully');
// console.log(response);
email = update_f_data_login(response);
$('#fb_login_popup, #popup_overlay').hide();
// loginme(email);
}
else {
loginClassbackQueue = [];
// console.log('user failed to login');
}
// console.log('fb login completed successfully');
}, {scope:"email,user_birthday,user_likes,user_location,friends_likes,publish_actions"}
);
}
else{
// console.log('logged in and connected');
email = update_f_data_login(response);
$('#fb_login_popup, #popup_overlay').hide();
}
});
}
The same action when I do on this site http://fab.com/ it open popups always never block a popup.
You cannot call FB.login from the callback of FB.getLoginStatus.
Browsers tend to block popup windows of the popup is not spawned as an immediate result of a user's click action.
Because FB.getLoginStatus does an ajax call and you call FB.login on it's response, the popup that would open as a result of this call is blocked.
A solution to your problem would be to call FB.getLoginStatus on page load and use the response inside your fb_login() method.
It's perfectly fine to call FB.login from the callback of FB.getLoginStatus, as long as you are confident that the login status has already been loaded internally. To do this, use one of these:
FB.init({..., status: true, ... }).
FB.getLoginStatus(...)
FB.login(...)
FB.ui(...)
Technically all of these options use FB.ui. The async process has to complete, which could take a few seconds. As long as you have already used one of the methods above to make a cross-domain call with FB, and that async process has completed, getting the login status will not make an async call, and the popup will not be blocked.
You should also make sure not to specify true for the second parameter, as in FB.getLoginStatus(..., true);.
Make sure you set status to true, this will fixed popup blocker issue.
window.fbAsyncInit = function() {
FB.init({
appId : '{your-app-id}',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.5', // use graph api version 2.5
status : true // set this status to true, this will fixed popup blocker issue
});
I had the same problem and it kick my head for 3 days. I did stumble on the above mentioned solutions and they worked in Firefox and Edge but in Chrome not matter what ever i did i still got blocked left right and center.The other problem was when i called the function from a button press event the login dialog was not block but it didn't get any responses after the login dialog closes for further actions so i got stuck. So my solution is as follow, but you don't need to press the login in button it will redirect to the FB-login page without a button press event, and on return continue with all the other sdk steps. Just add this to your code and see if it helps, from there adjust according to your need
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
document.getElementById('Image2').style.display = "none";
document.getElementById('mail').style.display = "in-line";
testAPI();
} else {
// The person is not logged into your app or we are unable to tell.
window.alert("Faça login no facebook antes de continuar - Obrigado");
window.location.href = 'https://www.facebook.com/dialog/oauth' +
'?client_id=55215442252214521548' +
'&scope=public_profile,email,user_friends' +
'&redirect_uri=' + encodeURIComponent(document.URL);
document.getElementById('Image2').style.visibility = "hidden";
document.getElementById('mail').style.display = "in-line";
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
}

Is it possible to add a redirect to webkitNotfications?

The webkitNotifications API in Chrome won't let me redirect to a page when the user clicks on the notification.
Is there any way I can make it work like Growl on the Mac, with a notification popping up, and then the user clicking on it to be redirected? For example, the user receives a new message, is notified via webkitNotifications, clicks on the message and is taken to message.php.
Maybe you should try this (onclick)
function setNotifJL(strtitre,strmsg) {
if (window.webkitNotifications.checkPermission() == 0 ) {
Window.webkitNotifications.createNotification('../mypic.gif',strtitre, strmsg);
n.show();
n.onclose = notify;
n.onclick = nclicked;
}
}
function notify() {location.href='<whereever you want';}

Categories

Resources