Using provider UID as Firestore ID in AngularFire2 auth - javascript

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.

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.

Create accounts in Firebase Auth from custom admin website while I'm logged in

I'm doing a web application using Angular 8 and AngularFire.
On my custom website, a user with the admin privilege, can create accounts for other people.
To do this, I have read that I need to:
Create a second auth reference and use that to create users.
Reason: if we use our default auth reference, when the createUserWithEmailAndPassword() method creates the new user, the
user is signed in automatically, overriding our current session (the
logged in user on our custom website).
I have tried:
async createUserWithEmailAndPassword(email: string, password: string): Promise<string> {
// 1. A new auth session
let secondaryApp = firebase.initializeApp(environment.firebaseConfig, 'Secondary');
// 2. Create the account
const user = await secondaryApp.auth().createUserWithEmailAndPassword(email, password);
// 3. Sign out the user created
await secondaryApp.auth().signOut();
// 4. Make the auth session null to ensure that it's deleted
secondaryApp = null;
if (user.user.uid) {
// User created
return Promise.resolve(user.user.uid);
} else {
// Error
return Promise.reject();
}
}
Error received (happens when I call the method a second time):
FirebaseError: Firebase: Firebase App named 'Secondary' already exists
(app/duplicate-app).
My thoughts/steps were:
Create a new auth session.
Create the user.
Sign out the user created.
Delete the auth session created.
All clear and ready to create a new account in any moment.
What I'm doing wrong?
My goal is to be able to create accounts while I'm logged in on my custom website.
An educated guess is that you get that error message the second time you call your own createUserWithEmailAndPassword method. The reason for that is that you've already created an app named Secondary on the previous call, and didn't remove that app.
The easiest solution is to check if the Secondary app already exists before creating it.
let secondaryApp = firebase.app("Secondary");
if (!secondaryApp) {
secondaryApp = firebase.initializeApp(environment.firebaseConfig, 'Secondary');
}

How to get current user or login user in Firebase cloud functions?

How to get current user email like there is a event called onCreate but i want to trigger onLogin or currentUser?
exports.currentUser = functions.auth.user().onCreate((user) => {
const email = user.email; // The email of the user.
const displayName = user.displayName; // The display name of the user.
});
There are no Cloud Functions triggers for when a user signs in to your app with Firebase Authentication. If you have something to do what the user signs in, that should be controlled by the app itself, since it has the callback for signin and signout. You could directly invoke an HTTP or callable type function in that case, and pass the function the UID to look up using the Firebase Admin SDK.

Firebase Auth Login not showing logged in user name

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 });
}
);
}

Categories