Firebase

How to implement Firebase Authentication with role-based user management?

Discover the steps to integrate Firebase Authentication and manage users with role-based access in your app, ensuring everyone's data remains secure and access is custom-tailored to roles. Complete with a thorough step-by-step guide.

Developer profile skeleton
a developer thinking

Overview

Implementing Firebase Authentication with role-based user management means setting up the basics for users to sign up and sign in. After that, you'll integrate role assignments by using either Firestore or Realtime Database. Custom claims for roles like admin, user, and moderator need to be created, and it's vital to manage them server-side with Firebase Functions to keep everything secure. This setup lets you control what parts of your app users can access based on their roles, boosting functionality and keeping things safe.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to implement Firebase Authentication with role-based user management?

Step 1: Set Up Firebase Project

  • Head over to the Firebase Console.
  • Either start a new project or pick one you already have.
  • In the Firebase Console, go to Authentication and turn on the sign-in methods you want (like Email/Password, Google, etc.).

Step 2: Initialize Firebase in Your Application

  • First, install the Firebase SDK:
    ```shell
    npm install firebase
    ```

  • Then, set up Firebase in your app:
    ```javascript
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "firebase/app";
    import { getAuth } from "firebase/auth";
    import { getFirestore } from "firebase/firestore";

    // Your web app's Firebase configuration
    const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID"
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);
    const db = getFirestore(app);
    ```

Step 3: Create Firestore Rules for Role-Based Access

  • Go to Firestore Database in the Firebase Console.
  • Click on Rules and set up rules to control access based on user roles:
    ```plaintext
    service cloud.firestore {
    match /databases/{database}/documents {
    match /{document=**} {
    allow read, write: if request.auth != null &&
    get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "admin";
    }
    }
    }
    ```

Step 4: Set Up User Authentication

  • Implement user registration and login:
    ```javascript
    import { createUserWithEmailAndPassword, signInWithEmailAndPassword } from "firebase/auth";

    // Register new user
    const registerUser = async (email, password) => {
    try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    const user = userCredential.user;
    // Initialize user role in Firestore
    await setDoc(doc(db, "users", user.uid), {
    email: user.email,
    role: "user" // Default role
    });
    console.log("User registered:", user);
    } catch (error) {
    console.error("Error registering user:", error);
    }
    };

    // Log in existing user
    const loginUser = async (email, password) => {
    try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    console.log("User logged in:", userCredential.user);
    } catch (error) {
    console.error("Error logging in user:", error);
    }
    };
    ```

Step 5: Implement Role-Based UI

  • Show different UI components based on the user role:
    ```javascript
    import { onAuthStateChanged } from "firebase/auth";
    import { doc, getDoc } from "firebase/firestore";

    const checkUserRole = async (user) => {
    if (user) {
    const userDoc = await getDoc(doc(db, "users", user.uid));
    const userRole = userDoc.data().role;
    if (userRole === "admin") {
    // Show Admin UI
    showAdminUI();
    } else {
    // Show User UI
    showUserUI();
    }
    } else {
    // Show Public UI
    showPublicUI();
    }
    };

    onAuthStateChanged(auth, (user) => {
    checkUserRole(user);
    });

    function showAdminUI() {
    console.log("Admin UI");
    }
    function showUserUI() {
    console.log("User UI");
    }
    function showPublicUI() {
    console.log("Public UI");
    }
    ```

Step 6: Update User Roles

  • To change user roles, use Firestore and a secure backend function, or handle it directly in Firestore:
    ```javascript
    import { doc, updateDoc } from "firebase/firestore";

    const updateUserRole = async (userId, newRole) => {
    try {
    await updateDoc(doc(db, "users", userId), {
    role: newRole
    });
    console.log("User role updated");
    } catch (error) {
    console.error("Error updating user role:", error);
    }
    };

    // Example usage:
    updateUserRole("userUID123", "admin");
    ```

Step 7: Secure Functions with Role-Based Access

  • Use Firebase Cloud Functions to add server-side logic with role checks:
    ```javascript
    const { getAuth } = require('firebase-admin/auth');
    const { getFirestore } = require('firebase-admin/firestore');
    const functions = require('firebase-functions');
    const admin = require('firebase-admin');

    admin.initializeApp();

    exports.secureFunction = functions.https.onCall(async (data, context) => {
    if (!context.auth) {
    throw new functions.https.HttpsError('unauthenticated', 'User is not authenticated');
    }

    const userDoc = await getFirestore().collection('users').doc(context.auth.uid).get();
    const userRole = userDoc.data().role;

    if (userRole !== 'admin') {
    throw new functions.https.HttpsError('permission-denied', 'User does not have the necessary permissions');
    }

    // Function logic for admin users
    return { message: "This is a secure function" };
    });
    ```

By following these steps, Firebase Authentication with role-based user management can be implemented effectively.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.