Does google one tap sign up works when user is not logged into his google account? - google-identity

Below code works fine but when opened from an incognito windows console only shows
GoogleYolo loaded.
No credentials
<html>
<head><title>My Yolo Login example</title>
<script src="/common.js"></script>
<script defer src="https://smartlock.google.com/client"></script>
<script>
const PUBLIC_CLIENT_ID =
'*******-**********.apps.googleusercontent.com';
const CONFIG = {
supportedAuthMethods: [
'googleyolo://id-and-password',
'https://accounts.google.com'
],
supportedIdTokenProviders: [{
uri: 'https://accounts.google.com',
clientId: PUBLIC_CLIENT_ID
}],
context:"signUp"
};
window.onGoogleYoloLoad = (googleyolo) => {
console.log("GoogleYolo loaded.");
var retrievePromise = googleyolo.retrieve(CONFIG);
retrievePromise.then((credential) => {
console.log(credential);
},
(error)=>{
if(error.type == "noCredentialsAvailable"){
console.log("No credential");
googleyolo.hint(CONFIG).then((credentials)=>{console.log(credentials);});}
});
};
</script>
</head>
</html>
How can I know that user doesn't have a google account and redirect/take other action for him to login to his google account.

I'm the product manager at Google for this library. We are working on some better support for users who are not signed in, but in the interim, when no Google Accounts are active and no credentials are available, you can simply show the traditional Google Sign-In button and have the user click to proceed through the flow to activate their Google Account in the browser.
https://developers.google.com/identity/sign-in/web/

window.onGoogleLibraryLoad = () => {
// initialize one-tap here
google.accounts.id.initialize({
client_id: "YOUR_ID.apps.googleusercontent.com",
callback: handleCredentialResponse,
itp_support: true,
auto_selec: true,
prompt_parent_id: 'g_id_onload',
cancel_on_tap_outside: false,
ux_mode: 'popup',
});
google.accounts.id.prompt((notification) => {
// if one-tap is not displayed show the google sign-in button (in private mode for example)
if (notification.isNotDisplayed()) {
console.log('not displayed');
google.accounts.id.renderButton(document.getElementById('g_id_onload'), {
type: 'standard',
shape: 'rectangular',
theme: 'outline',
text: 'continue_with',
size: 'large',
logo_alignment: 'center',
width: 300
})
}
});
};
function handleCredentialResponse(googleResponse) {
// do something after callback from Google
}
<script defer async src='https://accounts.google.com/gsi/client'></script>
<div id='g_id_onload'></div>

Related

How to check if user is logged from the middleware in Nuxt3 Auth0

I built a simple login page in Nuxt3 using Auth0 and it works. Now I am trying to build a middleware which will redirect users who are not authenticated to the login page. I am able to use this.$auth0.isAuthenticated variable on the login.vue page but not in my middleware because I get error "Cannot read properties of undefined (reading '$auth0')". How can I access isAuthenticated variable from the middleware?
this is login page: pages/login.vue
<template>
<div>
<p v-if="isAuthenticated">hey {{ user }}</p>
<p v-else>you are not authenticated</p>
<button #click="login">Log in</button>
<button #click="logout">logout</button>
</div>
</template>
<script>
export default {
data() {
return {
user: this.$auth0.user,
isAuthenticated: this.$auth0.isAuthenticated
};
},
methods: {
login() {
this.$auth0.loginWithRedirect();
},
logout() {
this.$auth0.logout({ returnTo: 'http://localhost:3000' });
}
},
};
</script>
and this is middleware page (middleware/auth.global.ts)
export default defineNuxtRouteMiddleware(() => {
if (this.$auth0.isAuthenticated) {
console.log('authenticated')
}
else {
console.log('not authenticated')
}
})
I tried the middleware approach but I've been facing the same problem.
I ended up with this in the <script setup> section of my layout:
import { authGuard } from "#auth0/auth0-vue";
const thisRouter = useRouter();
thisRouter.beforeEach(authGuard);
I feel this is not 100% correct but it seems to work.

Get Birthday Information using user.birthday.read scope

