need some advice here.
My Nuxt & Firebase/Firestore web app will have 3 different type of users:
First, I want my users, whenever they login, they will log into page related to their user type. e.g: subcontractor login push to /subcontractor, contractor login push to /contractor etc etc.
I also want the user can only see pages related to their types. (user A only see /A & /Atwo, user B can only see /B & /Btwo, user C, can only see /C & /Ctwo etc etc..)
I want to avoid using cloud functions if can, as from what I understand, you cannot deploy your app in the free plan if your app has cloud functions in it.
Anyway, is below the right way to do it?
If its correct, how to do step 1 & 2? Is there any articles or real-life application source code that explain briefly what I wanted?
Beginner here. Already gone thru here and there around the internet but can't quite find the answer that I wanted :(
Custom Claims are definitely an option but that would require Cloud functions or a server. Yes, you can store user type in their Firestore document and check it before the page renders or whenever required. However, you must make sure only authorized users can change their role.
The flow would be as simple as:
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
import { getFirestore, doc, getDoc } from "firebase/firestore";
const auth = getAuth();
const firestore = getFirestore();
const login = async () => {
const { user } = await signInWithEmailAndPassword(auth, email, password);
// Reading user document
const docRef = doc(firestore, "users", user.uid);
const docSnap = await getDoc(docRef);
const { userType } = docSnap.data()
switch (userType) {
case 'contractor':
// redirect to /contractor
break;
case 'sub-contractor':
// redirect to /sub-contractor
break;
default:
// redirect to default page
break;
}
}
I also want the user can only see pages related to their types.
You can follow them same method in a server side middleware. First read userType and then check if user is authorized to visit the page. If not, redirect to any other page.
Best part of using Custom Claims is that you can read them in security rules of Realtime Database, Firestore and Storage as well. If you store user type in Firestore you cannot read that in security rules of any other Firebase service. Using Firestore also incurs additional charge for reading user's role every time. You need a Cloud function to set the custom claim only and not read the claim every time.