Firebase Auth Login not showing logged in user name - javascript

I'm using firebase web authentication to log users into my website which works perfectly fine - but I want to be able to show the name of the user logged in. How do I do that?

When a user signs up, it will be written with some basic fields (email, uniqueID, etc) to the Firebase Authentication DB (which you have access to, but you don't have full control of, since it's controlled by the Firebase Auth system).
Once your brand new user is created, you'll get a UserCredential object with basic information of your user. Use the uniqueID field (UserCredential.user.uid) to write your user details with as many fields as you want (username, email, fullName, address, preferences, etc) to your Firebase database (realtime DB or cloud Firestore). I think it's a good practice to store under a document with the uniqueID created by the Auth system.
Once you've done that, and that users logins in at a later time, you'll get another userCredential object that contains the uniqueID for that user.
You'll use that uniqueID to access your database where you stored your users details and you will be able to retrieve all the data that you want.
See the code below (I'm using React): uppon a successful signUp, we get a UserCredential object, which we can use to read the uniqueId uid that it was just created, and use that to create a document in our database with that same id. We can add as many fields as we want. In this case, I added username (which I'm getting from my signup form) and email (which I'm getting directly from the UserCredential object).
UserCredential docs
Create User with Password and Email docs
handleSubmit(event){
event.preventDefault();
const { email, passwordOne} = this.state;
// SIGN UP FUNCTION
this.props.firebase.auth.createUserWithEmailAndPassword(email, passwordOne)
// SAVING USER DETAILS TO MY DATABASE
.then((UserCredential) => {
const username = this.state.username;
this.props.firebase.db.collection('users').doc(UserCredential.user.uid)
.set({
username: username,
email: UserCredential.user.email
})
.then( () => {
this.setState({ ...INITIAL_STATE });
this.props.history.push('/');
}
)
.catch(error => {
this.setState({ error });
}
);
}
)
.catch(error => {
this.setState({ error });
}
);
}

Related

Vue 3 Firebase Auth get *any* user data by id? [duplicate]

This question already has an answer here:
How to get FirebaseUser from a uid?
(1 answer)
Closed 8 months ago.
New to vue/firebase. I was able to lookup how to pull up “current user” data from auth no problem but trying to write a js composable that I can pass in any user id (not necessarily current user) and it will return the user object or at least displayName.
All the docs/vids I can find on the topic reference getting info on *current user *only not another user. From the Google Docs it says I should be able to do this in the "Retrieve user data" section. Closest model to Vue code-wise seems to be “Node.Js” but it isn't working.
Here's what I've got in getUserById
import { getAuth } from 'firebase/auth'
const getUserById = (u) => { // u = user id
const userData = null
getAuth()
.getUser(u)
.then((userRecord) => {
// See the UserRecord reference doc for the contents of userRecord.
console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);
userData = userRecord
})
.catch((error) => {
console.log('Error fetching user data:', error);
});
return { userData }
}
export default getUserById
The error I get is getUser is not a function. I tried adding getUser to the import but same error.
There is no way to look up information about just any user by their UID in the client-side APIs of Firebase as that would be a security risk. There is an API to look up a user by their UID in the Admin SDK, but that can only be used on a trusted environment (such as your development machine, a server you control, or Cloud Functions/Cloud Run), and not in client-side code.
If you need such functionality in your app, you can either wrap the functionality from the Admin SDK in a custom endpoint that you then secure, or have each user write information to a cloud database (such as Realtime Database or Firestore) and read it from there.
Also see:
How to get FirebaseUser from a uid?
Firebase get user by ID
Is there any way to get Firebase Auth User UID?

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.

Using provider UID as Firestore ID in AngularFire2 auth

