Firebase Auth check if new user on Facebook login - javascript

I am creating a web app using Firebase auth to authenticate my users and a MongoDB database to store some relevant user information specific to my site. I am trying to add Facebook as another means of authentication.
Logging in with Facebook is working, but what I want to do is intercept the user generation/authentication with Firebase to check if Firebase is creating a new user on a first-time Facebook login. This way if a new user is being created in Firebase I can also create a new user in my mongo database (essentially handling a signup). My facebook login function looks like this:
handleFacebookLogin() {
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
// check if new user here
// handleNewFacebookUser()
this.props.update(user);
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
});
}
I couldn't find anything that allowed me to check if a new user was being generated in the Firebase docs. It seems to silently handle new Firebase auth user generation when logging in through Facebook for the first time. If there is no built-in way for Firebase to handle this I will just check if the user exists in my database, but I wanted to be sure there wasn't a simpler alternative.

You can detect if a user is new or existing as follows:
firebase.auth().signInWithPopup(provider)
.then(function(result) {
console.log(result.additionalUserInfo.isNewUser);
})
.catch(function(error) {
// Handle error.
});
For more on this refer to the documentation.

Related

Error: auth.sendSignInLinkToEmail is not a function

const firebase = require("firebase-admin");
const auth=firebase.auth();
// create user in firebase data
var actionCodeSettings = {
// URL you want to redirect back to. The domain (www.example.com) for this
// URL must be in the authorized domains list in the Firebase Console.
url: 'https://www.example.com/finishSignUp?cartId=1234',
// This must be true.
handleCodeInApp: true,
dynamicLinkDomain: 'example.page.link'
};
// [END auth_email_link_actioncode_settings]
app.get("/firebase/api/createUser",function(req,resp){
auth.sendSignInLinkToEmail("sagar#gmail.com",actionCodeSettings)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
console.log("user created :"+user);
resp.send("--"+userCredential);
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ..
});
});
It gives me an error. the setting I already enable in firebase.
What is issue here?
This function was written in the firebase cloud function.
Sending emails and SMS messages to a user with Firebase Authentication is only possible with the client-side SDKs.
You're using the Admin SDK, which does not have this functionality, as it would be too prone to abuse.
So you will have to implement this functionality in the client-side application code, using the regular client-side/Web SDK for Firebase Authentication.

Firebase google sign in pop up window flashes and never signing in using Vuejs?

I have used google sign in popup method in vuejs. In live google sign in pop up window flashes and never signed in. But everything works fine in local.
Here is firebase google sign in & sign up method code:
const database = firebase.initializeApp(config);
const firestore = database.firestore();
var provider = new firebase.auth.GoogleAuthProvider();
database.signIn = async (email, password) => {
try {
await firebase.auth().signInWithPopup(provider).then((result) => {
// This gives you a Google Access Token. You can use it to access Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
console.log("user",user.displayName);
console.log('result google',result.user);
// ...
store.commit("setCurrentUser", 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;
// ...
});
return true;
} catch (error) {
return error;
}
}
Tried by changing chrome pop up, cookies setting nothing works. Any help much appreciated please...
If it's working locally, you should make sure your hosting domain is registered with Google OAuth.
In Firebase console:
Develop -> Authentication -> Sign-in method -> Authorized domains
And add your domain to the list. It may take some time to verify.
If that doesn't work, try logging error.message for more information.
After updating firebase it works fine. npm i firebase#latest..

Retrieving public profile from Facebook with Firebase and AngularJS

So, I've been using Firebase in my AngularJS/Ionic project to access my app with Facebook authentication.
The authentication goes fine, it retrieves some data (Display_name, email, urid, url photo, etc.), but I need more.
I need to get the first name and last name for my project, because I'll need to work with it. When the person accepts to share the information it says that she's sharing her public profile, but the data that comes doesn't have what Facebook documentation says that public profile provides.
I used Firebase documentation to program this. There's a part where it says to use addScope to add what you want, public profile is asked by default, but I added it anyway. (I can't post the link, StackOverflow says that my reputation is too low).
$scope.FBLogin = function (){
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
var profile = result.user.public_profile;
console.log("success")
console.log(result);
console.log(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;
// ...
});
};
Log here:
So, since I don't want to have to use the "display name". as people sometimes don't use their real names there.
Does anyone know how to retrieve that information using Firebase and AngularJS?
Currently this is not supported by Firebase. You have to make the extra api call to Facebook to get that data.
result.credential.accessToken contains the Facebook access token. Using that access token, you can get facebook profile data. Here is an example how to do that with facebook:
How to get user profile info using access token in php-sdk
AJAX GET 'https://graph.facebook.com/me?access_token=' + result.credential.accessToken
For people looking for how to do it in AngularJS or how do you filter what you want this is how i did it using the information bojeil gave me!(Thank you again!)
var token = result.credential.accessToken;
var user = result.user;
$http.get('https://graph.facebook.com/v2.5/me? access_token='+token+'&fields=id,name,first_name,last_name,email')
.success(function(jsonService){
$scope.user.firstName= jsonService.first_name;
$scope.user.lastName= jsonService.last_name
$scope.user.email = jsonService.email;
});

