How to reference predefined database entries in source code

At our company, we discussed how to access some database records in our Java source code. The situation is as follows:

The java web application is connected to the MySQL database, which is configured using SQL script, JPA / Hibernate is used for ORM. In this script, we insert 3 roles into the "roles" table (that is, the roles that the user can have in the web application, that is, the user table has a foreign key in the role table). Roles have predefined primary keys / identifiers (BIGINT) and names (VARCHAR), as specified in the SQL script. Roles are not used for security infrastructure, but for business logic. At the moment, it looks something like this:

if(user.getRole.getId()==1) {
     // user is in role A
} else if(user.getRole().getId()==2) {
    // user is in role B
} ...

Since the roles must be known by the source code at compile time (since the logic depends on them), we must verify that the user has specific roles. The question is how to do this. We discussed:

a) best check by identifier or by name b) using String / Long or Enums constants to verify equality

a) I would prefer to check the identifier (since it is unlikely to change when inserting identifiers when setting up the database using a script), the role name is likely to change during the life of the application.

to b) , / Enums. . , , , , . , , .

?

+4
2

, .

, id:

public enum Role {
     ROLE1(1), ROLE2(2), ROLE(3);

     private final int id;
     private Role(int id) {
         this.id=id;
     }

     public int getId() {
          return this.id;
     }
}

(, ), . .

+4

, @flo . : , , , , .

@flo , , , , - , .

, , , , .

:

public class Role {
    private Integer roleId = null;
    private String roleName = null;

    private static Map<Integer, String> roleMap = null;
    ...
}

roleMap , , - Spring Beans (* ), , .

: ?

, , . , :

, , . , () .

Role

private Map<String, Set<String>> roleActionMap = null;

public boolean isAuthorized(String action, String role){
    boolean result = false;

    Set<String> actions = getActionSet(role);
    if(actions != null)
        result = actions.contains(action);

    return result;
}

-, . , , , .

, , , , , .

, , , ,

Thread.currentThread().getStackTrace()[1].getMethodName();

, . ( , , , , )

, , SpringSecurity - , -, , , .

, .

+2

Source: https://habr.com/ru/post/1611876/


All Articles