Create a SAAS blog to store data per user with Firebase Auth and Firestore
Create a SAAS application to store data per user. This user data should only be accessible to this specific user. We will start configuring the security rule in the Cloud Firestore web interface to limit the visibility of documents then we will create a web client capable of authentication and then create and write documents.
Hyerarchy used here is /UserId/DocumentID
Only the authenticated author can access these documents
More details here: https://firebase.google.com/docs/rules/rules-language?hl=en
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{userId}/{document=**} {
// Only the authenticated user who authored the directory can read or write
allow read, write: if request.auth != null && request.auth.uid == userId;
}
// Another useful examples
//match /notes/{storyId} {
// // Only the authenticated user who authored the directory can read or write
// allow read, write: if request.auth != null && request.auth.uid == resource.data.author;
//}
//match /{document=**} {
// allow read, write: if request.time < timestamp.date(2020, 8, 23);
//}
//match /users/{userId} {
// allow read, update, delete: if request.auth != null && request.auth.uid == userId;
// allow create: if request.auth != null;
//}
}
}
npm i -S firebase
Go to firebase console settings for your application and download firebaseConfig: https://console.firebase.google.com/ Run this block of code below before all the others
//global 1
import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword } from "firebase/auth";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
More details here: https://firebase.google.com/docs/auth/web/start?hl=en
const email = "USERMAIL+test1@gmail.com"
const password = "MYAWESOMEPASSWORD";
// Create user
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
printJSON(user);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
print(errorMessage);
});
SignIn a user and create a Firestore document. More details here: https://firebase.google.com/docs/firestore/quickstart?hl=en
const email = "USERMAIL+test1@gmail.com"
const password = "MYAWESOMEPASSWORD";
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password)
// Signed in
const user = userCredential.user;
printJSON(user);
// Create a doc
const docRef = db.collection(user.uid).doc('alovelace');
await docRef.set({
first: 'Ada',
last: 'Lovelace',
born: 1915
});
} catch(error) {
const errorCode = error.code;
const errorMessage = error.message;
print(errorMessage);
}
SignIn a user and read Firestore documents
const email = "USERMAIL+test1@gmail.com"
const password = "MYAWESOMEPASSWORD";
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password)
// Signed in
const user = userCredential.user;
printJSON(user);
// Read a doc
const snapshot = await db.collection(user.uid).get();
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
});
} catch(error) {
const errorCode = error.code;
const errorMessage = error.message;
print(errorMessage);
}