I am a little stuck and would like to get some help. I have two html files index.html and welcome.html. I also have two js files, script.js and welcome.js. My problem is, I am trying to display an object but it is displaying undefined.
I am using firebase google sign in and I am trying to display the name of the user but when I do that in welcome.html, i get undefined as a result.
Here is my script.js code:
var username;
login.addEventListener('click' ,function(){
if(!firebase.auth().currentUser)
{
const provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider)
.then((result) => {
var token = result.credential.accessToken;
window.sessionStorage.setItem("token", token);
console.log(result);
username = result.user.displayName;
console.log("Success!");
doWelcome();
}).catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
if(errorCode === 'auth/account-exists-wtih-different-credential'){
alert("You have already signed up with a different auth provider for that email");
}else{
console.error(error);
}
});
}else{
firebase.auth().signOut();
}
})
var doWelcome = function(){
window.location.replace("welcome.html");
//alert(username);
}
welcome.js code:
const welcomeTitle = document.getElementById('welcomeTitle'); //from welcome.html
welcomeTitle.style.fontSize ="50px";
welcomeTitle.innerHTML = "Welcome, " + username;
Thank you so much for the help!
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'm using Firebase authentication with google accounts. Login process works fine, but I have a problem with logout. I successfuly log out of firebase, but not from google. That means that the user remains logged in to google. How can I log out from both of them?
That is my code:
function auth() {
// Initialize Firebase;
firebase.initializeApp(settings);
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
sessionStorage.setItem('tokenK', token);
// The signed-in user info.
var user = result.user;
var tempName = user.displayName.split(" ");
var fullName = tempName[0].charAt(0).toUpperCase() + tempName[0].toLowerCase().substring(1, tempName[0].length) +
" " + tempName[1].charAt(0).toUpperCase() +tempName[1].toLowerCase().substring(1, tempName[1].length);
sessionStorage.setItem('displayName', fullName);
sessionStorage.setItem('userName', user.email);
}).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;
console.log(error);
});
}
And
function logOut(){
firebase.initializeApp(settings);
var dataJ = JSON.stringify(sessionStorage.getItem('userName'));
var xhttp = new XMLHttpRequest();
firebase.auth().signOut().then(function() {
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 204) {
sessionStorage.removeItem('tokenK');
sessionStorage.removeItem('displayName');
sessionStorage.removeItem('userName');
sessionStorage.removeItem('role');
sessionStorage.removeItem('school');
sessionStorage.removeItem('grade');
window.open('index.html', '_self');
}
};
xhttp.open("POST", settings.protocol + "://" + settings.host + ":" + settings.port + "/api/Login/SignOut", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.setRequestHeader("Token", sessionStorage.getItem('tokenK'));
xhttp.send(dataJ);
}).catch(function(error) {
console.log(error);
});
}
I've seen this post, speaking about similar issue on android, but can't find anything for JS.
Normally this is expected behavior. Sign out from firebase is unrelated to sign out from google. User would need to explicitly sign out from google. However, if you know your application will be used on a share device you can do the following:
// Sign out from firebase.
firebase.auth().signOut().then(function() {
// Redirect to google sign out.
window.location.assign('https://accounts.google.com/logout');
}).catch(function(error) {
// Error occurred.
});
mGoogleSignInClient.signOut().addOnCompleteListener(ClassName.this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
Toast.makeText(ClassName.this, "logged out", Toast.LENGTH_SHORT).show();
}
});
I'm using firebase and html. The problem is sign in process allowed all email to sign in. I have activated firebase authentication email/password.
Below I attached the code. please do help me with posting the right code.
(HTML Coding)
[HTML CODING Notes: i have enter the firebase code and activate the firebase]
(Picture)
1
[Here is the javascript. i already try to follow the guidelines from the firebase but did not work. Below are the code i did try
var userEmail = document.getElementById("email_field").value;
var userPass = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorMessage);
// ...
});
}
(Picture of current coding)
1
You can use:-
firebase.auth().signInWithEmailAndPassword(email, password).then(data => {
// Successfully sign in
// ...
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
For more info, you can visit:- https://firebase.google.com/docs/auth/web/password-auth
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.