User with more than one profile

1

In the system business rule that I am working on, a user can have more than one profile. The profiles are: administrator, appraiser and responsible.

For example: So-and-so can be both administrator and appraiser at the same time.

My question is how to map this? I had some ideas but I do not know if this is the best way to do it.

An idea: Create a column in the database for each profile, for example: is_admin, is_responsible, and is_appraiser, and set 0 or 1, according to the user profile.

Another idea: Have a column in the database, to store only one number that will be generated according to the profile.

Exemplo:
Administrador = 0 
Avaliador = 1
Responsável = 2
Administrador + Avaliador = 4

These are ideas I had, but I do not know the right way to store it.

    
asked by anonymous 27.07.2018 / 04:20

2 answers

1

If they are static profiles - there is no possibility of creating new profiles with the application time - you can define them through an enumeration with values being powers of 2.

enum Perfis {
    Administrador = 1;
    Avaliador = 2;
    Responsavel = 4; 
}

And, to persist the value in the database, create a column of integer type. So, to define that a user has more than one profile, you can use the binary operator | :

john.perfil = Perfis.Administrador | Perfis.Avaliador;

In this case, the value of john.perfil will be 3, because 1 | 2 = 3. And if it is necessary to check if john has a specific profile, just use the binary operator & :

if (john.perfil & Perfis.Administrador) {
    // John é um administrador
}

This logic is secure in relation to ensuring that the user has a certain profile because since the values in the enumeration are powers of 2, the only combination that results in 3 is 1 | 2.

Analyzing at low level, you will basically have a binary value - in this example, size 3: 000 - where each profile is related to a bit. Profile Administrator would be bit 0, Evaluator bit 1 and Responsible bit 3. If the user has a certain profile, just set the bit to 1.

I've commented on this Python technique in this question: What does the "|=" operator in Python mean? ">

    
27.07.2018 / 14:39
1

My suggestion is to create a usuario table, a perfil table, and a usuario_perfil table.

The user can have more than one profile and a profile can belong to more than one user, characterizing a N-N relationship. So you'll need an intermediate table, usuario_perfil .

Example of registration:

-- tabela usuario
id | nome
1  | Gustavo
2  | Augusto

-- tabela usuario_perfil
usuario_id | perfil_id
1          | 1
1          | 2
2          | 3
2          | 1

-- tabela perfil
id | nome
1  | Administrador
2  | Avaliador
3  | Responsável

It is interesting to create a unique constraint in the usuario_perfil table in the usuario_id and perfil_id fields to ensure that a user is not associated more than once with the same profile

    
27.07.2018 / 14:49