Automating Firebase and Javascript (VueJS) - javascript

I'm adding users manually as I don't want them to access the app without authorisation.
Upon adding a user,I would like to add a new child to the database (named from the user email) and send him an email with his logins.
So far I've arrived to this, that doesn't work (webpack) and I cannot create a child using the current user's email:
firebase.auth.user().onCreate(function(event) {
var uid = event.data.uid;
return admin.database().ref("/users/" + uid)
});
I also found this one for the email:
exports.sendWelcomeEmail = functions.auth.user().onCreate(function(event) {
var uid = event.data.uid;
return sendEmail(uid);
});
Do you have any idea what the formula looks like to create a child in the DB with the user and send him an email with his credentials right upon creation of a new user.

Related

Add, update and read sub-collection in firestore using Angular (#angular/fire)

I am trying to learn firebase. I am making a project like Linkedin using Angular and Firebase.
I am using the #angular/fire package in my project.
So far I have done authentication and adding some basic info of a user. I have users collection where each documentId have information like name, email and etc
Now my next goal is to create a work experience section. Since a user can have multiple work experience.
I have to decided to proceed with sub-collection under each user document id instead of creating a separate collection for work-experience.
Now I am having a bit trouble how to add sub-collection in my users collection.
A user can only add/update one experience at a time. My UI will be something similar to Linkedin. When the 'Add Experience' button is clicked a modal will pop up and there will be a form inside the form with fields such as jobTitle, companyName and etc. So once the submit is clicked I want to save that data under the work-experience sub-collection with a unique documentId.
Currently I am adding my basic info like this
Adding
addUser(user: any): Observable<void> {
const ref = doc(this.firestore, 'users', user.uid);
return from(setDoc(ref, user));
}
Updating
updateUser(user: any): Observable<void> {
const ref = doc(this.firestore, 'users', user.uid);
return from(updateDoc(ref, { ...user }));
}
Now I want to add sub-collection called work-experience under the users collection.
From your other question I think you need to add a sub-collection which contains a document with ID work-experience.
If my assumption is correct, do as follows to create the DocumentReference to this Document:
const workExperienceDocRef = doc(this.firestore, `users/${user.uid}/sub-sections/work-experience`);
Note: Make sure to use back ticks.
And then you can set the data of this doc as follows, for example:
return from(setDoc(workExperienceDocRef, {experiences: [{years: "2015-2018", company: "comp1"}, {years: "2018-2021", company: "comp2"}]}));
If you want to create a sub-collection for the user's document, do as follows:
const userSubCollection = collection(this.firestore, `users/${user.uid}/sub-collection`);
Then you can use the addDoc() method, which will automatically generate the document ID.:
const docRef = await addDoc(userSubCollection, {
foo: "bar",
bar: "foo"
});

Is it secure to send the user UID to firebase cloud functions

I have a firestore collection and every user has one document. The document name is equal to the user UID.
I write to these documents with a firebase function. So I pass the user UID to this firebase cloud function so the function can write to the database (this is just a very simple write so I won't show it here).
Here is the function call in my js file:
const saveAllTimeData = firebase.functions().httpsCallable('saveAllTimeData');
saveAllTimeData({ data: firebase.auth().currentUser.uid })
But I am not very sure if this is safe.
Can't just someone change the firebase.auth().currentUser.uid part before the execution? And f.e. put in another uid to change documents he shouldn't be able to change?
The user's UID is safe to share as a UID acts like a fingerprint to differentiate and identify a user from another. these do not in any way give permission or power over that user, it is simply a random set of characters that is unique.
With the Admin SDK, you are also able to create these UID's per design, allowing you to have a custom UID that may represent their username if so desired.
Since you are also using a httpsCallable cloud function, this includes a value called context, which uses the JWT token from the auth module. the JWT token is decodable to the user and should not be shared. however, the method httpsCallable secures it through the HTTPS tunnel making it secure from most hijacking.
in your function, you should notice the context variable
exports.addMessage = functions.https.onCall((data, context) => {
// ...
});
For onCall, context contains a property called auth of which contains the decoded JWT values
// Message text passed from the client.
const text = data.text;
// Authentication / user information is automatically added to the request.
const uid = context.auth.uid;
const name = context.auth.token.name || null;
const picture = context.auth.token.picture || null;
const email = context.auth.token.email || null;
references
https://firebase.google.com/docs/reference/functions/providers_https_#oncall
https://firebase.google.com/docs/reference/functions/providers_https_.callablecontext
https://firebase.google.com/docs/auth/admin/verify-id-tokens

Firebase Realtime Database Connection Data - Web

I have to show data belonging to a user that logged in.
My database structure is as follows:
Users/Drivers/Uid/name,phone...
How can I show the data of a user that logged in by using JavaScript as a Text?
<a> Username </a>
If you have this HTML:
<a id="username"> Username </a>
And this database structure:
Users
Drivers
Uid: { name: "Name", phone: "Phone number" }
Then you can display the name of the current user with:
var currentUser = firebase.auth().currentUser;
var userRef = firebase.database().ref("Users/Drivers").child(currentUser.uid);
userRef.on("value", function(snapshot) {
document.getElementById("username").innerText = snapshot.val().name;
})
So this code does (line by line):
Determine the current user
Create a reference to that user's data in the database
Starts listening for that data, meaning it loads the current data, and then monitors for any changes
Puts the name of the user into the element.
Line 4 will be called immediately, with the current value of the user, and then every time that user data change.
Also see the Firebase documentation on listening for values.
If the page can also be loaded when the user is not signed in (yet), you'll want to make sure to only run this code when the user did sign in. You can do this by using a so-called auth state change listener, which is called whenever the user's auth state changes:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var userRef = firebase.database().ref("Users/Drivers").child(user.uid);
userRef.on("value", function(snapshot) {
document.getElementById("username").innerText = snapshot.val().name;
})
}
});
See the Firebase documentation on getting the current signed in user..