I want to add Google, Facebook and custom login to my Angular7 web app.
Is the UID identifier given by each provider unique ? I mean, can I use it as a user ID in my users Firestore collection ?
And if that's the case, can I still use the createId() method to generate this ID myself in my custom login ? Or might it be the same as one of the providers UIDs ?
Yes you can use it as an UID in your users collection.
Here is my authentification flow:
1/ User creates a new account with email/password
async signUpWithPassword(email, password) {
await firebase.auth().createUserWithEmailAndPassword(email, password)
// user created!
}
2/ I run a cloud function with the auth's onCreate triggers to save the user to my collection:
export const createUserProfile = functions.auth
.user()
.onCreate((user: admin.auth.UserRecord) => {
const { uid } = user
const userRef = db.doc(`users/${uid}`)
// Save it to firestore
return userRef.set({ points: 200 })
})
3/ If this user tries to register with another provider (Google/Facebook etc.), I detect if he's using the same email address, if so I link the new provider to the current one via account linking:
https://firebase.google.com/docs/auth/web/account-linking
That way, the user is going to have multiple auth providers attached to one unique UID/profile.

Interacting with the current user object in firebase requires me the type user.user, why must I type user twice?

I am trying to add a registration page for users to register on a firebase database in a web page(it's wordpress).
For example when I create the user and then try a simple console log to check the created user's uid like so:
auth.createUserWithEmailAndPassword(email, password)
.then(function(user){
console.log(user.uid);
});
I get an "undefined". But when I attempt to do the same thing by typing
auth.createUserWithEmailAndPassword(email, password)
.then(function(user){
console.log(user.user.uid);
});
It works correctly.
Why is this?
I followed the documentation for initialising firebase and then set the reference to the auth as
var auth = firebase.auth();
Thanks for any help. I am new to both Javascript and Firebase.
From the documentation
createUserWithEmailAndPassword(email, password) returns firebase.Promise containing non-null firebase.auth.UserCredential
Clicking firebase.auth.UserCredential shows you it has the structure
{
user: nullable firebase.User,
credential: nullable firebase.auth.AuthCredential,
operationType: (nullable string or undefined),
additionalUserInfo: (nullable firebase.auth.AdditionalUserInfo or undefined)
}
So you are accessing the user property of the returned UserCredential object which you have named user.
If you wanted to, you could change user to userCredential to help clarify what it is and avoid future confusion.
auth.createUserWithEmailAndPassword(email, password)
.then(function(userCredential){
console.log(userCredential.user.uid);
});

firebase add user information while creating user (react.js)

I researched before asking this question but I couldn't find an answer.
I made a form in react js. When I click the button it creates a user with createUserWithEmailAndPassword() method. There is no problem with creating the user. I want to add extra information like; username : "Usernameeeee" to my database. The database will look like this:
users {
userUid1: {name: "Name User 1"}
userUid2: {name: "Name User 2"}
....
}
When I use createUserWithEmailAndPassword(), it creates a user and logs them in. But as you can see the above, I need the current user's id. I know how to get it normally, firebase.auth().currenUser... But while creating a user I can't catch the user's id. It returns null;
export function signUpUser({email, password}) {
return function (dispatch){
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(
() => dispatch({type: USER_SIGNUP_SUCCESS})
)
.then(console.log(firebase.auth().currentUser))
.catch(error => {
dispatch({type: USER_SIGNUP_FAIL, payload: error.message});
});
}
}
When I console the current user, the creating user is complete but not logged in yet. So how can I add information while creating a user ? (not after logged in some other way)
I found the answer after a day. I hope this will be helpful to others. As you understand, the main problem is getting the user id right after creating a user, before user sign in...
So the solution is:
export function signUpUser({email, password, username}) {
const db = firebase.database();
return function (dispatch){
firebase.auth().createUserWithEmailAndPassword(email, password)
// here we get user id if creating is successful.
.then(function(user){
dispatch({type: USER_SIGNUP_SUCCESS}); // I dispatched some message.
db.ref(`users/${user.uid}`).set({name: username}); // I added user
console.log('uid:',user.uid)
})

Categories