Home > Net >  Firebase Role Managment
Firebase Role Managment

Time:10-26

I am developing a web platform using Vue.js Firebase. I would like to implement user role assignment so that I can effectively manage Firebase rules. Users can subscribe to this platform using 3 different forms placed in 3 different views. Based on where the user signs up, they will be assigned a certain role.

Once the user has been created, using Firebase Authentication, I'd like to create a document with the following anatomy:

enter image description here

The '/ private' collection must contain other documents and the '/ access' document must contain other fields. The main point is that the user {$ uid} will not be able to modify the entire document assigned to him, but only a part. What is the best way to implement this?

Thanks in advance.

CodePudding user response:

As discussed in the comments above, you can adapt the code contained in the "How to create an Admin module for managing Firebase users access and roles" article.

In your case the users "can register on the platform freely (like Facebook for example)" so you don't need to check that the Callable Cloud function caller is an admin.

Here is the adapted code for the Cloud Function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const FieldValue = require('firebase-admin').firestore.FieldValue;

admin.initializeApp();



class InvalidRoleError extends Error {
    constructor(message) {
        super(message);
        this.message = message;
        this.type = 'InvalidRoleError';
    }
}

function roleIsValid(role) {
    const validRoles = ['editor', 'author']; //To be adapted with your own list of roles
    return validRoles.includes(role);
}

exports.createUser = functions.https.onCall(async (data, context) => {

    try {

        //Checking that the new user role is valid
        const role = data.role;
        if (!roleIsValid(role)) {
            throw new InvalidRoleError('The "'   role   '" role is not a valid role');
        }


        const userCreationRequest = {
            userDetails: data,
            status: 'Pending',
            createdOn: FieldValue.serverTimestamp()
        }

        const userCreationRequestRef = await admin.firestore().collection("userCreationRequests").add(userCreationRequest);


        const newUser = {
            email: data.email,
            emailVerified: false,
            password: data.password,
            displayName: data.firstName   ' '   data.lastName,
            disabled: false
        }

        const userRecord = await admin
            .auth()
            .createUser(newUser);

        const userId = userRecord.uid;

        const claims = {};
        claims[role] = true;

        await admin.auth().setCustomUserClaims(userId, claims);

        await admin.firestore().collection("users").doc(userId).set(data);

        await userCreationRequestRef.update({ status: 'Treated' });

        return { result: 'The new user has been successfully created.' };


    } catch (error) {

        if (error.type === 'InvalidRoleError') {
            throw new functions.https.HttpsError('failed-precondition', error.message);
        } else {
            throw new functions.https.HttpsError('internal', error.message);
        }

    }

});
  • Related