Multi-Tenant with firebase

1

I'm starting a web system and it will be multi-tenant, I want to do using the firebase database, but I have not yet come up with a way to associate a user with a tenant (company) so he only has access to that company's tree. 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 can I add custom information to a user as the company ID so that he has access only to what he has permission.

    
asked by anonymous 31.03.2018 / 01:13

1 answer

0

I would recommend that you have 2 root nodes: Business and Users. Then when you have a new tenant (a company), you generate a new ID on the Companies node. And put all the data from that company on 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 define 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);
        });
});
    
01.04.2018 / 01:10