We have followed the steps mentioned as per the https://developers.google.com/identity/sign-in/web/server-side-flow. But while trying to fetch the date of birth information using 'scope': 'https://www.googleapis.com/auth/user.birthday.read', we are getting payload as below:
payload{"at_hash":"-mvIlEROpJsQSF9rQpRDfA","aud":"<CLIENT_ID>","azp":""<CLIENT_ID>"","email":"sample#gmail.com","email_verified":true,"exp":1628092721,"iat":1628089121,"iss":"https://accounts.google.com","sub":"108685651390298470023","name":"mnbvc plm","picture":"https://lh3.googleusercontent.com/a/AATXAJwejAC1r2SasgNdtqpd6f5q_Ih2-vDiTxELWDhg=s96-c","given_name":"mnbvc","family_name":"plm","locale":"en-GB"}
Please find below the index.html file we are using:
<!DOCTYPE html>
<html>
<head>
<meta name="google-signin-client_id" content="<CLIENT_ID>">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=renderButton" async defer>
</script>
<script>
function myFunction() {
auth2.grantOfflineAccess().then(signInCallback);
}
</script>
</head>
<body>
<button onclick="myFunction()" id="signinButton">Sign in with Google</button>
<script>
function renderButton() {
gapi.signin2.render('signinButton', {
'scope': 'https://www.googleapis.com/auth/user.birthday.read',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': start
});
}
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.getAuthInstance({
client_id: '<CLIENT_ID>',
scope: 'https://www.googleapis.com/auth/user.birthday.read',
access_type: 'offline'
});
});
}
function signInCallback(authResult) {
if (authResult['code']) {
var authcode = authResult['code'];
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'POST',
url: '/gplus.form?authcode='+authcode,
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
</body>
</html>
What else change is required at JAVA side to get the birthday information?

Facebook share on IOS safari not working with javascript SDK

I am using facebook share using javascript SDK where i need callback function in angular.js as below.
<button type="button" class="btn share-btn fb-share" ng-click="shareOnSocialMediaFB();"> </button>
Javascript code is as below (angularJs)
$scope.shareOnSocialMediaFB = function() {
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_US/sdk.js', function(){
FB.init({
appId: 'XXXXXXXXXXX', //replace with your app ID
version: 'v2.3'
});
FB.ui({
method: 'share',
mobile_iframe: true,
title: 'TEST',
description: "TEST",
href: 'www.example.com',
},
function(response) {
//
});
});
};
This is working fine with every desktop and browser. But for iphone safari browser FB is not getting open not in popup or in new tab.
How can i make it working so that on successful share i can do my stuff on callback function?

iOS web/native app Facebook Login Popup - FAILS?

