firebase - check if an user is already registered in database - javascript

I have a firebase app that is running on mobile devices and now I need to create the web version of it.
At the moment I have integrated firebase ui to give to users the ability to login. Since I need to show a wizard if the user isn't already registered, how I can check if user exists in the database so I can decide if show the wizard or not and then add it to the database?

It sounds like you're looking for the fetchSignInMethodsForEmail method, which returns the list of providers with which a specified email address has previously been signed in to Firebase.
The typical flow is:
Get the email address of the user
Call fetchSignInMethodsForEmail to get a list of providers
If the list is empty, go to your account creation flow
If the list has a single value, show the sign in screen for that provider
If the list has multiple values, show a screen where the user can pick from those providers

I consider you are using firebase auth and firestore, but this is the logic
firebase.auth().onAuthStateChanged(async (user)=> {
if (user == null){
//the user is not signed in, navigate to login screen
}else{
//the user is signed in, try to check if he exists in the database or register him
//let say you are using firestore roo
let user_ = await firebase.app().auth().currentUser
firebase.firestore().collection("collections_of_users").doc(user_.uid).get().then(snap =>{
if(snap.exists){
//the user exists
}else{
//register him, and before make sure his email is verified by checking if emailVerified === true
firebase.firestore().collection("collections_of_users").doc(user_.uid).set({user_mail: user_.email, user_name: "xxx"})
}
})
}
});

Related

How to add a user’s name when we sign up with fire base auth [duplicate]

I am trying out firebase auth. I want to store a photo-url and a username when the user signs up. My code for signing up -
const email = signupForm['email'].value;
const password = signupForm['password'].value;
auth
.createUserWithEmailAndPassword(email, password)
.then((cred) => {
console.log(cred);
alert('done');
signupForm.reset();
})
.catch((error) => {
console.log(error);
alert(error);
});
Could someone tell me how to add username and photo-url in signup. I know I can make a collection in a firebase db but I read somewhere that username and photo-url can also be saved in firebase auth
Firebase Authentication doesn't have a user property that stores username. You would have to store that on your own, in a database, and make sure the string is unique.
You can store a profile picture URL using updateProfile(). It will not store the image for you - you can only provide a URL. If you need to store the image file itself, tou should probably consider using another product for that, such as Cloud Storage.
Typically, if you have custom information to store per user, you should do that in a database using the unique ID of the user signed in. This gives you full control, rather than depending on what Firebase Auth provides (which is not much). The purpose of Auth is to validate the user's identity, not store per-user information.

Read tenantId for the loggedi in user in Angular & Firebase

I'm working on the multitenat application using Angular and Firebase in combination with Google Cloud Identity Platform. The later one is part of the Firebase auth and allows me to group users under different tenants plus it adds the "tenantId" property to a user.
All my users and a sub-collection of a tenant document.
The challenge I have is how to obtain a currently logged in user via Firebase auth API in time to make the query to list all the users for a given tenant.
Imagine logged in user pasts in the browser's address bar URL http://tenant.domain.com/users. In order to retrieve this data I need to know the "tenantId" which has to come via currently logged in user which resolves later than I make my query.
I retrieve current user using the following code:
getCurrentUser() {
return new Promise<any>((resolve, reject) => {
var user = firebase.auth().onAuthStateChanged(function (user) {
if (user) {
resolve(user);
} else {
reject('No user logged in');
}
})
});
}
Basically I'm looking for away to have "tenantId" available at any time and place in the application.

Check if an email already exists in firestore auth on signup (Angular)

As a user signs up to our app, I want them to know whether the email they are trying to sign up with already exists, without having to submit the form (A.K.A on blur of the email field). As it stands, the user has to enter their details and click signup before it let's them know whether the email is taken or not.
The required behaviour can be observed with spotify signup where you enter the email, and as soon as you click away you see the following:
So far, I have written a cloud function (http) that is triggered on blur that calls the getUserByEmail function from firestore admin auth. The function is as follows:
export const checkUserEmail = https.onRequest((req, res) => {
corsHandler(req, res, async () => {
try {
const email = req.body.email;
await admin.auth().getUserByEmail(email);
res.send({status: 200});
return;
} catch(e) {
return Helpers._handleError(res, 400, e.message);
}
})
});
This does work as I can now check at this moment whether or not an email exists, however the problem is it takes anywhere between 3-10 seconds to validate (long enough for the user to get deeper into the signup process).
Is there a way to either:
Speed up the cloud function or
Validate whether a user has already authenticated with the email provided directly on the client side with firestore?
Thanks in advance
You can use a users collection, which you may be doing already. This can store user information and often proves to be really handle since the auth user can't be updated with fields it doesn't how out of the box.
You can store users' emails here and check the collection for the user's input compared to the email field of the users collection here.

Keep user after redirect with firebase

Im currently working on a side project with firebase on web and it uses user auth. I have the user logging in and then creating a game room which redirects to a separate page for the game "room". After the page redirects though i cannot pull any of the users data and the only way that im doing it is by re initializing firebase and using
auth.onAuthStateChanged(function(user) {
if (user && user != null) {
uid = user.uid;
email = user.email;
currUser = user;
} else {
//user isnt logged in
window.location.href = 'index.html';
}
There seems to probably be an easier way to do this but i cant seem to get it working and this way also messes up sections of my other code.
Attaching an onAuthStateChanged callback is the idiomatic way to get the user.
You can also get the user with firebase.auth().currentUser. But if a token refresh is required, you may in that case mis-detect that there is no user. That why an onAuthStateChanged callback is recommended.
See the Firebase documentation on getting the current user.

Check for new user

I want to know when a user logs in via a provider(twitter,facebook,etc...) If he is a new user. If so then add his data to my firebase.. Currently i have read this:
https://www.firebase.com/docs/web/guide/user-auth.html
And it tells me to do:
var isNewUser = true;
Then check by saying
if(authData && isNewUser){
//This is a new user
}
But it dosent work... I logged in with the same account but it tells me its a new user...
Generally with Firebase, you would have a /users node where you would store other data about your users
users
user_id_0
name: "Buck Murdock"
email: "buck#moonbasealphabeta"
user_id_1
name: "Ted Striker"
email: "ted#airplane.com"
The user_id is the Firebase assigned user id.
When a user starts to access your App, you would query your /users node to see if, for example, their email already exists. If not, then you create the user and add them to the /users node.
Oh - and refer to the section Storing User Data in the Firebase guide as you may have overlooked the comment
// here we will just simulate this with an isNewUser boolean

Categories