firebase javascript injection

I want ask something about firebase security. How to handle following situations?
User is creating account with createUserWithEmailAndPassword() function, then i save his username,email,created_at...to realtime db. But what if data are not saved correctly. His account is created and he is logged in automatically but data is not stored.
I have some registration logic... for example unique usernames... so before creating acc i check if this username exist in realtime db. But he still can call createUserWithEmailandPassword() from js console and account is created.
For situation one:
According to the firebase docs (https://www.firebase.com/docs/web/api/firebase/createuser.html), creating a user does not automatically authenticate them. An additional call to authWithPassword() is required first. In order to ensure that a user isn't authenticated without valid data, you could run a check to the server to make sure the data is saved correctly before authenticating.
Edit: Nevermind that; looks like firebase does auto-auth now - take a look at what I wrote below.
Now a concern with this approach would be if your app allowed people to authenticate with an OAuth provider like gmail, then there is no function for creating the user before authenticating them. What you may need to do is pull the user data from the firebase, determine if it's valid, and if its not valid show a popup or redirect that lets the user fix any invalid data.
For situation two:
If you wanted to make sure that in the case of them calling createUserWithEmailAndPassword() from the console a new user is not created, you could try something like this with promises;
var createUserWithEmailAndPassword = function(username, password) {
var promise = isNewUserValid(username, password);
promise.then(function() {
// Code for creating new user goes here
});
}
In this way, you never expose the actual code that makes a new user because it exists within an anonymous function.
I don't think that this could solve the problem entirely though because firebases API would let anyone create an account using something
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.createUser({
email: "bobtony#firebase.com",
password: "correcthorsebatterystaple"
}
(Taken from https://www.firebase.com/docs/web/api/firebase/createuser.html)
If you wanted to make sure that server side you can't ever create a user with the same user name, you'd need to look into firebases's rules, specifically .validate
Using it, you could make sure that the username doesn't already exist in order to validate the operation of creating a username for an account.
Here's the firebase doc on rules: https://www.firebase.com/docs/security/quickstart.html
And this is another question on stack overflow that is quite similar to yours. Enforcing unique usernames with Firebase simplelogin Marein's answer is a good starting point for implementing the server side validation.
First save the user credentials in the realtime database before you create the user:
var rootRef = firebase.database().ref('child');
var newUser = {
[name]: username,
[email]: useremail,
[joined]: date
};
rootRef.update(newUser);
After adding the Usersinfo into the realtime database create a new user:
firebase.auth().createUserWithEmailAndPassword(useremail, userpassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
When an error occured while inserting the data in the realtime database, it will skip the createuser function.
This works fine for me, hope this helps!

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