I am trying to build a web app that will allow a user to login Facebook. Everything works in Firefox/Chrome/Safari (on the phone/tablet and on OSX).
When the App runs on the tablet (Native UIWebview and Web-app) it loads the first page perfectly.
When the user clicks the "connect with Facebook" button the app loads the Facebook logon page.
After the user logs in (again, in both a Native UIWebview and a web-app) the view turns white hanging on the URL: 'https://www.facebook.com/dialog/permissions.request?_path=permissions.request&app_id=[APP_ID]...' - this seems like it should not happen...
If I restart the app/web-app the user is logged in automatically, and redirected to the success page.
What I think is causing the problem
When you run the web page in the Firefox/Chrome/Safari browsers the Facebook login Dialog pops up as a popup or another tab (the latter on the native Safari browser).
I believe that this is a problem with this popup page and how the Javascript communicates with itself when a successful login takes place. Something with window.close where there is no root page to return to (as the web-app and UIWebview only have one instance of the webview)... maybe?
Failed work-around (UIWebview)
Since the app was hanging up on the previously mentioned URL I decided to add an if statement in shouldStartLoadWithRequest(...) to force the UIWebview to go to the success URL.
It loads the URL, but then before Facebook's Javascript SDK function FB.getLoginStatus function returns 'Connected' (It does return 'Connected' every time I've seen) The function FB.Event.subscribe('auth.logout' function() {...}); is fired.
I don't understand why it is logging the user out, then telling me that the user is connected (logged in) - in that order.
Any Ideas before I embark on trying to build this 100% native (and have to put up with apple's dev account and submitting the app)?
Login Script
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=APP_ID";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script>
var seccond_page = false;
window.fbAsyncInit = function() {
FB.init({
appId : '[APP_ID]',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.href = '<?= $success ?>';
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
FB.login(function(response) {
alert(response.status);
if (response.status) {
if (response.status == 'connected') {
window.location.href = '<?= $success ?>';
}
}
}, {scope: 'email, user_likes, user_status, user_birthday, user_location, publish_checkins'});
$(document).on('click', '#fb_login_button', function() {
FB.login();
});
};
</script>
Success Page
<script>
var fb_user_id = '';
var fb_access_token = '';
var user_location = '';
window.fbAsyncInit = function() {
FB.init({
appId : '[APP_ID]',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
FB.getLoginStatus(function(response) {
alert('Response - ' + response.status);
// the auth.logout is fired before the return of this in the failed fix
if (response.status === 'connected') {
if (response.authResponse) {
fb_user_id = response.authResponse.userID
fb_access_token = response.authResponse.accessToken;
}
}
});
FB.Event.subscribe('auth.logout', function(response) {
alert('logout - auth.logout');
// This event is fired before the above function in the failed fix
window.location.href = '<?= site_url('fb_login'); ?>';
});
FB.Event.subscribe('edge.create', function(response){
if (response == '<?= $like_url ?>') {
//action
}
});
};
</script>
All pages have the meta tag: <meta name="apple-mobile-web-app-capable" content="yes">
Facebook calls auth.logout just before auth.login for reasons not clear to me. You should inspect the response parameter before assuming that the user really has been logged out. Facebook docs state:
auth.logout - fired when the user logs out. The response object passed into the callback function looks like:
{
status: "", /* Current status of the session */
}
If you execute your logout handling only if response.status is really "", you may find that during login, it calls auth.login listeners immediately after calling the auth.logout listener. Your current auth.logout handling prevents you from noticing this, because the page reload stops JS and ajax executions.

Can Facebook's Javascript SDK work together with the older Facebook API?

Can the current Facebook Javascript SDK work with older Facebook API library?
Right now there is code to load the current Facebook Javascript SDK by:
window.fbAsyncInit = function() {
FB.init({appId: '218565466928', status: true, cookie: true,
xfbml: true});
};
// [...] initialize it
And there is code to use the old Facebook API by
init_fb_connect('Connect', 'XFBML', :js => :jquery, :app_settings=> '{ifUserNotConnected: fb_user_not_connected}' ) do
which is the Facebooker Rubygem. Can they work together somehow? If I have both, then the newly added "Like" button won't work. If I remove the older Facebooker code, then the "Login with Facebook" and "Share" button won't work. Any ideas?
Update: the older code do things like:
<a class="facebook-connect-link " href="#"
onclick="; FB.Connect.requireSession(fb_after_connect, null, true); return false;"
rel="nofollow">Sign in with Facebook</a>
and
<a href="#" onclick="FB.Connect.streamPublish('', {'name': 'Some product name' ...
and
$('.login-button').each(function() {
FB.XFBML.Host.addElement(new FB.XFBML.LoginButton(this));
})
Converting the JavaScript API is relatively easy. I am not sure how much your server side will be affected though. Here are the basic methods that you would probably need:
//Check if user is logged in right now.
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
} else {
// no user session available, someone you dont know
}
});
//Callback fired when user logs out/logs in.
FB.Event.subscribe('auth.sessionChange', function(response) {
// do something with response.session
});
//To force login (on login btn click).
FB.login(function(response) {
if (response.session) {
// user successfully logged in
fb_after_connect();
} else {
// user cancelled login
}
});
//Post to feed.
FB.api('/me/feed', 'post', { body: "message" }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
If you don't want to convert to the new API then you can embed like button as iframe. Sooner or later you would have to convert your project anyway so might as well do it now.

Resources