Multi-tenant with firebase

Asked

Viewed 133 times

1

I’m starting a web system and it will be multi-tenant, I want to do using the firebase database, but not yet I found a way to associate a user to a tenant (company) so that he has access only to the tree of that company. I use the following method to create a user and authenticate it:

// Criar novo usuário
createUserButton.addEventListener('click', function () {
firebase
    .auth()
    .createUserWithEmailAndPassword(emailInput.value, passwordInput.value, passwordId.value)
    .then(function () {
        alert('Bem vindo ' + emailInput.value);
    })
    .catch(function (error) {
        console.error(error.code);
        console.error(error.message);
    });
});



// Autenticar com E-mail e Senha
authEmailPassButton.addEventListener('click', function () {
firebase
    .auth()
    .signInWithEmailAndPassword(emailInput.value, passwordInput.value)
    .then(function (result) {
        console.log(result);
        displayName.innerText = 'Bem vindo, ' + emailInput.value;
        alert('Autenticado ' + emailInput.value);
    })
    .catch(function (error) {
        console.error(error.code);
        console.error(error.message);            
    });
});

Now my question is how do I add personalized information to a user like the company ID so that they only have access to what they are allowed to do.

1 answer

0


I would recommend that you have 2 nodes: Business and Users. Then when you have a new tenant (a company), you generate a new ID at the Companies node. And you put all the data of that company at that node. Your database would look something like this:

{
    "empresas":{
        "empresaX":{
            //Todos dados da empresa
        },
        "empresaY":{
            //Dados da outra empresa
        }
    },
    "usuarios":{
        "usuario1":{
            "nome":"Rosário",
            "empresa":"empresaX"
        },
        "usuario2":{
            "nome":"Dhouglas",
            "empresa":"empresaY"
        }
    }
}

So, to set the rule, you would:

{
    "rules":{
        "empresas":{
            "$idEmpresa":{
                ".read":"root.child('usuarios').child(auth.uid).child('empresa').val() == $idEmpresa",
                ".write":"root.child('usuarios').child(auth.uid).child('empresa').val() == $idEmpresa"
            }
        },
        "usuarios":{
            "$uid":{
                ".read":"$uid == auth.uid",
                ".write":"$uid == auth.uid",
            }
        }
    }
}

And to connect the user to the company:

createUserButton.addEventListener('click', function () {
    firebase
        .auth()
        .createUserWithEmailAndPassword(emailInput.value, passwordInput.value)
        .then(function () {
            alert('Bem vindo ' + emailInput.value);
            var userLogado = firebase.auth().currentUser; //Pegar o usuario que fez login
            var noUsuarios = firebase.database().ref('usuarios');  //Aceder ao nó usuários da BD
            noUsuarios.child(userLogado.uid).setValue({        //Guardar os dados desse usuário, usando o uid como chave
                email: userLogado.email,
                empresa: "Empresa XYZ",
                cpf: "CPF aqui"
            });
        })     
        .catch(function (error) {
            console.error(error.code);
            console.error(error.message);
        });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.