Getting additional data from Firebase Auth Facebook Login

I'm developing an application with Firebase Web and Javascript.
I built a Facebook Login, but i can't understand how to access the scopeData i requested in the sign-in step.
Here is my signInWithRedirect and getRedirectResult code:
// signInWithRedirect
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('user_birthday');
provider.addScope('user_friends');
firebase.auth().signInWithRedirect(provider);
// getRedirectResult
firebase.auth().getRedirectResult().then(function(result){
if(result.credential)
var token = result.credential.accessToken;
var user = result.user;
}).catch(function(error){
console.log(error.code);
console.log(error.message);
});
Currently additional OAuth provider data is not returned in Firebase. You will need to use the access token returned and query facebook api to get that additional information.

Link Facebook to Firebase Anonymous Auth without calling Facebook API

I am creating anonymous sessions in my Firebase application to save user data before they create their accounts. I saw that Firebase allows linking a Facebook login to an anonymous account which sounds really neat, but a caveat of this process seems to be that I have to grab the Facebook token myself, outside the warmth and comfort of the awesome Firebase API, which seems strangely un-developed given how much of the login flow Firebase seems to do on behalf of apps.
A code sample of how to connect an anonymous account from their account linking docs:
var credential = firebase.auth.FacebookAuthProvider.credential(
response.authResponse.accessToken);
Naturally, I want to use Firebase's way of getting a token
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// result.token or whatever would appear here
});
But if I were to run that, I would lose my anonymous session (and my anonymous user ID, which we want the new Facebook login to use).
Is there anyway to get a Facebook Token out of Firebase's auth mechanism without logging the user in and losing the anonymous session that I'm trying to convert into a Facebook Login-able account? (The goal is to not have to call the Facebook API myself, especially as I'll be adding Google here as well)
I think you're looking to #linkWithPopup or #linkWithRedirect:
var provider = new firebase.auth.FacebookAuthProvider();
user.linkWithPopup(provider).then(function(result) {
console.log('Party 🎉');
});
If for some reason that doesn't cut it, you could always opt to do yourself:
Sign in the user anonymously, and store the user somewhere
Sign in the user with the provider and store the token somewhere
Delete the provider user and then link the account with the token
Quick and dirty example:
var googleToken;
var anonUser;
firebase.auth().signInAnonymously().then(function(user) {
anonUser = user;
}).catch(function(error) {
console.error("Anon sign in failed", error);
});
function signInWithGoogle() {
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
googleToken = result.credential.idToken;
}).catch(function(error) {
console.error("Google sign in failed", error);
})
}
function deleteAndLink() {
firebase.auth().currentUser.delete().then(function() {
var credential =
firebase.auth.GoogleAuthProvider.credential(googleToken);
anonUser.link(googleCredential);
}).then(function() {
console.log("Link succeeded");
}).catch(function(error) {
console.error("Something went wrong", error);
});
}

Categories

Resources