Herer is my Google part
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().languageCode = 'zh-TW';
provider.addScope('profile');
provider.addScope('https://www.googleapis.com/auth/userinfo.profile');
provider.addScope('https://www.googleapis.com/auth/userinfo.email');
provider.addScope('https://www.googleapis.com/auth/plus.login');
provider.addScope('https://www.googleapis.com/auth/plus.me');
provider.addScope('https://www.googleapis.com/auth/user.birthday.read');
provider.addScope('email');
firebase.auth().signInWithPopup(provider).then(function(result) {
console.log(result.user)
}).catch(function(error) {
app.message.register = error.message;
});
Herer is my Facebook part
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('user_birthday');
firebase.auth().languageCode = 'zh-TW';
firebase.auth().signInWithPopup(provider).then(function(result) {
console.log(result.user)
}).catch(function(error) {
});
Those two part are not get the gender and birthday in console.log(result.user) is there missing some setting ? or having the wrong part? Any idea?
The access tokens returned result.credential.accessToken will provide access to these additional scopes. You would need to query the Google/Facebook API with that access token to get this data (specific to the additional requested scopes). By the way, some additional user info is now returned specific to IdP. Check content of result.additionalUserInfo.profile.
Related
Hello Im having and issue with Safari and Firebase's authentication process. The code works in Chrome but leaves a blank popup when using safari and doesn't redirect when using SignInWithRedirect. What am I missing? The console log shows all comments but the "Made it" one
Here's the code
var provider = new firebase.auth.GoogleAuthProvider();
console.log("FB");
firebase.auth().signInWithRedirect(provider);
console.log("Provider");
firebase
.auth()
.getRedirectResult()
.then(function (result) {
if (result.credential) {
console.log("Made it");
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// ...
}
// The signed-in user info.
var user = result.user;
})
.catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error code: " + errorCode + "\n" + "Error message:" + errorMessage);
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
console.log("done");
The issue was resolved. Seems like firebase as an entirety was having issues. I had to clear the cache in the preferences. Kinda silly but I followed the article below. Thanks self
Safari not updating
I'm essentially trying to have a website which authenticates the user's GitHub account through firebase, and then saves their username in a database - I specifically need the username for this. I have the authentication working but it seems that firebase doesn't have a way to access the username, only things such as the email, display name, etc. Currently I just want to save the username as a variable
I've come across this: https://developer.github.com/v3/users/#get-the-authenticated-user
I assume "login" is the username?
I'm relatively new to things though, and can't find any clear examples of how I would access this information with my token from firebase.
For reference, I have an index.html, linked to app.js, which contains all of my authentication code.
var provider = new firebase.auth.GithubAuthProvider();
provider.addScope('read:user');
//get elements
const authenticateBtn = document.getElementById('authbtn');
//add login event
authenticateBtn.addEventListener('click', e=>{
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a GitHub Access Token. You can use it to access the GitHub API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
//what I want to get
//var Username = ;
//some data I am able to get
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
//where I want to print the username
//console.log(userName);
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
})
I really just need a beginners explanation of if what I want to do is possible and if so, exactly what code I'd need where in my project.
Thanks!
So I ended up getting some help from a friend, here is my solution:
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a GitHub Access Token. You can use it to access the GitHub API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
var username;
var obj;
const Http = new XMLHttpRequest();
Http.open("GET", "https://api.github.com/user?access_token="+token);
Http.send();
Http.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
obj = JSON.parse(Http.responseText);
username = obj.login;
console.log(username);
}
}
}
I've followed the guide on https://github.com/gsuitedevs/apps-script-oauth2 for setting up the Oauth2 token for a google services very closely but i'm still not able to get the access token to work.
The error I'm receiving is Access not granted or expired. (line 454, file "Service", project "OAuth2")
Note* My project has already been whitelisted for the GMB API library and I have enabled it in the API console console. I retrieved a ClientID and ClientSecret from my project aswell.
//Oauth 2 Flow Start
function getGmbService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('gmb')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId('...')
.setClientSecret('...')
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
// Set the scopes to request (space-separated for Google services).
.setScope('https://www.googleapis.com/auth/business.manage')
// Below are Google-specific OAuth2 parameters.
// Sets the login hint, which will prevent the account chooser screen
// from being shown to users logged in with multiple accounts.
.setParam('login_hint', Session.getActiveUser().getEmail())
// Requests offline access.
.setParam('access_type', 'offline')
// Forces the approval prompt every time. This is useful for testing,
// but not desirable in a production application.
.setParam('approval_prompt', 'force');
}
function showSidebar() {
var gmbService = getGmbService();
if (!gmbService.hasAccess()) {
var authorizationUrl = gmbService.getAuthorizationUrl();
var template = HtmlService.createTemplate(
'Authorize. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
DocumentApp.getUi().showSidebar(page);
} else {
Logger.log("No Access")
}
}
function authCallback(request) {
var gmbService = getGmbService();
var isAuthorized = gmbService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
//Oauth2 Flow Finish
function testRequest() {
var gmbService = getGmbService();
var payload = {
"pageSize": 5
}
var options = {
"headers": {
"Authorization": 'Bearer ' + gmbService.getAccessToken()
},
"method": 'GET',
"payload": payload,
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch("https://mybusiness.googleapis.com/v4/accounts",options)
Logger.log(response);
}
CONTEXT
I'm working on Xcode (ios app) on an angularJS/ionic app, trying to use Firebase auth functions to login using Facebook.
To do that i'm using signInWithRedirect() and getRedirectResult(), it seems working until my code gets to getRedirectResult(), no errors shown but after access acceptance facebook is redirecting me on Safari to : localhost:8080/var/containers/Bundle/Application/******/testApp.app/www/index.html#/login instead of my app login page.
I setup the facebook app on the Developper Facebook website and set https://testApp-32338.firebaseapp.com/__/auth/handler into OAuth URI field.
QUESTION
Is there a file in Xcode or somewhere (.XML or something), where i must write something about this redirect ? How to use Facebook to sign in my ionic/ios app ?
Here is my code :
//********** EDIT 1 CODE **********//
function loginFacebook ()
{
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('user_birthday, email, public_profile');
firebase.auth().signInWithRedirect(provider);
// The only console.log() i can see in the console
console.log("0");
firebase.auth().getRedirectResult().then(function(result) {
console.log("1");
if (result.credential) {
console.log("2");
var user = result.user;
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
console.log("3");
}
// The signed-in user info.
var user = result.user;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
});
}
Edit 1 : (02/11/2018)
According to Firebase it seems to be a known problem, probably wkwebview is the main cause of this issue on an IOS/ionic app. In this link : https://ionicframework.com/docs/wkwebview/ ionic is speaking about "Cross-Origin Resource Sharing" (CORS), I'm really not familiar with this how could i "trap" the signInWithRedirect() result to change it to the required url ? Is this will fix my problem ? Is someone was already able to cope with this issue ?
Edit 2 : (02/12/2018)
Trying a new method, using the cordova-facebook4-plugin, everything seems working, even the redirect part to my app and collecting datas (name, birthday, token...etc). The unknown part is how to link my results to the firebase auth provider ? In Firebase doc (https://firebase.google.com/docs/auth/web/facebook-login) the method is to use signInWithRedirect() (see my first edit) or signInWithPopUp() (which is not working on phone app), there is a signInWithCustomToken(), but it doesn't work when i'm putting inside the Facebook given token. I also tried the universal-links method with unfortunately, same results. How do you guys would do this ? Is someone achieved the connexion between cordova-facebook4-plugin and Firebase ?
//********** EDIT 2 CODE **********//
function loginFacebook()
{
var fbLoginSuccess = function (userData) {
console.log("UserInfo: " + JSON.stringify(userData));
facebookConnectPlugin.getAccessToken(function(token) {
console.log("Token: " + token);
// What to do with this Token to link to Firebase ???
});
}
facebookConnectPlugin.login(["public_profile", "user_birthday"], fbLoginSuccess,
function (error) {
console.error(error)
}
);
}
Edit 3 : (02/14/2018) It's Working !!!
Finally is it working, thanks a lot to #mootrichard ! Here is my final working code :
//********** EDIT 3 CODE FINAL **********//
// SIGNIN WITH FACEBOOK4
function loginFacebook()
{
var provider = new firebase.auth.FacebookAuthProvider();
var fbLoginSuccess = function (userData) {
console.log("UserInfo: " + JSON.stringify(userData));
facebookConnectPlugin.getAccessToken(function(token) {
console.log("Token: " + token);
connectProvider(token);
});
}
facebookConnectPlugin.login(["public_profile", "user_birthday"], fbLoginSuccess,
function (error) {
console.error(error)
}
);
//CONNECT FACEBOOK TO THE FIREBASE PROVIDER
function connectProvider(access_token)
{
// Build Firebase credential with the Facebook access token.
var credential = firebase.auth.FacebookAuthProvider.credential(access_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).then(function(result) {
var firstName = result.displayName.split(' ').slice(0, -1).join(' ');
var lastName = result.displayName.split(' ').slice(-1).join(' ');
console.log("The firstName is : ", JSON.stringify(firstName));
console.log("The lastName is : ", JSON.stringify(lastName));
$state.go("anOtherPage");
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
});
}
I think you want to look at one of Firebase's advanced guides. Since you already have your token, you can simply create the Facebook Credentials using:
// Build Firebase credential with the Facebook access token.
var credential = firebase.auth.FacebookAuthProvider.credential(access_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
You can see their example at https://firebase.google.com/docs/auth/web/facebook-login#advanced-authenticate-with-firebase-in-nodejs.
I am using google login for custom website. here i wrote the code for it
var sOAuthServiceEndPoint = "https://accounts.google.com/o/oauth2/auth?scope=http://gdata.youtube.com https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&response_type=token&";
var sOAuthRedirectURL = "http://example.com/testpage/test.html";
var termsAndCondURL = "termsandcondition.html";
var sOAuthClientID = "294016263542.apps.googleusercontent.com";
var sAuthenticationURL = sOAuthServiceEndPoint + "redirect_uri=" + sOAuthRedirectURL + "&client_id=" + sOAuthClientID;
even i got an access token using below function
function fnOnLoad() {
//alert("Form Loaded");
var sAccessToken = '';
var params = {}, queryString = location.hash.substring(1),regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
if(params.error){
if(params.error == "access_denied"){
sAccessToken = "access_denied";
alert(sAccessToken);
}
}else{
sAccessToken = params.access_token;
alert(sAccessToken);
}
window.opener.fnAuthorisationSuccess(sAccessToken);
window.close();
}
It's working succesfully and redirect into the other page where I want. but my problem is how to retrive user login name..?
I am using javascript for it.
Thanks in Advance
This can be found in the documentation.
After your application acquires an access token and has (if necessary) verified it, you can use that access token when making requests to a Google API. If the https://www.googleapis.com/auth/userinfo.profile scope was included in the access token request, then you may use the access token to acquire the user's basic profile information by calling the UserInfo endpoint.
Endpoint: https://www.googleapis.com/oauth2/v1/userinfo
Returns basic user profile information, including name, userid, gender, birthdate, photo, locale, and timezone. If the https://www.googleapis.com/auth/userinfo.email scope was present in the request, then the user's email will also be present in the response. If the email has been verified, then there is also a field that indicates the email is a verified address.